Statistics
| Branch: | Tag: | Revision:

amiro-lld / drivers / DW1000 / v2 / decadriver / deca_device.c @ 1304b12b

History | View | Annotate | Download (142.18 KB)

1
/*! ------------------------------------------------------------------------------------------------------------------
2
 * @file    deca_device.c
3
 * @brief   Decawave device configuration and control functions
4
 *
5
 * @attention
6
 *
7
 * Copyright 2013 (c) Decawave Ltd, Dublin, Ireland.
8
 *
9
 * All rights reserved.
10
 *
11
 */
12

    
13
#include <assert.h>
14
#include <stdlib.h>
15

    
16
#include "deca_types.h"
17
#include "deca_param_types.h"
18
#include "deca_regs.h"
19
#include "deca_device_api.h"
20

    
21
// Defines for enable_clocks function
22
#define FORCE_SYS_XTI  0
23
#define ENABLE_ALL_SEQ 1
24
#define FORCE_SYS_PLL  2
25
#define READ_ACC_ON    7
26
#define READ_ACC_OFF   8
27
#define FORCE_OTP_ON   11
28
#define FORCE_OTP_OFF  12
29
#define FORCE_TX_PLL   13
30
#define FORCE_LDE      14
31

    
32
// Defines for ACK request bitmask in DATA and MAC COMMAND frame control (first byte) - Used to detect AAT bit wrongly set.
33
#define FCTRL_ACK_REQ_MASK 0x20
34
// Frame control maximum length in bytes.
35
#define FCTRL_LEN_MAX 2
36

    
37
// #define DWT_API_ERROR_CHECK     // define so API checks config input parameters
38

    
39
// -------------------------------------------------------------------------------------------------------------------
40
//
41
// Internal functions for controlling and configuring the device
42
//
43
// -------------------------------------------------------------------------------------------------------------------
44

    
45
// Enable and Configure specified clocks
46
void _dwt_enableclocks(int clocks) ;
47
// Configure the ucode (FP algorithm) parameters
48
void _dwt_configlde(int prf);
49
// Load ucode from OTP/ROM
50
void _dwt_loaducodefromrom(void);
51
// Read non-volatile memory
52
uint32 _dwt_otpread(uint16 address);
53
// Program the non-volatile memory
54
uint32 _dwt_otpprogword32(uint32 data, uint16 address);
55
// Upload the device configuration into always on memory
56
void _dwt_aonarrayupload(void);
57
// -------------------------------------------------------------------------------------------------------------------
58

    
59
/*!
60
 * Static data for DW1000 DecaWave Transceiver control
61
 */
62

    
63
// -------------------------------------------------------------------------------------------------------------------
64
// Structure to hold device data
65
typedef struct
66
{
67
    uint32      partID ;            // IC Part ID - read during initialisation
68
    uint32      lotID ;             // IC Lot ID - read during initialisation
69
    uint8       vBatP ;             // IC V bat read during production and stored in OTP (Vmeas @ 3V3)
70
    uint8       tempP ;             // IC V temp read during production and stored in OTP (Tmeas @ 23C)
71
    uint8       longFrames ;        // Flag in non-standard long frame mode
72
    uint8       otprev ;            // OTP revision number (read during initialisation)
73
    uint32      txFCTRL ;           // Keep TX_FCTRL register config
74
    uint32      sysCFGreg ;         // Local copy of system config register
75
    uint8       dblbuffon;          // Double RX buffer mode flag
76
    uint8       wait4resp ;         // wait4response was set with last TX start command
77
    uint16      sleep_mode;         // Used for automatic reloading of LDO tune and microcode at wake-up
78
    uint16      otp_mask ;          // Local copy of the OTP mask used in dwt_initialise call
79
    dwt_cb_data_t cbData;           // Callback data structure
80
    dwt_cb_t    cbTxDone;           // Callback for TX confirmation event
81
    dwt_cb_t    cbRxOk;             // Callback for RX good frame event
82
    dwt_cb_t    cbRxTo;             // Callback for RX timeout events
83
    dwt_cb_t    cbRxErr;            // Callback for RX error events
84
} dwt_local_data_t ;
85

    
86
static dwt_local_data_t dw1000local[DWT_NUM_DW_DEV] ; // Static local device data, can be an array to support multiple DW1000 testing applications/platforms
87
static dwt_local_data_t *pdw1000local = dw1000local ; // Static local data structure pointer
88

    
89

    
90
/*! ------------------------------------------------------------------------------------------------------------------
91
 * @fn dwt_apiversion()
92
 *
93
 * @brief This function returns the version of the API as defined by DW1000_DRIVER_VERSION
94
 *
95
 * input parameters
96
 *
97
 * output parameters
98
 *
99
 * returns version (DW1000_DRIVER_VERSION)
100
 */
101
int32 dwt_apiversion(void)
102
{
103
    return DW1000_DRIVER_VERSION ;
104
}
105

    
106
/*! ------------------------------------------------------------------------------------------------------------------
107
 * @fn dwt_setlocaldataptr()
108
 *
109
 * @brief This function sets the local data structure pointer to point to the element in the local array as given by the index.
110
 *
111
 * input parameters
112
 * @param index    - selects the array element to point to. Must be within the array bounds, i.e. < DWT_NUM_DW_DEV
113
 *
114
 * output parameters
115
 *
116
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
117
 */
118
int dwt_setlocaldataptr(unsigned int index)
119
{
120
    // Check the index is within the array bounds
121
    if (DWT_NUM_DW_DEV <= index) // return error if index outside the array bounds
122
    {
123
        return DWT_ERROR ;
124
    }
125

    
126
    pdw1000local = &dw1000local[index];
127

    
128
    return DWT_SUCCESS ;
129
}
130

    
131
/*! ------------------------------------------------------------------------------------------------------------------
132
 * @fn dwt_initialise()
133
 *
134
 * @brief This function initiates communications with the DW1000 transceiver
135
 * and reads its DEV_ID register (address 0x00) to verify the IC is one supported
136
 * by this software (e.g. DW1000 32-bit device ID value is 0xDECA0130).  Then it
137
 * does any initial once only device configurations needed for its use and initialises
138
 * as necessary any static data items belonging to this low-level driver.
139
 *
140
 * This function does not need to be called after DW1000 device is woken up from DEEPSLEEP,
141
 * the device will preserve register values e.g. LDO, UCODE, XTAL. However if needed this
142
 * function can be called to initialise internal structure  dw1000local[] if it has not been preserved
143
 * (e.g. if micro was in sleep and its RAM data (containing dw1000local structure was not preserved during sleep)
144
 *
145
 * NOTES:
146
 * 1. When DW1000 is powered on this function needs to be run before dwt_configuresleep,
147
 *    also the SPI frequency has to be < 3MHz
148
 * 2. It reads and applies LDO tune and crystal trim values from OTP memory
149
 * 3. If accurate RX timestamping is needed microcode/LDE must be loaded
150
 *
151
 * input parameters
152
 * @param config    -   specifies what configuration to load
153
 *                  DWT_LOADNONE         0x00 - do not load any values from OTP memory
154
 *                  DWT_LOADUCODE        0x01 - load the LDE microcode from ROM - enable accurate RX timestamp
155
 *                  DWT_DW_WAKE_UP       0x02 - just initialise dw1000local[] values (e.g. DW1000 has woken up)
156
 *                  DWT_DW_WUP_NO_UCODE  0x04 - if microcode/LDE algorithm has not already been loaded (on power up) e.g. when LDE is not used
157
 *                  DWT_READ_OTP_PID     0x10 - read part ID from OTP
158
 *                  DWT_READ_OTP_LID     0x20 - read lot ID from OTP
159
 *                  DWT_READ_OTP_BAT     0x40 - read ref voltage from OTP
160
 *                  DWT_READ_OTP_TMP     0x80 - read ref temperature from OTP
161
 * output parameters
162
 *
163
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
164
 */
165
// OTP addresses definitions
166
#define LDOTUNE_ADDRESS (0x04)
167
#define PARTID_ADDRESS (0x06)
168
#define LOTID_ADDRESS  (0x07)
169
#define VBAT_ADDRESS   (0x08)
170
#define VTEMP_ADDRESS  (0x09)
171
#define XTRIM_ADDRESS  (0x1E)
172

    
173
int dwt_initialise(int config)
174
{
175
    uint16 otp_xtaltrim_and_rev = 0;
176
    uint32 ldo_tune = 0;
177

    
178
    pdw1000local->dblbuffon = 0; // - set to 0 - meaning double buffer mode is off by default
179
    pdw1000local->wait4resp = 0; // - set to 0 - meaning wait for response not active
180
    pdw1000local->sleep_mode = 0; // - set to 0 - meaning sleep mode has not been configured
181

    
182
    pdw1000local->cbTxDone = NULL;
183
    pdw1000local->cbRxOk = NULL;
184
    pdw1000local->cbRxTo = NULL;
185
    pdw1000local->cbRxErr = NULL;
186

    
187
#if DWT_API_ERROR_CHECK
188
    pdw1000local->otp_mask = config ; // Save the READ_OTP config mask
189
#endif
190

    
191
    // Read and validate device ID, return -1 if not recognised
192
    if (DWT_DEVICE_ID != dwt_readdevid()) // MP IC ONLY (i.e. DW1000) FOR THIS CODE
193
    {
194
        return DWT_ERROR ;
195
    }
196

    
197
    if(!(DWT_DW_WAKE_UP & config)) // Don't reset the device if DWT_DW_WAKE_UP bit is set, e.g. when calling this API after wake up
198
    {
199
        dwt_softreset(); // Make sure the device is completely reset before starting initialisation
200
    }
201

    
202
    if(!((DWT_DW_WAKE_UP & config) && ((DWT_READ_OTP_TMP | DWT_READ_OTP_BAT | DWT_READ_OTP_LID | DWT_READ_OTP_PID | DWT_DW_WUP_RD_OTPREV)& config)))
203
    {
204
        _dwt_enableclocks(FORCE_SYS_XTI); // NOTE: set system clock to XTI - this is necessary to make sure the values read by _dwt_otpread are reliable
205
    }                                  // when not reading from OTP, clocks don't need to change.
206

    
207
    // Configure the CPLL lock detect
208
    dwt_write8bitoffsetreg(EXT_SYNC_ID, EC_CTRL_OFFSET, EC_CTRL_PLLLCK);
209

    
210
    // When DW1000 IC is initialised from power up, then the LDO value should be kicked from OTP, otherwise if this API is called after
211
    // DW1000 IC has been woken up (DWT_DW_WAKE_UP bit is set) this can be skipped as LDO would have already been automatically
212
    // kicked/loaded on wake up
213
    if(!(DWT_DW_WAKE_UP & config))
214
    {
215
        // Load LDO tune from OTP and kick it if there is a value actually programmed.
216
        ldo_tune = _dwt_otpread(LDOTUNE_ADDRESS);
217
        if((ldo_tune & 0xFF) != 0)
218
        {
219
            // Kick LDO tune
220
            dwt_write8bitoffsetreg(OTP_IF_ID, OTP_SF, OTP_SF_LDO_KICK); // Set load LDO kick bit
221
            pdw1000local->sleep_mode |= AON_WCFG_ONW_LLDO; // LDO tune must be kicked at wake-up
222
        }
223
    }
224
    else
225
    {   //if LDOTUNE reg contains value different from default it means it was kicked from OTP and thus set AON_WCFG_ONW_LLDO.
226
        if(dwt_read32bitoffsetreg(RF_CONF_ID, LDOTUNE) != LDOTUNE_DEFAULT)
227
            pdw1000local->sleep_mode |= AON_WCFG_ONW_LLDO;
228
    }
229

    
230
    if((!(DWT_DW_WAKE_UP & config)) || ((DWT_DW_WAKE_UP & config) && (DWT_DW_WUP_RD_OTPREV & config)))
231
    {
232
        // Read OTP revision number
233
        otp_xtaltrim_and_rev = _dwt_otpread(XTRIM_ADDRESS) & 0xffff;        // Read 32 bit value, XTAL trim val is in low octet-0 (5 bits)
234
        pdw1000local->otprev = (otp_xtaltrim_and_rev >> 8) & 0xff;          // OTP revision is the next byte
235
    }
236
    else
237
        pdw1000local->otprev = 0; // If OTP valuse are not used, if this API is called after DW1000 IC has been woken up
238
                                  // (DWT_DW_WAKE_UP bit is set), set otprev to 0
239

    
240
    if(!(DWT_DW_WAKE_UP & config))
241
    {
242
        // XTAL trim value is set in OTP for DW1000 module and EVK/TREK boards but that might not be the case in a custom design
243
        if ((otp_xtaltrim_and_rev & 0x1F) == 0) // A value of 0 means that the crystal has not been trimmed
244
        {
245
            otp_xtaltrim_and_rev = FS_XTALT_MIDRANGE ; // Set to mid-range if no calibration value inside
246
        }
247
        // Configure XTAL trim
248
        dwt_setxtaltrim((uint8)otp_xtaltrim_and_rev);
249
    }
250

    
251
    if(DWT_READ_OTP_PID & config)
252
    {
253
        // Load Part from OTP
254
        pdw1000local->partID = _dwt_otpread(PARTID_ADDRESS);
255
    }
256
    else
257
    {
258
        pdw1000local->partID = 0;
259
    }
260

    
261
    if(DWT_READ_OTP_LID & config)
262
    {
263
        // Load Lot ID from OTP
264
        pdw1000local->lotID = _dwt_otpread(LOTID_ADDRESS);
265
    }
266
    else
267
    {
268
        pdw1000local->lotID = 0;
269
    }
270

    
271
    if(DWT_READ_OTP_BAT & config)
272
    {
273
        // Load VBAT from OTP
274
        pdw1000local->vBatP = _dwt_otpread(VBAT_ADDRESS) & 0xff;
275
    }
276
    else
277
    {
278
        pdw1000local->vBatP = 0;
279
    }
280

    
281
    if(DWT_READ_OTP_TMP & config)
282
    {
283
        // Load TEMP from OTP
284
        pdw1000local->tempP = _dwt_otpread(VTEMP_ADDRESS) & 0xff;
285
    }
286
    else
287
    {
288
        pdw1000local->tempP = 0;
289
    }
290

    
291
    // Load leading edge detect code (LDE/microcode)
292
    if(!(DWT_DW_WAKE_UP & config))
293
    {
294
        if(DWT_LOADUCODE & config)
295
        {
296
            _dwt_loaducodefromrom();
297
            pdw1000local->sleep_mode |= AON_WCFG_ONW_LLDE; // microcode must be loaded at wake-up if loaded on initialisation
298
        }
299
        else // Should disable the LDERUN bit enable if LDE has not been loaded
300
        {
301
            uint16 rega = dwt_read16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET+1) ;
302
            rega &= 0xFDFF ; // Clear LDERUN bit
303
            dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET+1, rega) ;
304
        }
305
    }
306
    else //if DWT_DW_WUP_NO_UCODE is set then assume that the UCODE was loaded from ROM (i.e. DWT_LOADUCODE was set on power up),
307
    {     //thus set AON_WCFG_ONW_LLDE, otherwise don't set the AON_WCFG_ONW_LLDE bit in the sleep_mode configuration
308
        if((DWT_DW_WUP_NO_UCODE & config) == 0)
309
        {
310
            pdw1000local->sleep_mode |= AON_WCFG_ONW_LLDE;
311
        }
312
    }
313

    
314
    _dwt_enableclocks(ENABLE_ALL_SEQ); // Enable clocks for sequencing
315

    
316
    // The 3 bits in AON CFG1 register must be cleared to ensure proper operation of the DW1000 in DEEPSLEEP mode.
317
    dwt_write8bitoffsetreg(AON_ID, AON_CFG1_OFFSET, 0x00);
318

    
319
    // Read system register / store local copy
320
    pdw1000local->sysCFGreg = dwt_read32bitreg(SYS_CFG_ID) ; // Read sysconfig register
321
    pdw1000local->longFrames = (pdw1000local->sysCFGreg & SYS_CFG_PHR_MODE_11) >> SYS_CFG_PHR_MODE_SHFT ; //configure longFrames
322

    
323
    pdw1000local->txFCTRL = dwt_read32bitreg(TX_FCTRL_ID) ;
324

    
325
    return DWT_SUCCESS ;
326

    
327
} // end dwt_initialise()
328

    
329
/*! ------------------------------------------------------------------------------------------------------------------
330
 * @fn dwt_otprevision()
331
 *
332
 * @brief This is used to return the read OTP revision
333
 *
334
 * NOTE: dwt_initialise() must be called prior to this function so that it can return a relevant value.
335
 *
336
 * input parameters
337
 *
338
 * output parameters
339
 *
340
 * returns the read OTP revision value
341
 */
342
uint8 dwt_otprevision(void)
343
{
344
    return pdw1000local->otprev ;
345
}
346

    
347
/*! ------------------------------------------------------------------------------------------------------------------
348
 * @fn dwt_setfinegraintxseq()
349
 *
350
 * @brief This function enables/disables the fine grain TX sequencing (enabled by default).
351
 *
352
 * input parameters
353
 * @param enable - 1 to enable fine grain TX sequencing, 0 to disable it.
354
 *
355
 * output parameters none
356
 *
357
 * no return value
358
 */
359
void dwt_setfinegraintxseq(int enable)
360
{
361
    if (enable)
362
    {
363
        dwt_write16bitoffsetreg(PMSC_ID, PMSC_TXFINESEQ_OFFSET, PMSC_TXFINESEQ_ENABLE);
364
    }
365
    else
366
    {
367
        dwt_write16bitoffsetreg(PMSC_ID, PMSC_TXFINESEQ_OFFSET, PMSC_TXFINESEQ_DISABLE);
368
    }
369
}
370

    
371
/*! ------------------------------------------------------------------------------------------------------------------
372
 * @fn dwt_setlnapamode()
373
 *
374
 * @brief This is used to enable GPIO for external LNA or PA functionality - HW dependent, consult the DW1000 User Manual.
375
 *        This can also be used for debug as enabling TX and RX GPIOs is quite handy to monitor DW1000's activity.
376
 *
377
 * NOTE: Enabling PA functionality requires that fine grain TX sequencing is deactivated. This can be done using
378
 *       dwt_setfinegraintxseq().
379
 *
380
 * input parameters
381
 * @param lna_pa - bit field: bit 0 if set will enable LNA functionality,
382
 *                          : bit 1 if set will enable PA functionality,
383
 *                          : to disable LNA/PA set the bits to 0
384
 *
385
 * no return value
386
 */
387
void dwt_setlnapamode(int lna_pa)
388
{
389
    uint32 gpio_mode = dwt_read32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET);
390
    gpio_mode &= ~(GPIO_MSGP4_MASK | GPIO_MSGP5_MASK | GPIO_MSGP6_MASK);
391
    if (lna_pa & DWT_LNA_ENABLE)
392
    {
393
        gpio_mode |= GPIO_PIN6_EXTRXE;
394
    }
395
    if (lna_pa & DWT_PA_ENABLE)
396
    {
397
        gpio_mode |= (GPIO_PIN5_EXTTXE | GPIO_PIN4_EXTPA);
398
    }
399
    dwt_write32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET, gpio_mode);
400
}
401

    
402
/*! ------------------------------------------------------------------------------------------------------------------
403
 * @fn dwt_enablegpioclocks()
404
 *
405
 * @brief This is used to enable GPIO clocks. The clocks are needed to ensure correct GPIO operation
406
 *
407
 * input parameters
408
 *
409
 * output parameters
410
 *
411
 * no return value
412
 */
413
void dwt_enablegpioclocks(void)
414
{
415
    uint32 pmsc_clock_ctrl = dwt_read32bitreg(PMSC_ID);
416
    dwt_write32bitreg(PMSC_ID, pmsc_clock_ctrl | PMSC_CTRL0_GPCE | PMSC_CTRL0_GPRN) ;
417
}
418

    
419
/*! ------------------------------------------------------------------------------------------------------------------
420
 * @fn dwt_setgpiodirection()
421
 *
422
 * @brief This is used to set GPIO direction as an input (1) or output (0)
423
 *
424
 * input parameters
425
 * @param gpioNum    -   this is the GPIO to configure - see GxM0... GxM8 in the deca_regs.h file
426
 * @param direction  -   this sets the GPIO direction - see GxP0... GxP8 in the deca_regs.h file
427
 *
428
 * output parameters
429
 *
430
 * no return value
431
 */
432
void dwt_setgpiodirection(uint32 gpioNum, uint32 direction)
433
{
434
    uint8 buf[GPIO_DIR_LEN];
435
    uint32 command = direction | gpioNum;
436

    
437
    buf[0] = command & 0xff;
438
    buf[1] = (command >> 8) & 0xff;
439
    buf[2] = (command >> 16) & 0xff;
440

    
441
    dwt_writetodevice(GPIO_CTRL_ID, GPIO_DIR_OFFSET, GPIO_DIR_LEN, buf);
442
}
443

    
444
/*! ------------------------------------------------------------------------------------------------------------------
445
 * @fn dwt_setgpiovalue()
446
 *
447
 * @brief This is used to set GPIO value as (1) or (0) only applies if the GPIO is configured as output
448
 *
449
 * input parameters
450
 * @param gpioNum    -   this is the GPIO to configure - see DWT_GxP0... DWT_GxP8
451
 * @param value  -   this sets the GPIO value - see DWT_GxP0... DWT_GxP8
452
 *
453
 * output parameters
454
 *
455
 * no return value
456
 */
457
void dwt_setgpiovalue(uint32 gpioNum, uint32 value)
458
{
459
    uint8 buf[GPIO_DOUT_LEN];
460
    uint32 command = value | gpioNum;
461

    
462
    buf[0] = command & 0xff;
463
    buf[1] = (command >> 8) & 0xff;
464
    buf[2] = (command >> 16) & 0xff;
465

    
466
    dwt_writetodevice(GPIO_CTRL_ID, GPIO_DOUT_OFFSET, GPIO_DOUT_LEN, buf);
467
}
468

    
469
/*! ------------------------------------------------------------------------------------------------------------------
470
 * @fn dwt_getgpiovalue()
471
 *
472
 * @brief This is used to return 1 or 0 depending if the depending if the GPIO is high or low, only one GPIO should
473
 *        be tested at a time
474
 *
475
 * input parameters
476
 * @param gpioNum    -   this is the GPIO to configure - see DWT_GxP0... DWT_GxP8
477
 *
478
 * output parameters
479
 *
480
 * return int (1 or 0)
481
 */
482
int dwt_getgpiovalue(uint32 gpioNum)
483
{
484
    return ((dwt_read32bitoffsetreg(GPIO_CTRL_ID, GPIO_RAW_OFFSET) & gpioNum)? 1 : 0);
485
}
486

    
487

    
488
/*! ------------------------------------------------------------------------------------------------------------------
489
 * @fn dwt_geticrefvolt()
490
 *
491
 * @brief This is used to return the read V measured @ 3.3 V value recorded in OTP address 0x8 (VBAT_ADDRESS)
492
 *
493
 * NOTE: dwt_initialise() must be called prior to this function so that it can return a relevant value.
494
 *
495
 * input parameters
496
 *
497
 * output parameters
498
 *
499
 * returns the 8 bit V bat value as programmed in the factory
500
 */
501
uint8 dwt_geticrefvolt(void)
502
{
503
#ifdef DWT_API_ERROR_CHECK
504
    assert(pdw1000local->otp_mask & DWT_READ_OTP_BAT);
505
#endif
506
    return pdw1000local->vBatP;
507
}
508

    
509
/*! ------------------------------------------------------------------------------------------------------------------
510
 * @fn dwt_geticreftemp()
511
 *
512
 * @brief This is used to return the read T measured @ 23 C value recorded in OTP address 0x9 (VTEMP_ADDRESS)
513
 *
514
 * NOTE: dwt_initialise() must be called prior to this function so that it can return a relevant value.
515
 *
516
 * input parameters
517
 *
518
 * output parameters
519
 *
520
 * returns the 8 bit V temp value as programmed in the factory
521
 */
522
uint8 dwt_geticreftemp(void)
523
{
524
#ifdef DWT_API_ERROR_CHECK
525
    assert(pdw1000local->otp_mask & DWT_READ_OTP_TMP);
526
#endif
527
    return pdw1000local->tempP;
528
}
529

    
530
/*! ------------------------------------------------------------------------------------------------------------------
531
 * @fn dwt_getpartid()
532
 *
533
 * @brief This is used to return the read part ID (or chip ID) of the device
534
 *
535
 * NOTE: dwt_initialise() must be called prior to this function so that it can return a relevant value (stored in OTP).
536
 *
537
 * input parameters
538
 *
539
 * output parameters
540
 *
541
 * returns the 32 bit part ID (or chip ID) value as programmed in the factory
542
 */
543
uint32 dwt_getpartid(void)
544
{
545
#ifdef DWT_API_ERROR_CHECK
546
    assert(pdw1000local->otp_mask & DWT_READ_OTP_PID);
547
#endif
548

    
549
    return pdw1000local->partID;
550
}
551

    
552
/*! ------------------------------------------------------------------------------------------------------------------
553
 * @fn dwt_getlotid()
554
 *
555
 * @brief This is used to return the read lot ID of the device
556
 *
557
 * NOTE: dwt_initialise() must be called prior to this function so that it can return a relevant value.
558
 *
559
 * input parameters
560
 *
561
 * output parameters
562
 *
563
 * returns the 32 bit lot ID value as programmed in the factory
564
 */
565
uint32 dwt_getlotid(void)
566
{
567
#ifdef DWT_API_ERROR_CHECK
568
    assert(pdw1000local->otp_mask & DWT_READ_OTP_LID);
569
#endif
570

    
571
    return pdw1000local->lotID;
572
}
573

    
574
/*! ------------------------------------------------------------------------------------------------------------------
575
 * @fn dwt_readdevid()
576
 *
577
 * @brief This is used to return the read device type and revision information of the DW1000 device (MP part is 0xDECA0130)
578
 *
579
 * input parameters
580
 *
581
 * output parameters
582
 *
583
 * returns the read value which for DW1000 is 0xDECA0130
584
 */
585
uint32 dwt_readdevid(void)
586
{
587
    return dwt_read32bitoffsetreg(DEV_ID_ID,0);
588
}
589

    
590
/*! ------------------------------------------------------------------------------------------------------------------
591
 * @fn dwt_configuretxrf()
592
 *
593
 * @brief This function provides the API for the configuration of the TX spectrum
594
 * including the power and pulse generator delay. The input is a pointer to the data structure
595
 * of type dwt_txconfig_t that holds all the configurable items.
596
 *
597
 * input parameters
598
 * @param config    -   pointer to the txrf configuration structure, which contains the tx rf config data
599
 *
600
 * output parameters
601
 *
602
 * no return value
603
 */
604
void dwt_configuretxrf(dwt_txconfig_t *config)
605
{
606

    
607
    // Configure RF TX PG_DELAY
608
    dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGDELAY_OFFSET, config->PGdly);
609

    
610
    // Configure TX power
611
    dwt_write32bitreg(TX_POWER_ID, config->power);
612

    
613
}
614

    
615

    
616
/*! ------------------------------------------------------------------------------------------------------------------
617
 * @fn dwt_configurefor64plen()
618
 *  - Use default OPS table should be used with following register modifications:
619
 *    These modifications optimise the default OPS configuration further for 64 length preamble use case
620
 *
621
 * NOTE: These register settings are not preserved during SLEEP/DEEPSLEEP, thus they should be programmed again after wake up
622
 *
623
 * input parameters
624
 * @param prf
625
 *
626
 * output parameters
627
 *
628
 * no return value
629
 */
630
void dwt_configurefor64plen(int prf)
631
{
632
    dwt_write8bitoffsetreg(CRTR_ID, CRTR_GEAR_OFFSET, DEMOD_GEAR_64L);
633

    
634
    if(prf == DWT_PRF_16M)
635
    {
636
        dwt_write8bitoffsetreg(DRX_CONF_ID, DRX_TUNE2_OFFSET+2, DRX_TUNE2_UNCONF_SFD_TH_PRF16);
637
    }
638
    else
639
    {
640
        dwt_write8bitoffsetreg(DRX_CONF_ID, DRX_TUNE2_OFFSET+2, DRX_TUNE2_UNCONF_SFD_TH_PRF64);
641
    }
642
}
643

    
644

    
645
/*! ------------------------------------------------------------------------------------------------------------------
646
 * @fn dwt_configure()
647
 *
648
 * @brief This function provides the main API for the configuration of the
649
 * DW1000 and this low-level driver.  The input is a pointer to the data structure
650
 * of type dwt_config_t that holds all the configurable items.
651
 * The dwt_config_t structure shows which ones are supported
652
 *
653
 * input parameters
654
 * @param config    -   pointer to the configuration structure, which contains the device configuration data.
655
 *
656
 * output parameters
657
 *
658
 * no return value
659
 */
660
void dwt_configure(dwt_config_t *config)
661
{
662
    uint8 nsSfd_result  = 0;
663
    uint8 useDWnsSFD = 0;
664
    uint8 chan = config->chan ;
665
    uint32 regval ;
666
    uint16 reg16 = lde_replicaCoeff[config->rxCode];
667
    uint8 prfIndex = config->prf - DWT_PRF_16M;
668
    uint8 bw = ((chan == 4) || (chan == 7)) ? 1 : 0 ; // Select wide or narrow band
669

    
670
#ifdef DWT_API_ERROR_CHECK
671
    assert(config->dataRate <= DWT_BR_6M8);
672
    assert(config->rxPAC <= DWT_PAC64);
673
    assert((chan >= 1) && (chan <= 7) && (chan != 6));
674
    assert(((config->prf == DWT_PRF_64M) && (config->txCode >= 9) && (config->txCode <= 24))
675
           || ((config->prf == DWT_PRF_16M) && (config->txCode >= 1) && (config->txCode <= 8)));
676
    assert(((config->prf == DWT_PRF_64M) && (config->rxCode >= 9) && (config->rxCode <= 24))
677
           || ((config->prf == DWT_PRF_16M) && (config->rxCode >= 1) && (config->rxCode <= 8)));
678
    assert((config->txPreambLength == DWT_PLEN_64) || (config->txPreambLength == DWT_PLEN_128) || (config->txPreambLength == DWT_PLEN_256)
679
           || (config->txPreambLength == DWT_PLEN_512) || (config->txPreambLength == DWT_PLEN_1024) || (config->txPreambLength == DWT_PLEN_1536)
680
           || (config->txPreambLength == DWT_PLEN_2048) || (config->txPreambLength == DWT_PLEN_4096));
681
    assert((config->phrMode == DWT_PHRMODE_STD) || (config->phrMode == DWT_PHRMODE_EXT));
682
#endif
683

    
684
    // For 110 kbps we need a special setup
685
    if(DWT_BR_110K == config->dataRate)
686
    {
687
        pdw1000local->sysCFGreg |= SYS_CFG_RXM110K ;
688
        reg16 >>= 3; // lde_replicaCoeff must be divided by 8
689
    }
690
    else
691
    {
692
        pdw1000local->sysCFGreg &= (~SYS_CFG_RXM110K) ;
693
    }
694

    
695
    pdw1000local->longFrames = config->phrMode ;
696

    
697
    pdw1000local->sysCFGreg &= ~SYS_CFG_PHR_MODE_11;
698
    pdw1000local->sysCFGreg |= (SYS_CFG_PHR_MODE_11 & ((uint32)config->phrMode << SYS_CFG_PHR_MODE_SHFT));
699

    
700
    dwt_write32bitreg(SYS_CFG_ID,pdw1000local->sysCFGreg) ;
701
    // Set the lde_replicaCoeff
702
    dwt_write16bitoffsetreg(LDE_IF_ID, LDE_REPC_OFFSET, reg16) ;
703

    
704
    _dwt_configlde(prfIndex);
705

    
706
    // Configure PLL2/RF PLL block CFG/TUNE (for a given channel)
707
    dwt_write32bitoffsetreg(FS_CTRL_ID, FS_PLLCFG_OFFSET, fs_pll_cfg[chan_idx[chan]]);
708
    dwt_write8bitoffsetreg(FS_CTRL_ID, FS_PLLTUNE_OFFSET, fs_pll_tune[chan_idx[chan]]);
709

    
710
    // Configure RF RX blocks (for specified channel/bandwidth)
711
    dwt_write8bitoffsetreg(RF_CONF_ID, RF_RXCTRLH_OFFSET, rx_config[bw]);
712

    
713
    // Configure RF TX blocks (for specified channel and PRF)
714
    // Configure RF TX control
715
    dwt_write32bitoffsetreg(RF_CONF_ID, RF_TXCTRL_OFFSET, tx_config[chan_idx[chan]]);
716

    
717
    // Configure the baseband parameters (for specified PRF, bit rate, PAC, and SFD settings)
718
    // DTUNE0
719
    dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_TUNE0b_OFFSET, sftsh[config->dataRate][config->nsSFD]);
720

    
721
    // DTUNE1
722
    dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_TUNE1a_OFFSET, dtune1[prfIndex]);
723

    
724
    if(config->dataRate == DWT_BR_110K)
725
    {
726
        dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_TUNE1b_OFFSET, DRX_TUNE1b_110K);
727
    }
728
    else
729
    {
730
        if(config->txPreambLength == DWT_PLEN_64)
731
        {
732
            dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_TUNE1b_OFFSET, DRX_TUNE1b_6M8_PRE64);
733
            dwt_write8bitoffsetreg(DRX_CONF_ID, DRX_TUNE4H_OFFSET, DRX_TUNE4H_PRE64);
734
        }
735
        else
736
        {
737
            dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_TUNE1b_OFFSET, DRX_TUNE1b_850K_6M8);
738
            dwt_write8bitoffsetreg(DRX_CONF_ID, DRX_TUNE4H_OFFSET, DRX_TUNE4H_PRE128PLUS);
739
        }
740
    }
741

    
742
    // DTUNE2
743
    dwt_write32bitoffsetreg(DRX_CONF_ID, DRX_TUNE2_OFFSET, digital_bb_config[prfIndex][config->rxPAC]);
744

    
745
    // DTUNE3 (SFD timeout)
746
    // Don't allow 0 - SFD timeout will always be enabled
747
    if(config->sfdTO == 0)
748
    {
749
        config->sfdTO = DWT_SFDTOC_DEF;
750
    }
751
    dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_SFDTOC_OFFSET, config->sfdTO);
752

    
753
    // Configure AGC parameters
754
    dwt_write32bitoffsetreg( AGC_CFG_STS_ID, 0xC, agc_config.lo32);
755
    dwt_write16bitoffsetreg( AGC_CFG_STS_ID, 0x4, agc_config.target[prfIndex]);
756

    
757
    // Set (non-standard) user SFD for improved performance,
758
    if(config->nsSFD)
759
    {
760
        // Write non standard (DW) SFD length
761
        dwt_write8bitoffsetreg(USR_SFD_ID, 0x00, dwnsSFDlen[config->dataRate]);
762
        nsSfd_result = 3 ;
763
        useDWnsSFD = 1 ;
764
    }
765
    regval =  (CHAN_CTRL_TX_CHAN_MASK & (chan << CHAN_CTRL_TX_CHAN_SHIFT)) | // Transmit Channel
766
              (CHAN_CTRL_RX_CHAN_MASK & (chan << CHAN_CTRL_RX_CHAN_SHIFT)) | // Receive Channel
767
              (CHAN_CTRL_RXFPRF_MASK & ((uint32)config->prf << CHAN_CTRL_RXFPRF_SHIFT)) | // RX PRF
768
              ((CHAN_CTRL_TNSSFD|CHAN_CTRL_RNSSFD) & ((uint32)nsSfd_result << CHAN_CTRL_TNSSFD_SHIFT)) | // nsSFD enable RX&TX
769
              (CHAN_CTRL_DWSFD & ((uint32)useDWnsSFD << CHAN_CTRL_DWSFD_SHIFT)) | // Use DW nsSFD
770
              (CHAN_CTRL_TX_PCOD_MASK & ((uint32)config->txCode << CHAN_CTRL_TX_PCOD_SHIFT)) | // TX Preamble Code
771
              (CHAN_CTRL_RX_PCOD_MASK & ((uint32)config->rxCode << CHAN_CTRL_RX_PCOD_SHIFT)) ; // RX Preamble Code
772

    
773
    dwt_write32bitreg(CHAN_CTRL_ID,regval) ;
774

    
775
    // Set up TX Preamble Size, PRF and Data Rate
776
    pdw1000local->txFCTRL = ((uint32)(config->txPreambLength | config->prf) << TX_FCTRL_TXPRF_SHFT) | ((uint32)config->dataRate << TX_FCTRL_TXBR_SHFT);
777
    dwt_write32bitreg(TX_FCTRL_ID, pdw1000local->txFCTRL);
778

    
779
    // The SFD transmit pattern is initialised by the DW1000 upon a user TX request, but (due to an IC issue) it is not done for an auto-ACK TX. The
780
    // SYS_CTRL write below works around this issue, by simultaneously initiating and aborting a transmission, which correctly initialises the SFD
781
    // after its configuration or reconfiguration.
782
    // This issue is not documented at the time of writing this code. It should be in next release of DW1000 User Manual (v2.09, from July 2016).
783
    dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, SYS_CTRL_TXSTRT | SYS_CTRL_TRXOFF); // Request TX start and TRX off at the same time
784
} // end dwt_configure()
785

    
786
/*! ------------------------------------------------------------------------------------------------------------------
787
 * @fn dwt_setrxantennadelay()
788
 *
789
 * @brief This API function writes the antenna delay (in time units) to RX registers
790
 *
791
 * input parameters:
792
 * @param rxDelay - this is the total (RX) antenna delay value, which
793
 *                          will be programmed into the RX register
794
 *
795
 * output parameters
796
 *
797
 * no return value
798
 */
799
void dwt_setrxantennadelay(uint16 rxDelay)
800
{
801
    // Set the RX antenna delay for auto TX timestamp adjustment
802
    dwt_write16bitoffsetreg(LDE_IF_ID, LDE_RXANTD_OFFSET, rxDelay);
803
}
804

    
805
/*! ------------------------------------------------------------------------------------------------------------------
806
 * @fn dwt_settxantennadelay()
807
 *
808
 * @brief This API function writes the antenna delay (in time units) to TX registers
809
 *
810
 * input parameters:
811
 * @param txDelay - this is the total (TX) antenna delay value, which
812
 *                          will be programmed into the TX delay register
813
 *
814
 * output parameters
815
 *
816
 * no return value
817
 */
818
void dwt_settxantennadelay(uint16 txDelay)
819
{
820
    // Set the TX antenna delay for auto TX timestamp adjustment
821
    dwt_write16bitoffsetreg(TX_ANTD_ID, TX_ANTD_OFFSET, txDelay);
822
}
823

    
824
/*! ------------------------------------------------------------------------------------------------------------------
825
 * @fn dwt_writetxdata()
826
 *
827
 * @brief This API function writes the supplied TX data into the DW1000's
828
 * TX buffer.  The input parameters are the data length in bytes and a pointer
829
 * to those data bytes.
830
 *
831
 * input parameters
832
 * @param txFrameLength  - This is the total frame length, including the two byte CRC.
833
 *                         Note: this is the length of TX message (including the 2 byte CRC) - max is 1023
834
 *                         standard PHR mode allows up to 127 bytes
835
 *                         if > 127 is programmed, DWT_PHRMODE_EXT needs to be set in the phrMode configuration
836
 *                         see dwt_configure function
837
 * @param txFrameBytes   - Pointer to the user?s buffer containing the data to send.
838
 * @param txBufferOffset - This specifies an offset in the DW1000?s TX Buffer at which to start writing data.
839
 *
840
 * output parameters
841
 *
842
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
843
 */
844
int dwt_writetxdata(uint16 txFrameLength, uint8 *txFrameBytes, uint16 txBufferOffset)
845
{
846
#ifdef DWT_API_ERROR_CHECK
847
    assert(txFrameLength >= 2);
848
    assert((pdw1000local->longFrames && (txFrameLength <= 1023)) || (txFrameLength <= 127));
849
    assert((txBufferOffset + txFrameLength) <= 1024);
850
#endif
851

    
852
    if ((txBufferOffset + txFrameLength) <= 1024)
853
    {
854
        // Write the data to the IC TX buffer, (-2 bytes for auto generated CRC)
855
        dwt_writetodevice( TX_BUFFER_ID, txBufferOffset, txFrameLength-2, txFrameBytes);
856
        return DWT_SUCCESS;
857
    }
858
    else
859
    {
860
        return DWT_ERROR;
861
    }
862
} // end dwt_writetxdata()
863

    
864
/*! ------------------------------------------------------------------------------------------------------------------
865
 * @fn dwt_writetxfctrl()
866
 *
867
 * @brief This API function configures the TX frame control register before the transmission of a frame
868
 *
869
 * input parameters:
870
 * @param txFrameLength - this is the length of TX message (including the 2 byte CRC) - max is 1023
871
 *                              NOTE: standard PHR mode allows up to 127 bytes
872
 *                              if > 127 is programmed, DWT_PHRMODE_EXT needs to be set in the phrMode configuration
873
 *                              see dwt_configure function
874
 * @param txBufferOffset - the offset in the tx buffer to start writing the data
875
 * @param ranging - 1 if this is a ranging frame, else 0
876
 *
877
 * output parameters
878
 *
879
 * no return value
880
 */
881
void dwt_writetxfctrl(uint16 txFrameLength, uint16 txBufferOffset, int ranging)
882
{
883

    
884
#ifdef DWT_API_ERROR_CHECK
885
    assert((pdw1000local->longFrames && (txFrameLength <= 1023)) || (txFrameLength <= 127));
886
    assert((txBufferOffset + txFrameLength) <= 1024);
887
    assert((ranging == 0) || (ranging == 1))
888
#endif
889

    
890
    // Write the frame length to the TX frame control register
891
    // pdw1000local->txFCTRL has kept configured bit rate information
892
    uint32 reg32 = pdw1000local->txFCTRL | txFrameLength | ((uint32)txBufferOffset << TX_FCTRL_TXBOFFS_SHFT) | ((uint32)ranging << TX_FCTRL_TR_SHFT);
893
    dwt_write32bitreg(TX_FCTRL_ID, reg32);
894
} // end dwt_writetxfctrl()
895

    
896

    
897
/*! ------------------------------------------------------------------------------------------------------------------
898
 * @fn dwt_readrxdata()
899
 *
900
 * @brief This is used to read the data from the RX buffer, from an offset location give by offset parameter
901
 *
902
 * input parameters
903
 * @param buffer - the buffer into which the data will be read
904
 * @param length - the length of data to read (in bytes)
905
 * @param rxBufferOffset - the offset in the rx buffer from which to read the data
906
 *
907
 * output parameters
908
 *
909
 * no return value
910
 */
911
void dwt_readrxdata(uint8 *buffer, uint16 length, uint16 rxBufferOffset)
912
{
913
    dwt_readfromdevice(RX_BUFFER_ID,rxBufferOffset,length,buffer) ;
914
}
915

    
916
/*! ------------------------------------------------------------------------------------------------------------------
917
 * @fn dwt_readaccdata()
918
 *
919
 * @brief This is used to read the data from the Accumulator buffer, from an offset location give by offset parameter
920
 *
921
 * NOTE: Because of an internal memory access delay when reading the accumulator the first octet output is a dummy octet
922
 *       that should be discarded. This is true no matter what sub-index the read begins at.
923
 *
924
 * input parameters
925
 * @param buffer - the buffer into which the data will be read
926
 * @param length - the length of data to read (in bytes)
927
 * @param accOffset - the offset in the acc buffer from which to read the data
928
 *
929
 * output parameters
930
 *
931
 * no return value
932
 */
933
void dwt_readaccdata(uint8 *buffer, uint16 len, uint16 accOffset)
934
{
935
    // Force on the ACC clocks if we are sequenced
936
    _dwt_enableclocks(READ_ACC_ON);
937

    
938
    dwt_readfromdevice(ACC_MEM_ID,accOffset,len,buffer) ;
939

    
940
    _dwt_enableclocks(READ_ACC_OFF); // Revert clocks back
941
}
942

    
943
/*! ------------------------------------------------------------------------------------------------------------------
944
 * @fn dwt_readcarrierintegrator()
945
 *
946
 * @brief This is used to read the RX carrier integrator value (relating to the frequency offset of the TX node)
947
 *
948
 * NOTE: This is a 21-bit signed quantity, the function sign extends the most significant bit, which is bit #20
949
 *       (numbering from bit zero) to return a 32-bit signed integer value.
950
 *
951
 * input parameters - NONE
952
 *
953
 * return value - the (int32) signed carrier integrator value.
954
 *                A positive value means the local RX clock is running faster than the remote TX device.
955
 */
956

    
957
#define B20_SIGN_EXTEND_TEST (0x00100000UL)
958
#define B20_SIGN_EXTEND_MASK (0xFFF00000UL)
959

    
960
int32 dwt_readcarrierintegrator(void)
961
{
962
    uint32  regval = 0 ;
963
    int     j ;
964
    uint8   buffer[DRX_CARRIER_INT_LEN] ;
965

    
966
    /* Read 3 bytes into buffer (21-bit quantity) */
967

    
968
    dwt_readfromdevice(DRX_CONF_ID,DRX_CARRIER_INT_OFFSET,DRX_CARRIER_INT_LEN, buffer) ;
969

    
970
    for (j = 2 ; j >= 0 ; j --)  // arrange the three bytes into an unsigned integer value
971
    {
972
        regval = (regval << 8) + buffer[j] ;
973
    }
974

    
975
    if (regval & B20_SIGN_EXTEND_TEST) regval |= B20_SIGN_EXTEND_MASK ; // sign extend bit #20 to whole word
976
    else regval &= DRX_CARRIER_INT_MASK ;                               // make sure upper bits are clear if not sign extending
977

    
978
    return (int32) regval ; // cast unsigned value to signed quantity.
979
}
980

    
981
/*! ------------------------------------------------------------------------------------------------------------------
982
 * @fn dwt_readdiagnostics()
983
 *
984
 * @brief this function reads the RX signal quality diagnostic data
985
 *
986
 * input parameters
987
 * @param diagnostics - diagnostic structure pointer, this will contain the diagnostic data read from the DW1000
988
 *
989
 * output parameters
990
 *
991
 * no return value
992
 */
993
void dwt_readdiagnostics(dwt_rxdiag_t *diagnostics)
994
{
995
    // Read the HW FP index
996
    diagnostics->firstPath = dwt_read16bitoffsetreg(RX_TIME_ID, RX_TIME_FP_INDEX_OFFSET);
997

    
998
    // LDE diagnostic data
999
    diagnostics->maxNoise = dwt_read16bitoffsetreg(LDE_IF_ID, LDE_THRESH_OFFSET);
1000

    
1001
    // Read all 8 bytes in one SPI transaction
1002
    dwt_readfromdevice(RX_FQUAL_ID, 0x0, 8, (uint8*)&diagnostics->stdNoise);
1003

    
1004
    diagnostics->firstPathAmp1 = dwt_read16bitoffsetreg(RX_TIME_ID, RX_TIME_FP_AMPL1_OFFSET);
1005

    
1006
    diagnostics->rxPreamCount = (dwt_read32bitreg(RX_FINFO_ID) & RX_FINFO_RXPACC_MASK) >> RX_FINFO_RXPACC_SHIFT  ;
1007
}
1008

    
1009
/*! ------------------------------------------------------------------------------------------------------------------
1010
 * @fn dwt_readtxtimestamp()
1011
 *
1012
 * @brief This is used to read the TX timestamp (adjusted with the programmed antenna delay)
1013
 *
1014
 * input parameters
1015
 * @param timestamp - a pointer to a 5-byte buffer which will store the read TX timestamp time
1016
 *
1017
 * output parameters - the timestamp buffer will contain the value after the function call
1018
 *
1019
 * no return value
1020
 */
1021
void dwt_readtxtimestamp(uint8 * timestamp)
1022
{
1023
    dwt_readfromdevice(TX_TIME_ID, TX_TIME_TX_STAMP_OFFSET, TX_TIME_TX_STAMP_LEN, timestamp) ; // Read bytes directly into buffer
1024
}
1025

    
1026
/*! ------------------------------------------------------------------------------------------------------------------
1027
 * @fn dwt_readtxtimestamphi32()
1028
 *
1029
 * @brief This is used to read the high 32-bits of the TX timestamp (adjusted with the programmed antenna delay)
1030
 *
1031
 * input parameters
1032
 *
1033
 * output parameters
1034
 *
1035
 * returns high 32-bits of TX timestamp
1036
 */
1037
uint32 dwt_readtxtimestamphi32(void)
1038
{
1039
    return dwt_read32bitoffsetreg(TX_TIME_ID, 1); // Offset is 1 to get the 4 upper bytes out of 5
1040
}
1041

    
1042
/*! ------------------------------------------------------------------------------------------------------------------
1043
 * @fn dwt_readtxtimestamplo32()
1044
 *
1045
 * @brief This is used to read the low 32-bits of the TX timestamp (adjusted with the programmed antenna delay)
1046
 *
1047
 * input parameters
1048
 *
1049
 * output parameters
1050
 *
1051
 * returns low 32-bits of TX timestamp
1052
 */
1053
uint32 dwt_readtxtimestamplo32(void)
1054
{
1055
    return dwt_read32bitreg(TX_TIME_ID); // Read TX TIME as a 32-bit register to get the 4 lower bytes out of 5
1056
}
1057

    
1058
/*! ------------------------------------------------------------------------------------------------------------------
1059
 * @fn dwt_readrxtimestamp()
1060
 *
1061
 * @brief This is used to read the RX timestamp (adjusted time of arrival)
1062
 *
1063
 * input parameters
1064
 * @param timestamp - a pointer to a 5-byte buffer which will store the read RX timestamp time
1065
 *
1066
 * output parameters - the timestamp buffer will contain the value after the function call
1067
 *
1068
 * no return value
1069
 */
1070
void dwt_readrxtimestamp(uint8 * timestamp)
1071
{
1072
    dwt_readfromdevice(RX_TIME_ID, RX_TIME_RX_STAMP_OFFSET, RX_TIME_RX_STAMP_LEN, timestamp) ; // Get the adjusted time of arrival
1073
}
1074

    
1075
/*! ------------------------------------------------------------------------------------------------------------------
1076
 * @fn dwt_readrxtimestamphi32()
1077
 *
1078
 * @brief This is used to read the high 32-bits of the RX timestamp (adjusted with the programmed antenna delay)
1079
 *
1080
 * input parameters
1081
 *
1082
 * output parameters
1083
 *
1084
 * returns high 32-bits of RX timestamp
1085
 */
1086
uint32 dwt_readrxtimestamphi32(void)
1087
{
1088
    return dwt_read32bitoffsetreg(RX_TIME_ID, 1); // Offset is 1 to get the 4 upper bytes out of 5
1089
}
1090

    
1091
/*! ------------------------------------------------------------------------------------------------------------------
1092
 * @fn dwt_readrxtimestamplo32()
1093
 *
1094
 * @brief This is used to read the low 32-bits of the RX timestamp (adjusted with the programmed antenna delay)
1095
 *
1096
 * input parameters
1097
 *
1098
 * output parameters
1099
 *
1100
 * returns low 32-bits of RX timestamp
1101
 */
1102
uint32 dwt_readrxtimestamplo32(void)
1103
{
1104
    return dwt_read32bitreg(RX_TIME_ID); // Read RX TIME as a 32-bit register to get the 4 lower bytes out of 5
1105
}
1106

    
1107
/*! ------------------------------------------------------------------------------------------------------------------
1108
 * @fn dwt_readsystimestamphi32()
1109
 *
1110
 * @brief This is used to read the high 32-bits of the system time
1111
 *
1112
 * input parameters
1113
 *
1114
 * output parameters
1115
 *
1116
 * returns high 32-bits of system time timestamp
1117
 */
1118
uint32 dwt_readsystimestamphi32(void)
1119
{
1120
    return dwt_read32bitoffsetreg(SYS_TIME_ID, 1); // Offset is 1 to get the 4 upper bytes out of 5
1121
}
1122

    
1123
/*! ------------------------------------------------------------------------------------------------------------------
1124
 * @fn dwt_readsystime()
1125
 *
1126
 * @brief This is used to read the system time
1127
 *
1128
 * input parameters
1129
 * @param timestamp - a pointer to a 5-byte buffer which will store the read system time
1130
 *
1131
 * output parameters
1132
 * @param timestamp - the timestamp buffer will contain the value after the function call
1133
 *
1134
 * no return value
1135
 */
1136
void dwt_readsystime(uint8 * timestamp)
1137
{
1138
    dwt_readfromdevice(SYS_TIME_ID, SYS_TIME_OFFSET, SYS_TIME_LEN, timestamp) ;
1139
}
1140

    
1141
/*! ------------------------------------------------------------------------------------------------------------------
1142
 * @fn dwt_writetodevice()
1143
 *
1144
 * @brief  this function is used to write to the DW1000 device registers
1145
 * Notes:
1146
 *        1. Firstly we create a header (the first byte is a header byte)
1147
 *        a. check if sub index is used, if subindexing is used - set bit-6 to 1 to signify that the sub-index address follows the register index byte
1148
 *        b. set bit-7 (or with 0x80) for write operation
1149
 *        c. if extended sub address index is used (i.e. if index > 127) set bit-7 of the first sub-index byte following the first header byte
1150
 *
1151
 *        2. Write the header followed by the data bytes to the DW1000 device
1152
 *
1153
 *
1154
 * input parameters:
1155
 * @param recordNumber  - ID of register file or buffer being accessed
1156
 * @param index         - byte index into register file or buffer being accessed
1157
 * @param length        - number of bytes being written
1158
 * @param buffer        - pointer to buffer containing the 'length' bytes to be written
1159
 *
1160
 * output parameters
1161
 *
1162
 * no return value
1163
 */
1164
void dwt_writetodevice
1165
(
1166
    uint16  recordNumber,
1167
    uint16  index,
1168
    uint32        length,
1169
    const uint8   *buffer
1170
)
1171
{
1172
    uint8 header[3] ; // Buffer to compose header in
1173
    int   cnt = 0; // Counter for length of header
1174
#ifdef DWT_API_ERROR_CHECK
1175
    assert(recordNumber <= 0x3F); // Record number is limited to 6-bits.
1176
#endif
1177

    
1178
    // Write message header selecting WRITE operation and addresses as appropriate (this is one to three bytes long)
1179
    if (index == 0) // For index of 0, no sub-index is required
1180
    {
1181
        header[cnt++] = 0x80 | recordNumber ; // Bit-7 is WRITE operation, bit-6 zero=NO sub-addressing, bits 5-0 is reg file id
1182
    }
1183
    else
1184
    {
1185
#ifdef DWT_API_ERROR_CHECK
1186
        assert((index <= 0x7FFF) && ((index + length) <= 0x7FFF)); // Index and sub-addressable area are limited to 15-bits.
1187
#endif
1188
        header[cnt++] = 0xC0 | recordNumber ; // Bit-7 is WRITE operation, bit-6 one=sub-address follows, bits 5-0 is reg file id
1189

    
1190
        if (index <= 127) // For non-zero index < 127, just a single sub-index byte is required
1191
        {
1192
            header[cnt++] = (uint8)index ; // Bit-7 zero means no extension, bits 6-0 is index.
1193
        }
1194
        else
1195
        {
1196
            header[cnt++] = 0x80 | (uint8)(index) ; // Bit-7 one means extended index, bits 6-0 is low seven bits of index.
1197
            header[cnt++] =  (uint8) (index >> 7) ; // 8-bit value = high eight bits of index.
1198
        }
1199
    }
1200

    
1201
    // Write it to the SPI
1202
    writetospi(cnt,header,length,buffer);
1203
} // end dwt_writetodevice()
1204

    
1205
/*! ------------------------------------------------------------------------------------------------------------------
1206
 * @fn dwt_readfromdevice()
1207
 *
1208
 * @brief  this function is used to read from the DW1000 device registers
1209
 * Notes:
1210
 *        1. Firstly we create a header (the first byte is a header byte)
1211
 *        a. check if sub index is used, if subindexing is used - set bit-6 to 1 to signify that the sub-index address follows the register index byte
1212
 *        b. set bit-7 (or with 0x80) for write operation
1213
 *        c. if extended sub address index is used (i.e. if index > 127) set bit-7 of the first sub-index byte following the first header byte
1214
 *
1215
 *        2. Write the header followed by the data bytes to the DW1000 device
1216
 *        3. Store the read data in the input buffer
1217
 *
1218
 * input parameters:
1219
 * @param recordNumber  - ID of register file or buffer being accessed
1220
 * @param index         - byte index into register file or buffer being accessed
1221
 * @param length        - number of bytes being read
1222
 * @param buffer        - pointer to buffer in which to return the read data.
1223
 *
1224
 * output parameters
1225
 *
1226
 * no return value
1227
 */
1228
void dwt_readfromdevice
1229
(
1230
    uint16  recordNumber,
1231
    uint16  index,
1232
    uint32        length,
1233
    uint8         *buffer
1234
)
1235
{
1236
    uint8 header[3] ; // Buffer to compose header in
1237
    int   cnt = 0; // Counter for length of header
1238
#ifdef DWT_API_ERROR_CHECK
1239
    assert(recordNumber <= 0x3F); // Record number is limited to 6-bits.
1240
#endif
1241

    
1242
    // Write message header selecting READ operation and addresses as appropriate (this is one to three bytes long)
1243
    if (index == 0) // For index of 0, no sub-index is required
1244
    {
1245
        header[cnt++] = (uint8) recordNumber ; // Bit-7 zero is READ operation, bit-6 zero=NO sub-addressing, bits 5-0 is reg file id
1246
    }
1247
    else
1248
    {
1249
#ifdef DWT_API_ERROR_CHECK
1250
        assert((index <= 0x7FFF) && ((index + length) <= 0x7FFF)); // Index and sub-addressable area are limited to 15-bits.
1251
#endif
1252
        header[cnt++] = (uint8)(0x40 | recordNumber) ; // Bit-7 zero is READ operation, bit-6 one=sub-address follows, bits 5-0 is reg file id
1253

    
1254
        if (index <= 127) // For non-zero index < 127, just a single sub-index byte is required
1255
        {
1256
            header[cnt++] = (uint8) index ; // Bit-7 zero means no extension, bits 6-0 is index.
1257
        }
1258
        else
1259
        {
1260
            header[cnt++] = 0x80 | (uint8)(index) ; // Bit-7 one means extended index, bits 6-0 is low seven bits of index.
1261
            header[cnt++] =  (uint8) (index >> 7) ; // 8-bit value = high eight bits of index.
1262
        }
1263
    }
1264

    
1265
    // Do the read from the SPI
1266
    readfromspi(cnt, header, length, buffer);  // result is stored in the buffer
1267
} // end dwt_readfromdevice()
1268

    
1269

    
1270

    
1271
/*! ------------------------------------------------------------------------------------------------------------------
1272
 * @fn dwt_read32bitoffsetreg()
1273
 *
1274
 * @brief  this function is used to read 32-bit value from the DW1000 device registers
1275
 *
1276
 * input parameters:
1277
 * @param regFileID - ID of register file or buffer being accessed
1278
 * @param regOffset - the index into register file or buffer being accessed
1279
 *
1280
 * output parameters
1281
 *
1282
 * returns 32 bit register value
1283
 */
1284
uint32 dwt_read32bitoffsetreg(int regFileID, int regOffset)
1285
{
1286
    uint32  regval = 0 ;
1287
    int     j ;
1288
    uint8   buffer[4] ;
1289

    
1290
    dwt_readfromdevice(regFileID,regOffset,4,buffer); // Read 4 bytes (32-bits) register into buffer
1291

    
1292
    for (j = 3 ; j >= 0 ; j --)
1293
    {
1294
        regval = (regval << 8) + buffer[j] ;
1295
    }
1296
    return regval ;
1297

    
1298
} // end dwt_read32bitoffsetreg()
1299

    
1300
/*! ------------------------------------------------------------------------------------------------------------------
1301
 * @fn dwt_read16bitoffsetreg()
1302
 *
1303
 * @brief  this function is used to read 16-bit value from the DW1000 device registers
1304
 *
1305
 * input parameters:
1306
 * @param regFileID - ID of register file or buffer being accessed
1307
 * @param regOffset - the index into register file or buffer being accessed
1308
 *
1309
 * output parameters
1310
 *
1311
 * returns 16 bit register value
1312
 */
1313
uint16 dwt_read16bitoffsetreg(int regFileID, int regOffset)
1314
{
1315
    uint16  regval = 0 ;
1316
    uint8   buffer[2] ;
1317

    
1318
    dwt_readfromdevice(regFileID,regOffset,2,buffer); // Read 2 bytes (16-bits) register into buffer
1319

    
1320
    regval = ((uint16)buffer[1] << 8) + buffer[0] ;
1321
    return regval ;
1322

    
1323
} // end dwt_read16bitoffsetreg()
1324

    
1325
/*! ------------------------------------------------------------------------------------------------------------------
1326
 * @fn dwt_read8bitoffsetreg()
1327
 *
1328
 * @brief  this function is used to read an 8-bit value from the DW1000 device registers
1329
 *
1330
 * input parameters:
1331
 * @param regFileID - ID of register file or buffer being accessed
1332
 * @param regOffset - the index into register file or buffer being accessed
1333
 *
1334
 * output parameters
1335
 *
1336
 * returns 8-bit register value
1337
 */
1338
uint8 dwt_read8bitoffsetreg(int regFileID, int regOffset)
1339
{
1340
    uint8 regval;
1341

    
1342
    dwt_readfromdevice(regFileID, regOffset, 1, &regval);
1343

    
1344
    return regval ;
1345
}
1346

    
1347
/*! ------------------------------------------------------------------------------------------------------------------
1348
 * @fn dwt_write8bitoffsetreg()
1349
 *
1350
 * @brief  this function is used to write an 8-bit value to the DW1000 device registers
1351
 *
1352
 * input parameters:
1353
 * @param regFileID - ID of register file or buffer being accessed
1354
 * @param regOffset - the index into register file or buffer being accessed
1355
 * @param regval    - the value to write
1356
 *
1357
 * output parameters
1358
 *
1359
 * no return value
1360
 */
1361
void dwt_write8bitoffsetreg(int regFileID, int regOffset, uint8 regval)
1362
{
1363
    dwt_writetodevice(regFileID, regOffset, 1, &regval);
1364
}
1365

    
1366
/*! ------------------------------------------------------------------------------------------------------------------
1367
 * @fn dwt_write16bitoffsetreg()
1368
 *
1369
 * @brief  this function is used to write 16-bit value to the DW1000 device registers
1370
 *
1371
 * input parameters:
1372
 * @param regFileID - ID of register file or buffer being accessed
1373
 * @param regOffset - the index into register file or buffer being accessed
1374
 * @param regval    - the value to write
1375
 *
1376
 * output parameters
1377
 *
1378
 * no return value
1379
 */
1380
void dwt_write16bitoffsetreg(int regFileID, int regOffset, uint16 regval)
1381
{
1382
    uint8   buffer[2] ;
1383

    
1384
    buffer[0] = regval & 0xFF;
1385
    buffer[1] = regval >> 8 ;
1386

    
1387
    dwt_writetodevice(regFileID,regOffset,2,buffer);
1388
} // end dwt_write16bitoffsetreg()
1389

    
1390
/*! ------------------------------------------------------------------------------------------------------------------
1391
 * @fn dwt_write32bitoffsetreg()
1392
 *
1393
 * @brief  this function is used to write 32-bit value to the DW1000 device registers
1394
 *
1395
 * input parameters:
1396
 * @param regFileID - ID of register file or buffer being accessed
1397
 * @param regOffset - the index into register file or buffer being accessed
1398
 * @param regval    - the value to write
1399
 *
1400
 * output parameters
1401
 *
1402
 * no return value
1403
 */
1404
void dwt_write32bitoffsetreg(int regFileID, int regOffset, uint32 regval)
1405
{
1406
    int     j ;
1407
    uint8   buffer[4] ;
1408

    
1409
    for ( j = 0 ; j < 4 ; j++ )
1410
    {
1411
        buffer[j] = regval & 0xff ;
1412
        regval >>= 8 ;
1413
    }
1414

    
1415
    dwt_writetodevice(regFileID,regOffset,4,buffer);
1416
} // end dwt_write32bitoffsetreg()
1417

    
1418
/*! ------------------------------------------------------------------------------------------------------------------
1419
 * @fn dwt_enableframefilter()
1420
 *
1421
 * @brief This is used to enable the frame filtering - (the default option is to
1422
 * accept any data and ACK frames with correct destination address
1423
 *
1424
 * input parameters
1425
 * @param - bitmask - enables/disables the frame filtering options according to
1426
 *      DWT_FF_NOTYPE_EN        0x000   no frame types allowed
1427
 *      DWT_FF_COORD_EN         0x002   behave as coordinator (can receive frames with no destination address (PAN ID has to match))
1428
 *      DWT_FF_BEACON_EN        0x004   beacon frames allowed
1429
 *      DWT_FF_DATA_EN          0x008   data frames allowed
1430
 *      DWT_FF_ACK_EN           0x010   ack frames allowed
1431
 *      DWT_FF_MAC_EN           0x020   mac control frames allowed
1432
 *      DWT_FF_RSVD_EN          0x040   reserved frame types allowed
1433
 *
1434
 * output parameters
1435
 *
1436
 * no return value
1437
 */
1438
void dwt_enableframefilter(uint16 enable)
1439
{
1440
    uint32 sysconfig = SYS_CFG_MASK & dwt_read32bitreg(SYS_CFG_ID) ; // Read sysconfig register
1441

    
1442
    if(enable)
1443
    {
1444
        // Enable frame filtering and configure frame types
1445
        sysconfig &= ~(SYS_CFG_FF_ALL_EN); // Clear all
1446
        sysconfig |= (enable & SYS_CFG_FF_ALL_EN) | SYS_CFG_FFE;
1447
    }
1448
    else
1449
    {
1450
        sysconfig &= ~(SYS_CFG_FFE);
1451
    }
1452

    
1453
    pdw1000local->sysCFGreg = sysconfig ;
1454
    dwt_write32bitreg(SYS_CFG_ID,sysconfig) ;
1455
}
1456

    
1457
/*! ------------------------------------------------------------------------------------------------------------------
1458
 * @fn dwt_setpanid()
1459
 *
1460
 * @brief This is used to set the PAN ID
1461
 *
1462
 * input parameters
1463
 * @param panID - this is the PAN ID
1464
 *
1465
 * output parameters
1466
 *
1467
 * no return value
1468
 */
1469
void dwt_setpanid(uint16 panID)
1470
{
1471
    // PAN ID is high 16 bits of register
1472
    dwt_write16bitoffsetreg(PANADR_ID, PANADR_PAN_ID_OFFSET, panID);
1473
}
1474

    
1475
/*! ------------------------------------------------------------------------------------------------------------------
1476
 * @fn dwt_setaddress16()
1477
 *
1478
 * @brief This is used to set 16-bit (short) address
1479
 *
1480
 * input parameters
1481
 * @param shortAddress - this sets the 16 bit short address
1482
 *
1483
 * output parameters
1484
 *
1485
 * no return value
1486
 */
1487
void dwt_setaddress16(uint16 shortAddress)
1488
{
1489
    // Short address into low 16 bits
1490
    dwt_write16bitoffsetreg(PANADR_ID, PANADR_SHORT_ADDR_OFFSET, shortAddress);
1491
}
1492

    
1493
/*! ------------------------------------------------------------------------------------------------------------------
1494
 * @fn dwt_seteui()
1495
 *
1496
 * @brief This is used to set the EUI 64-bit (long) address
1497
 *
1498
 * input parameters
1499
 * @param eui64 - this is the pointer to a buffer that contains the 64bit address
1500
 *
1501
 * output parameters
1502
 *
1503
 * no return value
1504
 */
1505
void dwt_seteui(uint8 *eui64)
1506
{
1507
    dwt_writetodevice(EUI_64_ID, EUI_64_OFFSET, EUI_64_LEN, eui64);
1508
}
1509

    
1510
/*! ------------------------------------------------------------------------------------------------------------------
1511
 * @fn dwt_geteui()
1512
 *
1513
 * @brief This is used to get the EUI 64-bit from the DW1000
1514
 *
1515
 * input parameters
1516
 * @param eui64 - this is the pointer to a buffer that will contain the read 64-bit EUI value
1517
 *
1518
 * output parameters
1519
 *
1520
 * no return value
1521
 */
1522
void dwt_geteui(uint8 *eui64)
1523
{
1524
    dwt_readfromdevice(EUI_64_ID, EUI_64_OFFSET, EUI_64_LEN, eui64);
1525
}
1526

    
1527
/*! ------------------------------------------------------------------------------------------------------------------
1528
 * @fn dwt_otpread()
1529
 *
1530
 * @brief This is used to read the OTP data from given address into provided array
1531
 *
1532
 * input parameters
1533
 * @param address - this is the OTP address to read from
1534
 * @param array - this is the pointer to the array into which to read the data
1535
 * @param length - this is the number of 32 bit words to read (array needs to be at least this length)
1536
 *
1537
 * output parameters
1538
 *
1539
 * no return value
1540
 */
1541
void dwt_otpread(uint16 address, uint32 *array, uint8 length)
1542
{
1543
    int i;
1544

    
1545
    _dwt_enableclocks(FORCE_SYS_XTI); // NOTE: Set system clock to XTAL - this is necessary to make sure the values read by _dwt_otpread are reliable
1546

    
1547
    for(i=0; i<length; i++)
1548
    {
1549
        array[i] = _dwt_otpread(address + i) ;
1550
    }
1551

    
1552
    _dwt_enableclocks(ENABLE_ALL_SEQ); // Restore system clock to PLL
1553

    
1554
    return ;
1555
}
1556

    
1557
/*! ------------------------------------------------------------------------------------------------------------------
1558
 * @fn _dwt_otpread()
1559
 *
1560
 * @brief function to read the OTP memory. Ensure that MR,MRa,MRb are reset to 0.
1561
 *
1562
 * input parameters
1563
 * @param address - address to read at
1564
 *
1565
 * output parameters
1566
 *
1567
 * returns the 32bit of read data
1568
 */
1569
uint32 _dwt_otpread(uint16 address)
1570
{
1571
    uint32 ret_data;
1572

    
1573
    // Write the address
1574
    dwt_write16bitoffsetreg(OTP_IF_ID, OTP_ADDR, address);
1575

    
1576
    // Perform OTP Read - Manual read mode has to be set
1577
    dwt_write8bitoffsetreg(OTP_IF_ID, OTP_CTRL, OTP_CTRL_OTPREAD | OTP_CTRL_OTPRDEN);
1578
    dwt_write8bitoffsetreg(OTP_IF_ID, OTP_CTRL, 0x00); // OTPREAD is self clearing but OTPRDEN is not
1579

    
1580
    // Read read data, available 40ns after rising edge of OTP_READ
1581
    ret_data = dwt_read32bitoffsetreg(OTP_IF_ID, OTP_RDAT);
1582

    
1583
    // Return the 32bit of read data
1584
    return ret_data;
1585
}
1586

    
1587
/*! ------------------------------------------------------------------------------------------------------------------
1588
 * @fn _dwt_otpsetmrregs()
1589
 *
1590
 * @brief Configure the MR registers for initial programming (enable charge pump).
1591
 * Read margin is used to stress the read back from the
1592
 * programmed bit. In normal operation this is relaxed.
1593
 *
1594
 * input parameters
1595
 * @param mode - "0" : Reset all to 0x0:           MRA=0x0000, MRB=0x0000, MR=0x0000
1596
 *               "1" : Set for inital programming: MRA=0x9220, MRB=0x000E, MR=0x1024
1597
 *               "2" : Set for soak programming:   MRA=0x9220, MRB=0x0003, MR=0x1824
1598
 *               "3" : High Vpp:                   MRA=0x9220, MRB=0x004E, MR=0x1824
1599
 *               "4" : Low Read Margin:            MRA=0x0000, MRB=0x0003, MR=0x0000
1600
 *               "5" : Array Clean:                MRA=0x0049, MRB=0x0003, MR=0x0024
1601
 *               "4" : Very Low Read Margin:       MRA=0x0000, MRB=0x0003, MR=0x0000
1602
 *
1603
 * output parameters
1604
 *
1605
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
1606
 */
1607
uint32 _dwt_otpsetmrregs(int mode)
1608
{
1609
    uint8 wr_buf[4];
1610
    uint32 mra=0,mrb=0,mr=0;
1611

    
1612
    // PROGRAMME MRA
1613
    // Set MRA, MODE_SEL
1614
    wr_buf[0] = 0x03;
1615
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL+1,1,wr_buf);
1616

    
1617
    // Load data
1618
    switch(mode&0x0f) {
1619
    case 0x0 :
1620
        mr =0x0000;
1621
        mra=0x0000;
1622
        mrb=0x0000;
1623
        break;
1624
    case 0x1 :
1625
        mr =0x1024;
1626
        mra=0x9220; // Enable CPP mon
1627
        mrb=0x000e;
1628
        break;
1629
    case 0x2 :
1630
        mr =0x1824;
1631
        mra=0x9220;
1632
        mrb=0x0003;
1633
        break;
1634
    case 0x3 :
1635
        mr =0x1824;
1636
        mra=0x9220;
1637
        mrb=0x004e;
1638
        break;
1639
    case 0x4 :
1640
        mr =0x0000;
1641
        mra=0x0000;
1642
        mrb=0x0003;
1643
        break;
1644
    case 0x5 :
1645
        mr =0x0024;
1646
        mra=0x0000;
1647
        mrb=0x0003;
1648
        break;
1649
    default :
1650
        return DWT_ERROR;
1651
    }
1652

    
1653
    wr_buf[0] = mra & 0x00ff;
1654
    wr_buf[1] = (mra & 0xff00)>>8;
1655
    dwt_writetodevice(OTP_IF_ID, OTP_WDAT,2,wr_buf);
1656

    
1657

    
1658
    // Set WRITE_MR
1659
    wr_buf[0] = 0x08;
1660
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1661

    
1662
    // Wait?
1663
    deca_sleep(2);
1664

    
1665
    // Set Clear Mode sel
1666
    wr_buf[0] = 0x02;
1667
    dwt_writetodevice(OTP_IF_ID,OTP_CTRL+1,1,wr_buf);
1668

    
1669
    // Set AUX update, write MR
1670
    wr_buf[0] = 0x88;
1671
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1672
    // Clear write MR
1673
    wr_buf[0] = 0x80;
1674
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1675
    // Clear AUX update
1676
    wr_buf[0] = 0x00;
1677
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1678

    
1679
    ///////////////////////////////////////////
1680
    // PROGRAM MRB
1681
    // Set SLOW, MRB, MODE_SEL
1682
    wr_buf[0] = 0x05;
1683
    dwt_writetodevice(OTP_IF_ID,OTP_CTRL+1,1,wr_buf);
1684

    
1685
    wr_buf[0] = mrb & 0x00ff;
1686
    wr_buf[1] = (mrb & 0xff00)>>8;
1687
    dwt_writetodevice(OTP_IF_ID, OTP_WDAT,2,wr_buf);
1688

    
1689
    // Set WRITE_MR
1690
    wr_buf[0] = 0x08;
1691
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1692

    
1693
    // Wait?
1694
    deca_sleep(2);
1695

    
1696
    // Set Clear Mode sel
1697
    wr_buf[0] = 0x04;
1698
    dwt_writetodevice(OTP_IF_ID,OTP_CTRL+1,1,wr_buf);
1699

    
1700
    // Set AUX update, write MR
1701
    wr_buf[0] = 0x88;
1702
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1703
    // Clear write MR
1704
    wr_buf[0] = 0x80;
1705
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1706
    // Clear AUX update
1707
    wr_buf[0] = 0x00;
1708
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1709

    
1710
    ///////////////////////////////////////////
1711
    // PROGRAM MR
1712
    // Set SLOW, MODE_SEL
1713
    wr_buf[0] = 0x01;
1714
    dwt_writetodevice(OTP_IF_ID,OTP_CTRL+1,1,wr_buf);
1715
    // Load data
1716

    
1717
    wr_buf[0] = mr & 0x00ff;
1718
    wr_buf[1] = (mr & 0xff00)>>8;
1719
    dwt_writetodevice(OTP_IF_ID, OTP_WDAT,2,wr_buf);
1720

    
1721
    // Set WRITE_MR
1722
    wr_buf[0] = 0x08;
1723
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL,1,wr_buf);
1724

    
1725
    // Wait?
1726
    deca_sleep(2);
1727
    // Set Clear Mode sel
1728
    wr_buf[0] = 0x00;
1729
    dwt_writetodevice(OTP_IF_ID,OTP_CTRL+1,1,wr_buf);
1730

    
1731
    return DWT_SUCCESS;
1732
}
1733

    
1734
/*! ------------------------------------------------------------------------------------------------------------------
1735
 * @fn _dwt_otpprogword32()
1736
 *
1737
 * @brief function to program the OTP memory. Ensure that MR,MRa,MRb are reset to 0.
1738
 * VNM Charge pump needs to be enabled (see _dwt_otpsetmrregs)
1739
 * Note the address is only 11 bits long.
1740
 *
1741
 * input parameters
1742
 * @param address - address to read at
1743
 *
1744
 * output parameters
1745
 *
1746
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
1747
 */
1748
uint32 _dwt_otpprogword32(uint32 data, uint16 address)
1749
{
1750
    uint8 rd_buf[1];
1751
    uint8 wr_buf[4];
1752
    uint8 otp_done;
1753

    
1754
    // Write the data
1755
    wr_buf[3] = (data>>24) & 0xff;
1756
    wr_buf[2] = (data>>16) & 0xff;
1757
    wr_buf[1] = (data>>8) & 0xff;
1758
    wr_buf[0] = data & 0xff;
1759
    dwt_writetodevice(OTP_IF_ID, OTP_WDAT, 4, wr_buf);
1760

    
1761
    // Write the address [10:0]
1762
    wr_buf[1] = (address>>8) & 0x07;
1763
    wr_buf[0] = address & 0xff;
1764
    dwt_writetodevice(OTP_IF_ID, OTP_ADDR, 2, wr_buf);
1765

    
1766
    // Enable Sequenced programming
1767
    wr_buf[0] = OTP_CTRL_OTPPROG;
1768
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL, 1, wr_buf);
1769
    wr_buf[0] = 0x00; // And clear
1770
    dwt_writetodevice(OTP_IF_ID, OTP_CTRL, 1, wr_buf);
1771

    
1772
    // WAIT for status to flag PRGM OK..
1773
    otp_done = 0;
1774
    while(otp_done == 0)
1775
    {
1776
        deca_sleep(1);
1777
        dwt_readfromdevice(OTP_IF_ID, OTP_STAT, 1, rd_buf);
1778

    
1779
        if((rd_buf[0] & 0x01) == 0x01)
1780
        {
1781
            otp_done = 1;
1782
        }
1783
    }
1784

    
1785
    return DWT_SUCCESS;
1786
}
1787

    
1788
/*! ------------------------------------------------------------------------------------------------------------------
1789
 * @fn dwt_otpwriteandverify()
1790
 *
1791
 * @brief This is used to program 32-bit value into the DW1000 OTP memory.
1792
 *
1793
 * input parameters
1794
 * @param value - this is the 32-bit value to be programmed into OTP
1795
 * @param address - this is the 16-bit OTP address into which the 32-bit value is programmed
1796
 *
1797
 * output parameters
1798
 *
1799
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
1800
 */
1801
int dwt_otpwriteandverify(uint32 value, uint16 address)
1802
{
1803
    int prog_ok = DWT_SUCCESS;
1804
    int retry = 0;
1805
    // Firstly set the system clock to crystal
1806
    _dwt_enableclocks(FORCE_SYS_XTI); //set system clock to XTI
1807

    
1808
    //
1809
    //!!!!!!!!!!!!!! NOTE !!!!!!!!!!!!!!!!!!!!!
1810
    //Set the supply to 3.7V
1811
    //
1812

    
1813
    _dwt_otpsetmrregs(1); // Set mode for programming
1814

    
1815
    // For each value to program - the readback/check is done couple of times to verify it has programmed successfully
1816
    while(1)
1817
    {
1818
        _dwt_otpprogword32(value, address);
1819

    
1820
        if(_dwt_otpread(address) == value)
1821
        {
1822
            break;
1823
        }
1824
        retry++;
1825
        if(retry==10)
1826
        {
1827
            break;
1828
        }
1829
    }
1830

    
1831
    // Even if the above does not exit before retry reaches 10, the programming has probably been successful
1832

    
1833
    _dwt_otpsetmrregs(4); // Set mode for reading
1834

    
1835
    if(_dwt_otpread(address) != value) // If this does not pass please check voltage supply on VDDIO
1836
    {
1837
        prog_ok = DWT_ERROR;
1838
    }
1839

    
1840
    _dwt_otpsetmrregs(0); // Setting OTP mode register for low RM read - resetting the device would be alternative
1841

    
1842
    return prog_ok;
1843
}
1844

    
1845
/*! ------------------------------------------------------------------------------------------------------------------
1846
 * @fn _dwt_aonconfigupload()
1847
 *
1848
 * @brief This function uploads always on (AON) configuration, as set in the AON_CFG0_OFFSET register.
1849
 *
1850
 * input parameters
1851
 *
1852
 * output parameters
1853
 *
1854
 * no return value
1855
 */
1856
void _dwt_aonconfigupload(void)
1857
{
1858
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_UPL_CFG);
1859
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, 0x00); // Clear the register
1860
}
1861

    
1862
/*! ------------------------------------------------------------------------------------------------------------------
1863
 * @fn _dwt_aonarrayupload()
1864
 *
1865
 * @brief This function uploads always on (AON) data array and configuration. Thus if this function is used, then _dwt_aonconfigupload
1866
 * is not necessary. The DW1000 will go so SLEEP straight after this if the DWT_SLP_EN has been set.
1867
 *
1868
 * input parameters
1869
 *
1870
 * output parameters
1871
 *
1872
 * no return value
1873
 */
1874
void _dwt_aonarrayupload(void)
1875
{
1876
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, 0x00); // Clear the register
1877
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_SAVE);
1878
}
1879

    
1880
/*! ------------------------------------------------------------------------------------------------------------------
1881
 * @fn dwt_entersleep()
1882
 *
1883
 * @brief This function puts the device into deep sleep or sleep. dwt_configuresleep() should be called first
1884
 * to configure the sleep and on-wake/wake-up parameters
1885
 *
1886
 * input parameters
1887
 *
1888
 * output parameters
1889
 *
1890
 * no return value
1891
 */
1892
void dwt_entersleep(void)
1893
{
1894
    // Copy config to AON - upload the new configuration
1895
    _dwt_aonarrayupload();
1896
}
1897

    
1898
/*! ------------------------------------------------------------------------------------------------------------------
1899
 * @fn dwt_configuresleepcnt()
1900
 *
1901
 * @brief sets the sleep counter to new value, this function programs the high 16-bits of the 28-bit counter
1902
 *
1903
 * NOTE: this function needs to be run before dwt_configuresleep, also the SPI frequency has to be < 3MHz
1904
 *
1905
 * input parameters
1906
 * @param sleepcnt - this it value of the sleep counter to program
1907
 *
1908
 * output parameters
1909
 *
1910
 * no return value
1911
 */
1912
void dwt_configuresleepcnt(uint16 sleepcnt)
1913
{
1914
    // Force system clock to crystal
1915
    _dwt_enableclocks(FORCE_SYS_XTI);
1916

    
1917
    // Reset sleep configuration to make sure we don't accidentally go to sleep
1918
    dwt_write8bitoffsetreg(AON_ID, AON_CFG0_OFFSET, 0x00); // NB: this write change the default LPCLKDIVA value which is not used anyway.
1919
    dwt_write8bitoffsetreg(AON_ID, AON_CFG1_OFFSET, 0x00);
1920

    
1921
    // Disable the sleep counter
1922
    _dwt_aonconfigupload();
1923

    
1924
    // Set new value
1925
    dwt_write16bitoffsetreg(AON_ID, AON_CFG0_OFFSET + AON_CFG0_SLEEP_TIM_OFFSET, sleepcnt);
1926
    _dwt_aonconfigupload();
1927

    
1928
    // Enable the sleep counter
1929
    dwt_write8bitoffsetreg(AON_ID, AON_CFG1_OFFSET, AON_CFG1_SLEEP_CEN);
1930
    _dwt_aonconfigupload();
1931

    
1932
    // Put system PLL back on
1933
    _dwt_enableclocks(ENABLE_ALL_SEQ);
1934
}
1935

    
1936

    
1937
/*! ------------------------------------------------------------------------------------------------------------------
1938
 * @fn dwt_calibratesleepcnt()
1939
 *
1940
 * @brief calibrates the local oscillator as its frequency can vary between 7 and 13kHz depending on temp and voltage
1941
 *
1942
 * NOTE: this function needs to be run before dwt_configuresleepcnt, so that we know what the counter units are
1943
 *
1944
 * input parameters
1945
 *
1946
 * output parameters
1947
 *
1948
 * returns the number of XTAL/2 cycles per low-power oscillator cycle. LP OSC frequency = 19.2 MHz/return value
1949
 */
1950
uint16 dwt_calibratesleepcnt(void)
1951
{
1952
    uint16 result;
1953

    
1954
    // Enable calibration of the sleep counter
1955
    dwt_write8bitoffsetreg(AON_ID, AON_CFG1_OFFSET, AON_CFG1_LPOSC_CAL);
1956
    _dwt_aonconfigupload();
1957

    
1958
    // Disable calibration of the sleep counter
1959
    dwt_write8bitoffsetreg(AON_ID, AON_CFG1_OFFSET, 0x00);
1960
    _dwt_aonconfigupload();
1961

    
1962
    // Force system clock to crystal
1963
    _dwt_enableclocks(FORCE_SYS_XTI);
1964

    
1965
    deca_sleep(1);
1966

    
1967
    // Read the number of XTAL/2 cycles one LP oscillator cycle took.
1968
    // Set up address - Read upper byte first
1969
    dwt_write8bitoffsetreg(AON_ID, AON_ADDR_OFFSET, AON_ADDR_LPOSC_CAL_1);
1970

    
1971
    // Enable manual override
1972
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_DCA_ENAB);
1973

    
1974
    // Read confirm data that was written
1975
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_DCA_ENAB | AON_CTRL_DCA_READ);
1976

    
1977
    // Read back byte from AON
1978
    result = dwt_read8bitoffsetreg(AON_ID, AON_RDAT_OFFSET);
1979
    result <<= 8;
1980

    
1981
    // Set up address - Read lower byte
1982
    dwt_write8bitoffsetreg(AON_ID, AON_ADDR_OFFSET, AON_ADDR_LPOSC_CAL_0);
1983

    
1984
    // Enable manual override
1985
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_DCA_ENAB);
1986

    
1987
    // Read confirm data that was written
1988
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, AON_CTRL_DCA_ENAB | AON_CTRL_DCA_READ);
1989

    
1990
    // Read back byte from AON
1991
    result |= dwt_read8bitoffsetreg(AON_ID, AON_RDAT_OFFSET);
1992

    
1993
    // Disable manual override
1994
    dwt_write8bitoffsetreg(AON_ID, AON_CTRL_OFFSET, 0x00);
1995

    
1996
    // Put system PLL back on
1997
    _dwt_enableclocks(ENABLE_ALL_SEQ);
1998

    
1999
    // Returns the number of XTAL/2 cycles per one LP OSC cycle
2000
    // This can be converted into LP OSC frequency by 19.2 MHz/result
2001
    return result;
2002
}
2003

    
2004
/*! ------------------------------------------------------------------------------------------------------------------
2005
 * @fn dwt_configuresleep()
2006
 *
2007
 * @brief configures the device for both DEEP_SLEEP and SLEEP modes, and on-wake mode
2008
 * i.e. before entering the sleep, the device should be programmed for TX or RX, then upon "waking up" the TX/RX settings
2009
 * will be preserved and the device can immediately perform the desired action TX/RX
2010
 *
2011
 * NOTE: e.g. Tag operation - after deep sleep, the device needs to just load the TX buffer and send the frame
2012
 *
2013
 *
2014
 *      mode: the array and LDE code (OTP/ROM) and LDO tune, and set sleep persist
2015
 *      DWT_PRESRV_SLEEP 0x0100 - preserve sleep
2016
 *      DWT_LOADOPSET    0x0080 - load operating parameter set on wakeup
2017
 *      DWT_CONFIG       0x0040 - download the AON array into the HIF (configuration download)
2018
 *      DWT_LOADEUI      0x0008
2019
 *      DWT_GOTORX       0x0002
2020
 *      DWT_TANDV        0x0001
2021
 *
2022
 *      wake: wake up parameters
2023
 *      DWT_XTAL_EN      0x10 - keep XTAL running during sleep
2024
 *      DWT_WAKE_SLPCNT  0x8 - wake up after sleep count
2025
 *      DWT_WAKE_CS      0x4 - wake up on chip select
2026
 *      DWT_WAKE_WK      0x2 - wake up on WAKEUP PIN
2027
 *      DWT_SLP_EN       0x1 - enable sleep/deep sleep functionality
2028
 *
2029
 * input parameters
2030
 * @param mode - config on-wake parameters
2031
 * @param wake - config wake up parameters
2032
 *
2033
 * output parameters
2034
 *
2035
 * no return value
2036
 */
2037
void dwt_configuresleep(uint16 mode, uint8 wake)
2038
{
2039
    // Add predefined sleep settings before writing the mode
2040
    mode |= pdw1000local->sleep_mode;
2041
    dwt_write16bitoffsetreg(AON_ID, AON_WCFG_OFFSET, mode);
2042

    
2043
    dwt_write8bitoffsetreg(AON_ID, AON_CFG0_OFFSET, wake);
2044
}
2045

    
2046
/*! ------------------------------------------------------------------------------------------------------------------
2047
 * @fn dwt_entersleepaftertx(int enable)
2048
 *
2049
 * @brief sets the auto TX to sleep bit. This means that after a frame
2050
 * transmission the device will enter deep sleep mode. The dwt_configuresleep() function
2051
 * needs to be called before this to configure the on-wake settings
2052
 *
2053
 * NOTE: the IRQ line has to be low/inactive (i.e. no pending events)
2054
 *
2055
 * input parameters
2056
 * @param enable - 1 to configure the device to enter deep sleep after TX, 0 - disables the configuration
2057
 *
2058
 * output parameters
2059
 *
2060
 * no return value
2061
 */
2062
void dwt_entersleepaftertx(int enable)
2063
{
2064
    uint32 reg = dwt_read32bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET);
2065
    // Set the auto TX -> sleep bit
2066
    if(enable)
2067
    {
2068
        reg |= PMSC_CTRL1_ATXSLP;
2069
    }
2070
    else
2071
    {
2072
        reg &= ~(PMSC_CTRL1_ATXSLP);
2073
    }
2074
    dwt_write32bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, reg);
2075
}
2076

    
2077

    
2078
/*! ------------------------------------------------------------------------------------------------------------------
2079
 * @fn dwt_spicswakeup()
2080
 *
2081
 * @brief wake up the device from sleep mode using the SPI read,
2082
 * the device will wake up on chip select line going low if the line is held low for at least 500us.
2083
 * To define the length depending on the time one wants to hold
2084
 * the chip select line low, use the following formula:
2085
 *
2086
 *      length (bytes) = time (s) * byte_rate (Hz)
2087
 *
2088
 * where fastest byte_rate is spi_rate (Hz) / 8 if the SPI is sending the bytes back-to-back.
2089
 * To save time and power, a system designer could determine byte_rate value more precisely.
2090
 *
2091
 * NOTE: Alternatively the device can be waken up with WAKE_UP pin if configured for that operation
2092
 *
2093
 * input parameters
2094
 * @param buff   - this is a pointer to the dummy buffer which will be used in the SPI read transaction used for the WAKE UP of the device
2095
 * @param length - this is the length of the dummy buffer
2096
 *
2097
 * output parameters
2098
 *
2099
 * returns DWT_SUCCESS for success, or DWT_ERROR for error
2100
 */
2101
int dwt_spicswakeup(uint8 *buff, uint16 length)
2102
{
2103
    if(dwt_readdevid() != DWT_DEVICE_ID) // Device was in deep sleep (the first read fails)
2104
    {
2105
        // Need to keep chip select line low for at least 500us
2106
        dwt_readfromdevice(0x0, 0x0, length, buff); // Do a long read to wake up the chip (hold the chip select low)
2107

    
2108
        // Need 5ms for XTAL to start and stabilise (could wait for PLL lock IRQ status bit !!!)
2109
        // NOTE: Polling of the STATUS register is not possible unless frequency is < 3MHz
2110
        deca_sleep(5);
2111
    }
2112
    else
2113
    {
2114
        return DWT_SUCCESS;
2115
    }
2116
    // DEBUG - check if still in sleep mode
2117
    if(dwt_readdevid() != DWT_DEVICE_ID)
2118
    {
2119
        return DWT_ERROR;
2120
    }
2121

    
2122
    return DWT_SUCCESS;
2123
}
2124

    
2125
/*! ------------------------------------------------------------------------------------------------------------------
2126
 * @fn _dwt_configlde()
2127
 *
2128
 * @brief configure LDE algorithm parameters
2129
 *
2130
 * input parameters
2131
 * @param prf   -   this is the PRF index (0 or 1) 0 corresponds to 16 and 1 to 64 PRF
2132
 *
2133
 * output parameters
2134
 *
2135
 * no return value
2136
 */
2137
void _dwt_configlde(int prfIndex)
2138
{
2139
    dwt_write8bitoffsetreg(LDE_IF_ID, LDE_CFG1_OFFSET, LDE_PARAM1); // 8-bit configuration register
2140

    
2141
    if(prfIndex)
2142
    {
2143
        dwt_write16bitoffsetreg( LDE_IF_ID, LDE_CFG2_OFFSET, (uint16) LDE_PARAM3_64); // 16-bit LDE configuration tuning register
2144
    }
2145
    else
2146
    {
2147
        dwt_write16bitoffsetreg( LDE_IF_ID, LDE_CFG2_OFFSET, (uint16) LDE_PARAM3_16);
2148
    }
2149
}
2150

    
2151

    
2152
/*! ------------------------------------------------------------------------------------------------------------------
2153
 * @fn _dwt_loaducodefromrom()
2154
 *
2155
 * @brief  load ucode from OTP MEMORY or ROM
2156
 *
2157
 * input parameters
2158
 *
2159
 * output parameters
2160
 *
2161
 * no return value
2162
 */
2163
void _dwt_loaducodefromrom(void)
2164
{
2165
    // Set up clocks
2166
    _dwt_enableclocks(FORCE_LDE);
2167

    
2168
    // Kick off the LDE load
2169
    dwt_write16bitoffsetreg(OTP_IF_ID, OTP_CTRL, OTP_CTRL_LDELOAD); // Set load LDE kick bit
2170

    
2171
    deca_sleep(1); // Allow time for code to upload (should take up to 120 us)
2172

    
2173
    // Default clocks (ENABLE_ALL_SEQ)
2174
    _dwt_enableclocks(ENABLE_ALL_SEQ); // Enable clocks for sequencing
2175
}
2176

    
2177
/*! ------------------------------------------------------------------------------------------------------------------
2178
 * @fn dwt_loadopsettabfromotp()
2179
 *
2180
 * @brief This is used to select which Operational Parameter Set table to load from OTP memory
2181
 *
2182
 * input parameters
2183
 * @param ops_sel - Operational Parameter Set table to load:
2184
 *                  DWT_OPSET_64LEN = 0x0 - load the operational parameter set table for 64 length preamble configuration
2185
 *                  DWT_OPSET_TIGHT = 0x1 - load the operational parameter set table for tight xtal offsets (<1ppm)
2186
 *                  DWT_OPSET_DEFLT = 0x2 - load the default operational parameter set table (this is loaded from reset)
2187
 *
2188
 * output parameters
2189
 *
2190
 * no return value
2191
 */
2192
void dwt_loadopsettabfromotp(uint8 ops_sel)
2193
{
2194
    uint16 reg = ((ops_sel << OTP_SF_OPS_SEL_SHFT) & OTP_SF_OPS_SEL_MASK) | OTP_SF_OPS_KICK; // Select defined OPS table and trigger its loading
2195

    
2196
    // Set up clocks
2197
    _dwt_enableclocks(FORCE_LDE);
2198

    
2199
    dwt_write16bitoffsetreg(OTP_IF_ID, OTP_SF, reg);
2200

    
2201
    // Default clocks (ENABLE_ALL_SEQ)
2202
    _dwt_enableclocks(ENABLE_ALL_SEQ); // Enable clocks for sequencing
2203

    
2204
}
2205

    
2206
/*! ------------------------------------------------------------------------------------------------------------------
2207
 * @fn dwt_setsmarttxpower()
2208
 *
2209
 * @brief This call enables or disables the smart TX power feature.
2210
 *
2211
 * input parameters
2212
 * @param enable - this enables or disables the TX smart power (1 = enable, 0 = disable)
2213
 *
2214
 * output parameters
2215
 *
2216
 * no return value
2217
 */
2218
void dwt_setsmarttxpower(int enable)
2219
{
2220
    // Config system register
2221
    pdw1000local->sysCFGreg = dwt_read32bitreg(SYS_CFG_ID) ; // Read sysconfig register
2222

    
2223
    // Disable smart power configuration
2224
    if(enable)
2225
    {
2226
        pdw1000local->sysCFGreg &= ~(SYS_CFG_DIS_STXP) ;
2227
    }
2228
    else
2229
    {
2230
        pdw1000local->sysCFGreg |= SYS_CFG_DIS_STXP ;
2231
    }
2232

    
2233
    dwt_write32bitreg(SYS_CFG_ID,pdw1000local->sysCFGreg) ;
2234
}
2235

    
2236

    
2237
/*! ------------------------------------------------------------------------------------------------------------------
2238
 * @fn dwt_enableautoack()
2239
 *
2240
 * @brief This call enables the auto-ACK feature. If the responseDelayTime (parameter) is 0, the ACK will be sent a.s.a.p.
2241
 * otherwise it will be sent with a programmed delay (in symbols), max is 255.
2242
 * NOTE: needs to have frame filtering enabled as well
2243
 *
2244
 * input parameters
2245
 * @param responseDelayTime - if non-zero the ACK is sent after this delay, max is 255.
2246
 *
2247
 * output parameters
2248
 *
2249
 * no return value
2250
 */
2251
void dwt_enableautoack(uint8 responseDelayTime)
2252
{
2253
    // Set auto ACK reply delay
2254
    dwt_write8bitoffsetreg(ACK_RESP_T_ID, ACK_RESP_T_ACK_TIM_OFFSET, responseDelayTime); // In symbols
2255
    // Enable auto ACK
2256
    pdw1000local->sysCFGreg |= SYS_CFG_AUTOACK;
2257
    dwt_write32bitreg(SYS_CFG_ID,pdw1000local->sysCFGreg) ;
2258
}
2259

    
2260
/*! ------------------------------------------------------------------------------------------------------------------
2261
 * @fn dwt_setdblrxbuffmode()
2262
 *
2263
 * @brief This call enables the double receive buffer mode
2264
 *
2265
 * input parameters
2266
 * @param enable - 1 to enable, 0 to disable the double buffer mode
2267
 *
2268
 * output parameters
2269
 *
2270
 * no return value
2271
 */
2272
void dwt_setdblrxbuffmode(int enable)
2273
{
2274
    if(enable)
2275
    {
2276
        // Enable double RX buffer mode
2277
        pdw1000local->sysCFGreg &= ~SYS_CFG_DIS_DRXB;
2278
        pdw1000local->dblbuffon = 1;
2279
    }
2280
    else
2281
    {
2282
        // Disable double RX buffer mode
2283
        pdw1000local->sysCFGreg |= SYS_CFG_DIS_DRXB;
2284
        pdw1000local->dblbuffon = 0;
2285
    }
2286

    
2287
    dwt_write32bitreg(SYS_CFG_ID,pdw1000local->sysCFGreg) ;
2288
}
2289

    
2290
/*! ------------------------------------------------------------------------------------------------------------------
2291
 * @fn dwt_setrxaftertxdelay()
2292
 *
2293
 * @brief This sets the receiver turn on delay time after a transmission of a frame
2294
 *
2295
 * input parameters
2296
 * @param rxDelayTime - (20 bits) - the delay is in UWB microseconds
2297
 *
2298
 * output parameters
2299
 *
2300
 * no return value
2301
 */
2302
void dwt_setrxaftertxdelay(uint32 rxDelayTime)
2303
{
2304
    uint32 val = dwt_read32bitreg(ACK_RESP_T_ID) ; // Read ACK_RESP_T_ID register
2305

    
2306
    val &= ~(ACK_RESP_T_W4R_TIM_MASK) ; // Clear the timer (19:0)
2307

    
2308
    val |= (rxDelayTime & ACK_RESP_T_W4R_TIM_MASK) ; // In UWB microseconds (e.g. turn the receiver on 20uus after TX)
2309

    
2310
    dwt_write32bitreg(ACK_RESP_T_ID, val) ;
2311
}
2312

    
2313
/*! ------------------------------------------------------------------------------------------------------------------
2314
 * @fn dwt_setcallbacks()
2315
 *
2316
 * @brief This function is used to register the different callbacks called when one of the corresponding event occurs.
2317
 *
2318
 * NOTE: Callbacks can be undefined (set to NULL). In this case, dwt_isr() will process the event as usual but the 'null'
2319
 * callback will not be called.
2320
 *
2321
 * input parameters
2322
 * @param cbTxDone - the pointer to the TX confirmation event callback function
2323
 * @param cbRxOk - the pointer to the RX good frame event callback function
2324
 * @param cbRxTo - the pointer to the RX timeout events callback function
2325
 * @param cbRxErr - the pointer to the RX error events callback function
2326
 *
2327
 * output parameters
2328
 *
2329
 * no return value
2330
 */
2331
void dwt_setcallbacks(dwt_cb_t cbTxDone, dwt_cb_t cbRxOk, dwt_cb_t cbRxTo, dwt_cb_t cbRxErr)
2332
{
2333
    pdw1000local->cbTxDone = cbTxDone;
2334
    pdw1000local->cbRxOk = cbRxOk;
2335
    pdw1000local->cbRxTo = cbRxTo;
2336
    pdw1000local->cbRxErr = cbRxErr;
2337
}
2338

    
2339
/*! ------------------------------------------------------------------------------------------------------------------
2340
 * @fn dwt_checkirq()
2341
 *
2342
 * @brief This function checks if the IRQ line is active - this is used instead of interrupt handler
2343
 *
2344
 * input parameters
2345
 *
2346
 * output parameters
2347
 *
2348
 * return value is 1 if the IRQS bit is set and 0 otherwise
2349
 */
2350
uint8 dwt_checkirq(void)
2351
{
2352
    return (dwt_read8bitoffsetreg(SYS_STATUS_ID, SYS_STATUS_OFFSET) & SYS_STATUS_IRQS); // Reading the lower byte only is enough for this operation
2353
}
2354

    
2355
/*! ------------------------------------------------------------------------------------------------------------------
2356
 * @fn dwt_isr()
2357
 *
2358
 * @brief This is the DW1000's general Interrupt Service Routine. It will process/report the following events:
2359
 *          - RXFCG (through cbRxOk callback)
2360
 *          - TXFRS (through cbTxDone callback)
2361
 *          - RXRFTO/RXPTO (through cbRxTo callback)
2362
 *          - RXPHE/RXFCE/RXRFSL/RXSFDTO/AFFREJ/LDEERR (through cbRxTo cbRxErr)
2363
 *        For all events, corresponding interrupts are cleared and necessary resets are performed. In addition, in the RXFCG case,
2364
 *        received frame information and frame control are read before calling the callback. If double buffering is activated, it
2365
 *        will also toggle between reception buffers once the reception callback processing has ended.
2366
 *
2367
 *        /!\ This version of the ISR supports double buffering but does not support automatic RX re-enabling!
2368
 *
2369
 * NOTE:  In PC based system using (Cheetah or ARM) USB to SPI converter there can be no interrupts, however we still need something
2370
 *        to take the place of it and operate in a polled way. In an embedded system this function should be configured to be triggered
2371
 *        on any of the interrupts described above.
2372

2373
 * input parameters
2374
 *
2375
 * output parameters
2376
 *
2377
 * no return value
2378
 */
2379
void dwt_isr(void)
2380
{
2381
    uint32 status = pdw1000local->cbData.status = dwt_read32bitreg(SYS_STATUS_ID); // Read status register low 32bits
2382

    
2383
    // Handle RX good frame event
2384
    if(status & SYS_STATUS_RXFCG)
2385
    {
2386
        uint16 finfo16;
2387
        uint16 len;
2388

    
2389
        dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_RX_GOOD); // Clear all receive status bits
2390

    
2391
        pdw1000local->cbData.rx_flags = 0;
2392

    
2393
        // Read frame info - Only the first two bytes of the register are used here.
2394
        finfo16 = dwt_read16bitoffsetreg(RX_FINFO_ID, RX_FINFO_OFFSET);
2395

    
2396
        // Report frame length - Standard frame length up to 127, extended frame length up to 1023 bytes
2397
        len = finfo16 & RX_FINFO_RXFL_MASK_1023;
2398
        if(pdw1000local->longFrames == 0)
2399
        {
2400
            len &= RX_FINFO_RXFLEN_MASK;
2401
        }
2402
        pdw1000local->cbData.datalength = len;
2403

    
2404
        // Report ranging bit
2405
        if(finfo16 & RX_FINFO_RNG)
2406
        {
2407
            pdw1000local->cbData.rx_flags |= DWT_CB_DATA_RX_FLAG_RNG;
2408
        }
2409

    
2410
        // Report frame control - First bytes of the received frame.
2411
        dwt_readfromdevice(RX_BUFFER_ID, 0, FCTRL_LEN_MAX, pdw1000local->cbData.fctrl);
2412

    
2413
        // Because of a previous frame not being received properly, AAT bit can be set upon the proper reception of a frame not requesting for
2414
        // acknowledgement (ACK frame is not actually sent though). If the AAT bit is set, check ACK request bit in frame control to confirm (this
2415
        // implementation works only for IEEE802.15.4-2011 compliant frames).
2416
        // This issue is not documented at the time of writing this code. It should be in next release of DW1000 User Manual (v2.09, from July 2016).
2417
        if((status & SYS_STATUS_AAT) && ((pdw1000local->cbData.fctrl[0] & FCTRL_ACK_REQ_MASK) == 0))
2418
        {
2419
            dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_AAT); // Clear AAT status bit in register
2420
            pdw1000local->cbData.status &= ~SYS_STATUS_AAT; // Clear AAT status bit in callback data register copy
2421
            pdw1000local->wait4resp = 0;
2422
        }
2423

    
2424
        // Call the corresponding callback if present
2425
        if(pdw1000local->cbRxOk != NULL)
2426
        {
2427
            pdw1000local->cbRxOk(&pdw1000local->cbData);
2428
        }
2429

    
2430
        if (pdw1000local->dblbuffon)
2431
        {
2432
            // Toggle the Host side Receive Buffer Pointer
2433
            dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_HRBT_OFFSET, 1);
2434
        }
2435
    }
2436

    
2437
    // Handle TX confirmation event
2438
    if(status & SYS_STATUS_TXFRS)
2439
    {
2440
        dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_TX); // Clear TX event bits
2441

    
2442
        // In the case where this TXFRS interrupt is due to the automatic transmission of an ACK solicited by a response (with ACK request bit set)
2443
        // that we receive through using wait4resp to a previous TX (and assuming that the IRQ processing of that TX has already been handled), then
2444
        // we need to handle the IC issue which turns on the RX again in this situation (i.e. because it is wrongly applying the wait4resp after the
2445
        // ACK TX).
2446
        // See section "Transmit and automatically wait for response" in DW1000 User Manual
2447
        if((status & SYS_STATUS_AAT) && pdw1000local->wait4resp)
2448
        {
2449
            dwt_forcetrxoff(); // Turn the RX off
2450
            dwt_rxreset(); // Reset in case we were late and a frame was already being received
2451
        }
2452

    
2453
        // Call the corresponding callback if present
2454
        if(pdw1000local->cbTxDone != NULL)
2455
        {
2456
            pdw1000local->cbTxDone(&pdw1000local->cbData);
2457
        }
2458
    }
2459

    
2460
    // Handle frame reception/preamble detect timeout events
2461
    if(status & SYS_STATUS_ALL_RX_TO)
2462
    {
2463
        dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_RXRFTO); // Clear RX timeout event bits
2464

    
2465
        pdw1000local->wait4resp = 0;
2466

    
2467
        // Because of an issue with receiver restart after error conditions, an RX reset must be applied after any error or timeout event to ensure
2468
        // the next good frame's timestamp is computed correctly.
2469
        // See section "RX Message timestamp" in DW1000 User Manual.
2470
        dwt_forcetrxoff();
2471
        dwt_rxreset();
2472

    
2473
        // Call the corresponding callback if present
2474
        if(pdw1000local->cbRxTo != NULL)
2475
        {
2476
            pdw1000local->cbRxTo(&pdw1000local->cbData);
2477
        }
2478
    }
2479

    
2480
    // Handle RX errors events
2481
    if(status & SYS_STATUS_ALL_RX_ERR)
2482
    {
2483
        dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_RX_ERR); // Clear RX error event bits
2484

    
2485
        pdw1000local->wait4resp = 0;
2486

    
2487
        // Because of an issue with receiver restart after error conditions, an RX reset must be applied after any error or timeout event to ensure
2488
        // the next good frame's timestamp is computed correctly.
2489
        // See section "RX Message timestamp" in DW1000 User Manual.
2490
        dwt_forcetrxoff();
2491
        dwt_rxreset();
2492

    
2493
        // Call the corresponding callback if present
2494
        if(pdw1000local->cbRxErr != NULL)
2495
        {
2496
            pdw1000local->cbRxErr(&pdw1000local->cbData);
2497
        }
2498
    }
2499
}
2500

    
2501
/*! ------------------------------------------------------------------------------------------------------------------
2502
 * @fn dwt_isr_lplisten()
2503
 *
2504
 * @brief This is the DW1000's Interrupt Service Routine to use when low-power listening scheme is implemented. It will
2505
 *        only process/report the RXFCG event (through cbRxOk callback).
2506
 *        It clears RXFCG interrupt and reads received frame information and frame control before calling the callback.
2507
 *
2508
 *        /!\ This version of the ISR is designed for single buffering case only!
2509
 *
2510
 * input parameters
2511
 *
2512
 * output parameters
2513
 *
2514
 * no return value
2515
 */
2516
void dwt_lowpowerlistenisr(void)
2517
{
2518
    uint32 status = pdw1000local->cbData.status = dwt_read32bitreg(SYS_STATUS_ID); // Read status register low 32bits
2519
    uint16 finfo16;
2520
    uint16 len;
2521

    
2522
    // The only interrupt handled when in low-power listening mode is RX good frame so proceed directly to the handling of the received frame.
2523

    
2524
    // Deactivate low-power listening before clearing the interrupt. If not, the DW1000 will go back to sleep as soon as the interrupt is cleared.
2525
    dwt_setlowpowerlistening(0);
2526

    
2527
    dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_RX_GOOD); // Clear all receive status bits
2528

    
2529
    pdw1000local->cbData.rx_flags = 0;
2530

    
2531
    // Read frame info - Only the first two bytes of the register are used here.
2532
    finfo16 = dwt_read16bitoffsetreg(RX_FINFO_ID, 0);
2533

    
2534
    // Report frame length - Standard frame length up to 127, extended frame length up to 1023 bytes
2535
    len = finfo16 & RX_FINFO_RXFL_MASK_1023;
2536
    if(pdw1000local->longFrames == 0)
2537
    {
2538
        len &= RX_FINFO_RXFLEN_MASK;
2539
    }
2540
    pdw1000local->cbData.datalength = len;
2541

    
2542
    // Report ranging bit
2543
    if(finfo16 & RX_FINFO_RNG)
2544
    {
2545
        pdw1000local->cbData.rx_flags |= DWT_CB_DATA_RX_FLAG_RNG;
2546
    }
2547

    
2548
    // Report frame control - First bytes of the received frame.
2549
    dwt_readfromdevice(RX_BUFFER_ID, 0, FCTRL_LEN_MAX, pdw1000local->cbData.fctrl);
2550

    
2551
    // Because of a previous frame not being received properly, AAT bit can be set upon the proper reception of a frame not requesting for
2552
    // acknowledgement (ACK frame is not actually sent though). If the AAT bit is set, check ACK request bit in frame control to confirm (this
2553
    // implementation works only for IEEE802.15.4-2011 compliant frames).
2554
    // This issue is not documented at the time of writing this code. It should be in next release of DW1000 User Manual (v2.09, from July 2016).
2555
    if((status & SYS_STATUS_AAT) && ((pdw1000local->cbData.fctrl[0] & FCTRL_ACK_REQ_MASK) == 0))
2556
    {
2557
        dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_AAT); // Clear AAT status bit in register
2558
        pdw1000local->cbData.status &= ~SYS_STATUS_AAT; // Clear AAT status bit in callback data register copy
2559
        pdw1000local->wait4resp = 0;
2560
    }
2561

    
2562
    // Call the corresponding callback if present
2563
    if(pdw1000local->cbRxOk != NULL)
2564
    {
2565
        pdw1000local->cbRxOk(&pdw1000local->cbData);
2566
    }
2567
}
2568

    
2569
/*! ------------------------------------------------------------------------------------------------------------------
2570
 * @fn dwt_setleds()
2571
 *
2572
 * @brief This is used to set up Tx/Rx GPIOs which could be used to control LEDs
2573
 * Note: not completely IC dependent, also needs board with LEDS fitted on right I/O lines
2574
 *       this function enables GPIOs 2 and 3 which are connected to LED3 and LED4 on EVB1000
2575
 *
2576
 * input parameters
2577
 * @param mode - this is a bit field interpreted as follows:
2578
 *          - bit 0: 1 to enable LEDs, 0 to disable them
2579
 *          - bit 1: 1 to make LEDs blink once on init. Only valid if bit 0 is set (enable LEDs)
2580
 *          - bit 2 to 7: reserved
2581
 *
2582
 * output parameters none
2583
 *
2584
 * no return value
2585
 */
2586
void dwt_setleds(uint8 mode)
2587
{
2588
    uint32 reg;
2589

    
2590
    if (mode & DWT_LEDS_ENABLE)
2591
    {
2592
        // Set up MFIO for LED output.
2593
        reg = dwt_read32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET);
2594
        reg &= ~(GPIO_MSGP2_MASK | GPIO_MSGP3_MASK);
2595
        reg |= (GPIO_PIN2_RXLED | GPIO_PIN3_TXLED);
2596
        dwt_write32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET, reg);
2597

    
2598
        // Enable LP Oscillator to run from counter and turn on de-bounce clock.
2599
        reg = dwt_read32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET);
2600
        reg |= (PMSC_CTRL0_GPDCE | PMSC_CTRL0_KHZCLEN);
2601
        dwt_write32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, reg);
2602

    
2603
        // Enable LEDs to blink and set default blink time.
2604
        reg = PMSC_LEDC_BLNKEN | PMSC_LEDC_BLINK_TIME_DEF;
2605
        // Make LEDs blink once if requested.
2606
        if (mode & DWT_LEDS_INIT_BLINK)
2607
        {
2608
            reg |= PMSC_LEDC_BLINK_NOW_ALL;
2609
        }
2610
        dwt_write32bitoffsetreg(PMSC_ID, PMSC_LEDC_OFFSET, reg);
2611
        // Clear force blink bits if needed.
2612
        if(mode & DWT_LEDS_INIT_BLINK)
2613
        {
2614
            reg &= ~PMSC_LEDC_BLINK_NOW_ALL;
2615
            dwt_write32bitoffsetreg(PMSC_ID, PMSC_LEDC_OFFSET, reg);
2616
        }
2617
    }
2618
    else
2619
    {
2620
        // Clear the GPIO bits that are used for LED control.
2621
        reg = dwt_read32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET);
2622
        reg &= ~(GPIO_MSGP2_MASK | GPIO_MSGP3_MASK);
2623
        dwt_write32bitoffsetreg(GPIO_CTRL_ID, GPIO_MODE_OFFSET, reg);
2624
    }
2625
}
2626

    
2627
/*! ------------------------------------------------------------------------------------------------------------------
2628
 * @fn _dwt_enableclocks()
2629
 *
2630
 * @brief function to enable/disable clocks to particular digital blocks/system
2631
 *
2632
 * input parameters
2633
 * @param clocks - set of clocks to enable/disable
2634
 *
2635
 * output parameters none
2636
 *
2637
 * no return value
2638
 */
2639
void _dwt_enableclocks(int clocks)
2640
{
2641
    uint8 reg[2];
2642

    
2643
    dwt_readfromdevice(PMSC_ID, PMSC_CTRL0_OFFSET, 2, reg);
2644
    switch(clocks)
2645
    {
2646
        case ENABLE_ALL_SEQ:
2647
        {
2648
            reg[0] = 0x00 ;
2649
            reg[1] = reg[1] & 0xfe;
2650
        }
2651
        break;
2652
        case FORCE_SYS_XTI:
2653
        {
2654
            // System and RX
2655
            reg[0] = 0x01 | (reg[0] & 0xfc);
2656
        }
2657
        break;
2658
        case FORCE_SYS_PLL:
2659
        {
2660
            // System
2661
            reg[0] = 0x02 | (reg[0] & 0xfc);
2662
        }
2663
        break;
2664
        case READ_ACC_ON:
2665
        {
2666
            reg[0] = 0x48 | (reg[0] & 0xb3);
2667
            reg[1] = 0x80 | reg[1];
2668
        }
2669
        break;
2670
        case READ_ACC_OFF:
2671
        {
2672
            reg[0] = reg[0] & 0xb3;
2673
            reg[1] = 0x7f & reg[1];
2674
        }
2675
        break;
2676
        case FORCE_OTP_ON:
2677
        {
2678
            reg[1] = 0x02 | reg[1];
2679
        }
2680
        break;
2681
        case FORCE_OTP_OFF:
2682
        {
2683
            reg[1] = reg[1] & 0xfd;
2684
        }
2685
        break;
2686
        case FORCE_TX_PLL:
2687
        {
2688
            reg[0] = 0x20 | (reg[0] & 0xcf);
2689
        }
2690
        break;
2691
        case FORCE_LDE:
2692
        {
2693
            reg[0] = 0x01;
2694
            reg[1] = 0x03;
2695
        }
2696
        break;
2697
        default:
2698
        break;
2699
    }
2700

    
2701

    
2702
    // Need to write lower byte separately before setting the higher byte(s)
2703
    dwt_writetodevice(PMSC_ID, PMSC_CTRL0_OFFSET, 1, &reg[0]);
2704
    dwt_writetodevice(PMSC_ID, 0x1, 1, &reg[1]);
2705

    
2706
} // end _dwt_enableclocks()
2707

    
2708
/*! ------------------------------------------------------------------------------------------------------------------
2709
 * @fn _dwt_disablesequencing()
2710
 *
2711
 * @brief This function disables the TX blocks sequencing, it disables PMSC control of RF blocks, system clock is also set to XTAL
2712
 *
2713
 * input parameters none
2714
 *
2715
 * output parameters none
2716
 *
2717
 * no return value
2718
 */
2719
void _dwt_disablesequencing(void) // Disable sequencing and go to state "INIT"
2720
{
2721
    _dwt_enableclocks(FORCE_SYS_XTI); // Set system clock to XTI
2722

    
2723
    dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, PMSC_CTRL1_PKTSEQ_DISABLE); // Disable PMSC ctrl of RF and RX clk blocks
2724
}
2725

    
2726
/*! ------------------------------------------------------------------------------------------------------------------
2727
 * @fn dwt_setdelayedtrxtime()
2728
 *
2729
 * @brief This API function configures the delayed transmit time or the delayed RX on time
2730
 *
2731
 * input parameters
2732
 * @param starttime - the TX/RX start time (the 32 bits should be the high 32 bits of the system time at which to send the message,
2733
 * or at which to turn on the receiver)
2734
 *
2735
 * output parameters none
2736
 *
2737
 * no return value
2738
 */
2739
void dwt_setdelayedtrxtime(uint32 starttime)
2740
{
2741
    dwt_write32bitoffsetreg(DX_TIME_ID, 1, starttime); // Write at offset 1 as the lower 9 bits of this register are ignored
2742

    
2743
} // end dwt_setdelayedtrxtime()
2744

    
2745
/*! ------------------------------------------------------------------------------------------------------------------
2746
 * @fn dwt_starttx()
2747
 *
2748
 * @brief This call initiates the transmission, input parameter indicates which TX mode is used see below
2749
 *
2750
 * input parameters:
2751
 * @param mode - if mode = DWT_START_TX_IMMEDIATE - immediate TX (no response expected)
2752
 *               if mode = DWT_START_TX_DELAYED - delayed TX (no response expected)
2753
 *               if mode = DWT_START_TX_IMMEDIATE | DWT_RESPONSE_EXPECTED - immediate TX (response expected - so the receiver will be automatically turned on after TX is done)
2754
 *               if mode = DWT_START_TX_DELAYED | DWT_RESPONSE_EXPECTED - delayed TX (response expected - so the receiver will be automatically turned on after TX is done)
2755
 *
2756
 * output parameters
2757
 *
2758
 * returns DWT_SUCCESS for success, or DWT_ERROR for error (e.g. a delayed transmission will be cancelled if the delayed time has passed)
2759
 */
2760

    
2761
int dwt_starttx(uint8 mode)
2762
{
2763
    int retval = DWT_SUCCESS ;
2764
    uint8 temp  = 0x00;
2765
    uint16 checkTxOK = 0 ;
2766

    
2767
    if(mode & DWT_RESPONSE_EXPECTED)
2768
    {
2769
        temp = (uint8)SYS_CTRL_WAIT4RESP ; // Set wait4response bit
2770
        pdw1000local->wait4resp = 1;
2771
    }
2772

    
2773
    if (mode & DWT_START_TX_DELAYED)
2774
    {
2775
        // Both SYS_CTRL_TXSTRT and SYS_CTRL_TXDLYS to correctly enable TX
2776
        temp |= (uint8)(SYS_CTRL_TXDLYS | SYS_CTRL_TXSTRT) ;
2777
        dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, temp);
2778
        checkTxOK = dwt_read16bitoffsetreg(SYS_STATUS_ID, 3); // Read at offset 3 to get the upper 2 bytes out of 5
2779
        if ((checkTxOK & SYS_STATUS_TXERR) == 0) // Transmit Delayed Send set over Half a Period away or Power Up error (there is enough time to send but not to power up individual blocks).
2780
        {
2781
            retval = DWT_SUCCESS ; // All okay
2782
        }
2783
        else
2784
        {
2785
            // If HPDWARN or TXPUTE are set this indicates that the TXDLYS was set too late for the specified DX_TIME.
2786
            // remedial action is to cancel delayed send and report error
2787
            dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, (uint8)SYS_CTRL_TRXOFF);
2788
            retval = DWT_ERROR ; // Failed !
2789
        }
2790
    }
2791
    else
2792
    {
2793
        temp |= (uint8)SYS_CTRL_TXSTRT ;
2794
        dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, temp);
2795
    }
2796

    
2797
    return retval;
2798

    
2799
} // end dwt_starttx()
2800

    
2801
/*! ------------------------------------------------------------------------------------------------------------------
2802
 * @fn dwt_forcetrxoff()
2803
 *
2804
 * @brief This is used to turn off the transceiver
2805
 *
2806
 * input parameters
2807
 *
2808
 * output parameters
2809
 *
2810
 * no return value
2811
 */
2812
void dwt_forcetrxoff(void)
2813
{
2814
    decaIrqStatus_t stat ;
2815
    uint32 mask;
2816

    
2817
    mask = dwt_read32bitreg(SYS_MASK_ID) ; // Read set interrupt mask
2818

    
2819
    // Need to beware of interrupts occurring in the middle of following read modify write cycle
2820
    // We can disable the radio, but before the status is cleared an interrupt can be set (e.g. the
2821
    // event has just happened before the radio was disabled)
2822
    // thus we need to disable interrupt during this operation
2823
    stat = decamutexon() ;
2824

    
2825
    dwt_write32bitreg(SYS_MASK_ID, 0) ; // Clear interrupt mask - so we don't get any unwanted events
2826

    
2827
    dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, (uint8)SYS_CTRL_TRXOFF) ; // Disable the radio
2828

    
2829
    // Forcing Transceiver off - so we do not want to see any new events that may have happened
2830
    dwt_write32bitreg(SYS_STATUS_ID, (SYS_STATUS_ALL_TX | SYS_STATUS_ALL_RX_ERR | SYS_STATUS_ALL_RX_TO | SYS_STATUS_ALL_RX_GOOD));
2831

    
2832
    dwt_syncrxbufptrs();
2833

    
2834
    dwt_write32bitreg(SYS_MASK_ID, mask) ; // Set interrupt mask to what it was
2835

    
2836
    // Enable/restore interrupts again...
2837
    decamutexoff(stat) ;
2838
    pdw1000local->wait4resp = 0;
2839

    
2840
} // end deviceforcetrxoff()
2841

    
2842
/*! ------------------------------------------------------------------------------------------------------------------
2843
 * @fn dwt_syncrxbufptrs()
2844
 *
2845
 * @brief this function synchronizes rx buffer pointers
2846
 * need to make sure that the host/IC buffer pointers are aligned before starting RX
2847
 *
2848
 * input parameters:
2849
 *
2850
 * output parameters
2851
 *
2852
 * no return value
2853
 */
2854
void dwt_syncrxbufptrs(void)
2855
{
2856
    uint8  buff ;
2857
    // Need to make sure that the host/IC buffer pointers are aligned before starting RX
2858
    buff = dwt_read8bitoffsetreg(SYS_STATUS_ID, 3); // Read 1 byte at offset 3 to get the 4th byte out of 5
2859

    
2860
    if((buff & (SYS_STATUS_ICRBP >> 24)) !=     // IC side Receive Buffer Pointer
2861
       ((buff & (SYS_STATUS_HSRBP>>24)) << 1) ) // Host Side Receive Buffer Pointer
2862
    {
2863
        dwt_write8bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_HRBT_OFFSET , 0x01) ; // We need to swap RX buffer status reg (write one to toggle internally)
2864
    }
2865
}
2866

    
2867
/*! ------------------------------------------------------------------------------------------------------------------
2868
 * @fn dwt_setsniffmode()
2869
 *
2870
 * @brief enable/disable and configure SNIFF mode.
2871
 *
2872
 * SNIFF mode is a low-power reception mode where the receiver is sequenced on and off instead of being on all the time.
2873
 * The time spent in each state (on/off) is specified through the parameters below.
2874
 * See DW1000 User Manual section 4.5 "Low-Power SNIFF mode" for more details.
2875
 *
2876
 * input parameters:
2877
 * @param enable - 1 to enable SNIFF mode, 0 to disable. When 0, all other parameters are not taken into account.
2878
 * @param timeOn - duration of receiver ON phase, expressed in multiples of PAC size. The counter automatically adds 1 PAC
2879
 *                 size to the value set. Min value that can be set is 1 (i.e. an ON time of 2 PAC size), max value is 15.
2880
 * @param timeOff - duration of receiver OFF phase, expressed in multiples of 128/125 ?s (~1 ?s). Max value is 255.
2881
 *
2882
 * output parameters
2883
 *
2884
 * no return value
2885
 */
2886
void dwt_setsniffmode(int enable, uint8 timeOn, uint8 timeOff)
2887
{
2888
    uint32 pmsc_reg;
2889
    if (enable)
2890
    {
2891
        /* Configure ON/OFF times and enable PLL2 on/off sequencing by SNIFF mode. */
2892
        uint16 sniff_reg = (((uint16)timeOff << 8) | timeOn) & RX_SNIFF_MASK;
2893
        dwt_write16bitoffsetreg(RX_SNIFF_ID, RX_SNIFF_OFFSET, sniff_reg);
2894
        pmsc_reg = dwt_read32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET);
2895
        pmsc_reg |= PMSC_CTRL0_PLL2_SEQ_EN;
2896
        dwt_write32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, pmsc_reg);
2897
    }
2898
    else
2899
    {
2900
        /* Clear ON/OFF times and disable PLL2 on/off sequencing by SNIFF mode. */
2901
        dwt_write16bitoffsetreg(RX_SNIFF_ID, RX_SNIFF_OFFSET, 0x0000);
2902
        pmsc_reg = dwt_read32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET);
2903
        pmsc_reg &= ~PMSC_CTRL0_PLL2_SEQ_EN;
2904
        dwt_write32bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, pmsc_reg);
2905
    }
2906
}
2907

    
2908
/*! ------------------------------------------------------------------------------------------------------------------
2909
 * @fn dwt_setlowpowerlistening()
2910
 *
2911
 * @brief enable/disable low-power listening mode.
2912
 *
2913
 * Low-power listening is a feature whereby the DW1000 is predominantly in the SLEEP state but wakes periodically, (after
2914
 * this "long sleep"), for a very short time to sample the air for a preamble sequence. This preamble sampling "listening"
2915
 * phase is actually two reception phases separated by a "short sleep" time. See DW1000 User Manual section "Low-Power
2916
 * Listening" for more details.
2917
 *
2918
 * NOTE: Before enabling low-power listening, the following functions have to be called to fully configure it:
2919
 *           - dwt_configuresleep() to configure long sleep phase. "mode" parameter should at least have DWT_PRESRV_SLEEP,
2920
 *             DWT_CONFIG and DWT_RX_EN set and "wake" parameter should at least have both DWT_WAKE_SLPCNT and DWT_SLP_EN set.
2921
 *           - dwt_calibratesleepcnt() and dwt_configuresleepcnt() to define the "long sleep" phase duration.
2922
 *           - dwt_setsnoozetime() to define the "short sleep" phase duration.
2923
 *           - dwt_setpreambledetecttimeout() to define the reception phases duration.
2924
 *           - dwt_setinterrupt() to activate RX good frame interrupt (DWT_INT_RFCG) only.
2925
 *       When configured, low-power listening mode can be triggered either by putting the DW1000 to sleep (using
2926
 *       dwt_entersleep()) or by activating reception (using dwt_rxenable()).
2927
 *
2928
 *       Please refer to the low-power listening examples (examples 8a/8b accompanying the API distribution on Decawave's
2929
 *       website). They form a working example code that shows how to use low-power listening correctly.
2930
 *
2931
 * input parameters:
2932
 * @param enable - 1 to enable low-power listening, 0 to disable.
2933
 *
2934
 * output parameters
2935
 *
2936
 * no return value
2937
 */
2938
void dwt_setlowpowerlistening(int enable)
2939
{
2940
    uint32 pmsc_reg = dwt_read32bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET);
2941
    if (enable)
2942
    {
2943
        /* Configure RX to sleep and snooze features. */
2944
        pmsc_reg |= (PMSC_CTRL1_ARXSLP | PMSC_CTRL1_SNOZE);
2945
    }
2946
    else
2947
    {
2948
        /* Reset RX to sleep and snooze features. */
2949
        pmsc_reg &= ~(PMSC_CTRL1_ARXSLP | PMSC_CTRL1_SNOZE);
2950
    }
2951
    dwt_write32bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, pmsc_reg);
2952
}
2953

    
2954
/*! ------------------------------------------------------------------------------------------------------------------
2955
 * @fn dwt_setsnoozetime()
2956
 *
2957
 * @brief Set duration of "short sleep" phase when in low-power listening mode.
2958
 *
2959
 * input parameters:
2960
 * @param snooze_time - "short sleep" phase duration, expressed in multiples of 512/19.2 ?s (~26.7 ?s). The counter
2961
 *                      automatically adds 1 to the value set. The smallest working value that should be set is 1,
2962
 *                      i.e. giving a snooze time of 2 units (or ~53 ?s).
2963
 *
2964
 * output parameters
2965
 *
2966
 * no return value
2967
 */
2968
void dwt_setsnoozetime(uint8 snooze_time)
2969
{
2970
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_SNOZT_OFFSET, snooze_time);
2971
}
2972

    
2973
/*! ------------------------------------------------------------------------------------------------------------------
2974
 * @fn dwt_rxenable()
2975
 *
2976
 * @brief This call turns on the receiver, can be immediate or delayed (depending on the mode parameter). In the case of a
2977
 * "late" error the receiver will only be turned on if the DWT_IDLE_ON_DLY_ERR is not set.
2978
 * The receiver will stay turned on, listening to any messages until
2979
 * it either receives a good frame, an error (CRC, PHY header, Reed Solomon) or  it times out (SFD, Preamble or Frame).
2980
 *
2981
 * input parameters
2982
 * @param mode - this can be one of the following allowed values:
2983
 *
2984
 * DWT_START_RX_IMMEDIATE      0 used to enbale receiver immediately
2985
 * DWT_START_RX_DELAYED        1 used to set up delayed RX, if "late" error triggers, then the RX will be enabled immediately
2986
 * (DWT_START_RX_DELAYED | DWT_IDLE_ON_DLY_ERR) 3 used to disable re-enabling of receiver if delayed RX failed due to "late" error
2987
 * (DWT_START_RX_IMMEDIATE | DWT_NO_SYNC_PTRS) 4 used to re-enable RX without trying to sync IC and host side buffer pointers, typically when
2988
 *                                               performing manual RX re-enabling in double buffering mode
2989
 *
2990
 * returns DWT_SUCCESS for success, or DWT_ERROR for error (e.g. a delayed receive enable will be too far in the future if delayed time has passed)
2991
 */
2992
int dwt_rxenable(int mode)
2993
{
2994
    uint16 temp ;
2995
    uint8 temp1 ;
2996

    
2997
    if ((mode & DWT_NO_SYNC_PTRS) == 0)
2998
    {
2999
        dwt_syncrxbufptrs();
3000
    }
3001

    
3002
    temp = (uint16)SYS_CTRL_RXENAB ;
3003

    
3004
    if (mode & DWT_START_RX_DELAYED)
3005
    {
3006
        temp |= (uint16)SYS_CTRL_RXDLYE ;
3007
    }
3008

    
3009
    dwt_write16bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, temp);
3010

    
3011
    if (mode & DWT_START_RX_DELAYED) // check for errors
3012
    {
3013
        temp1 = dwt_read8bitoffsetreg(SYS_STATUS_ID, 3); // Read 1 byte at offset 3 to get the 4th byte out of 5
3014
        if ((temp1 & (SYS_STATUS_HPDWARN >> 24)) != 0) // if delay has passed do immediate RX on unless DWT_IDLE_ON_DLY_ERR is true
3015
        {
3016
            dwt_forcetrxoff(); // turn the delayed receive off
3017

    
3018
            if((mode & DWT_IDLE_ON_DLY_ERR) == 0) // if DWT_IDLE_ON_DLY_ERR not set then re-enable receiver
3019
            {
3020
                dwt_write16bitoffsetreg(SYS_CTRL_ID, SYS_CTRL_OFFSET, SYS_CTRL_RXENAB);
3021
            }
3022
            return DWT_ERROR; // return warning indication
3023
        }
3024
    }
3025

    
3026
    return DWT_SUCCESS;
3027
} // end dwt_rxenable()
3028

    
3029
/*! ------------------------------------------------------------------------------------------------------------------
3030
 * @fn dwt_setrxtimeout()
3031
 *
3032
 * @brief This call enables RX timeout (SY_STAT_RFTO event)
3033
 *
3034
 * input parameters
3035
 * @param time - how long the receiver remains on from the RX enable command
3036
 *               The time parameter used here is in 1.0256 us (512/499.2MHz) units
3037
 *               If set to 0 the timeout is disabled.
3038
 *
3039
 * output parameters
3040
 *
3041
 * no return value
3042
 */
3043
void dwt_setrxtimeout(uint16 time)
3044
{
3045
    uint8 temp ;
3046

    
3047
    temp = dwt_read8bitoffsetreg(SYS_CFG_ID, 3); // Read at offset 3 to get the upper byte only
3048

    
3049
    if(time > 0)
3050
    {
3051
        dwt_write16bitoffsetreg(RX_FWTO_ID, RX_FWTO_OFFSET, time) ;
3052

    
3053
        temp |= (uint8)(SYS_CFG_RXWTOE>>24); // Shift RXWTOE mask as we read the upper byte only
3054
        // OR in 32bit value (1 bit set), I know this is in high byte.
3055
        pdw1000local->sysCFGreg |= SYS_CFG_RXWTOE;
3056

    
3057
        dwt_write8bitoffsetreg(SYS_CFG_ID, 3, temp); // Write at offset 3 to write the upper byte only
3058
    }
3059
    else
3060
    {
3061
        temp &= ~((uint8)(SYS_CFG_RXWTOE>>24)); // Shift RXWTOE mask as we read the upper byte only
3062
        // AND in inverted 32bit value (1 bit clear), I know this is in high byte.
3063
        pdw1000local->sysCFGreg &= ~(SYS_CFG_RXWTOE);
3064

    
3065
        dwt_write8bitoffsetreg(SYS_CFG_ID, 3, temp); // Write at offset 3 to write the upper byte only
3066
    }
3067

    
3068
} // end dwt_setrxtimeout()
3069

    
3070

    
3071
/*! ------------------------------------------------------------------------------------------------------------------
3072
 * @fn dwt_setpreambledetecttimeout()
3073
 *
3074
 * @brief This call enables preamble timeout (SY_STAT_RXPTO event)
3075
 *
3076
 * input parameters
3077
 * @param  timeout - Preamble detection timeout, expressed in multiples of PAC size. The counter automatically adds 1 PAC
3078
 *                   size to the value set. Min value that can be set is 1 (i.e. a timeout of 2 PAC size).
3079
 *
3080
 *                   Note: value of 0 disables the preamble timeout
3081
 * output parameters
3082
 *
3083
 * no return value
3084
 */
3085
void dwt_setpreambledetecttimeout(uint16 timeout)
3086
{
3087
    dwt_write16bitoffsetreg(DRX_CONF_ID, DRX_PRETOC_OFFSET, timeout);
3088
}
3089

    
3090
/*! ------------------------------------------------------------------------------------------------------------------
3091
 * @fn void dwt_setinterrupt()
3092
 *
3093
 * @brief This function enables the specified events to trigger an interrupt.
3094
 * The following events can be enabled:
3095
 * DWT_INT_TFRS         0x00000080          // frame sent
3096
 * DWT_INT_RFCG         0x00004000          // frame received with good CRC
3097
 * DWT_INT_RPHE         0x00001000          // receiver PHY header error
3098
 * DWT_INT_RFCE         0x00008000          // receiver CRC error
3099
 * DWT_INT_RFSL         0x00010000          // receiver sync loss error
3100
 * DWT_INT_RFTO         0x00020000          // frame wait timeout
3101
 * DWT_INT_RXPTO        0x00200000          // preamble detect timeout
3102
 * DWT_INT_SFDT         0x04000000          // SFD timeout
3103
 * DWT_INT_ARFE         0x20000000          // frame rejected (due to frame filtering configuration)
3104
 *
3105
 *
3106
 * input parameters:
3107
 * @param bitmask - sets the events which will generate interrupt
3108
 * @param operation - if set to 1 the interrupts (only the ones selected in the bitmask) are enabled else they are cleared
3109
 *                  - if set to 2 the interrupts in the bitmask are forced to selected state - i.e. the mask is written to the register directly.
3110
 *
3111
 * output parameters
3112
 *
3113
 * no return value
3114
 */
3115
void dwt_setinterrupt(uint32 bitmask, uint8 operation)
3116
{
3117
    decaIrqStatus_t stat ;
3118
    uint32 mask ;
3119

    
3120
    // Need to beware of interrupts occurring in the middle of following read modify write cycle
3121
    stat = decamutexon() ;
3122

    
3123
    if(operation == 2)
3124
    {
3125
        dwt_write32bitreg(SYS_MASK_ID, bitmask) ; // New value
3126
    }
3127
    else
3128
    {
3129
        mask = dwt_read32bitreg(SYS_MASK_ID) ; // Read register
3130
        if(operation == 1)
3131
        {
3132
            mask |= bitmask ;
3133
        }
3134
        else
3135
        {
3136
            mask &= ~bitmask ; // Clear the bit
3137
        }
3138
        dwt_write32bitreg(SYS_MASK_ID, mask) ; // New value
3139
    }
3140

    
3141
    decamutexoff(stat) ;
3142
}
3143

    
3144
/*! ------------------------------------------------------------------------------------------------------------------
3145
 * @fn dwt_configeventcounters()
3146
 *
3147
 * @brief This is used to enable/disable the event counter in the IC
3148
 *
3149
 * input parameters
3150
 * @param - enable - 1 enables (and reset), 0 disables the event counters
3151
 * output parameters
3152
 *
3153
 * no return value
3154
 */
3155
void dwt_configeventcounters(int enable)
3156
{
3157
    // Need to clear and disable, can't just clear
3158
    dwt_write8bitoffsetreg(DIG_DIAG_ID, EVC_CTRL_OFFSET, (uint8)(EVC_CLR));
3159

    
3160
    if(enable)
3161
    {
3162
        dwt_write8bitoffsetreg(DIG_DIAG_ID, EVC_CTRL_OFFSET, (uint8)(EVC_EN)); // Enable
3163
    }
3164
}
3165

    
3166
/*! ------------------------------------------------------------------------------------------------------------------
3167
 * @fn dwt_readeventcounters()
3168
 *
3169
 * @brief This is used to read the event counters in the IC
3170
 *
3171
 * input parameters
3172
 * @param counters - pointer to the dwt_deviceentcnts_t structure which will hold the read data
3173
 *
3174
 * output parameters
3175
 *
3176
 * no return value
3177
 */
3178
void dwt_readeventcounters(dwt_deviceentcnts_t *counters)
3179
{
3180
    uint32 temp;
3181

    
3182
    temp= dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_PHE_OFFSET); // Read sync loss (31-16), PHE (15-0)
3183
    counters->PHE = temp & 0xFFF;
3184
    counters->RSL = (temp >> 16) & 0xFFF;
3185

    
3186
    temp = dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_FCG_OFFSET); // Read CRC bad (31-16), CRC good (15-0)
3187
    counters->CRCG = temp & 0xFFF;
3188
    counters->CRCB = (temp >> 16) & 0xFFF;
3189

    
3190
    temp = dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_FFR_OFFSET); // Overruns (31-16), address errors (15-0)
3191
    counters->ARFE = temp & 0xFFF;
3192
    counters->OVER = (temp >> 16) & 0xFFF;
3193

    
3194
    temp = dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_STO_OFFSET); // Read PTO (31-16), SFDTO (15-0)
3195
    counters->PTO = (temp >> 16) & 0xFFF;
3196
    counters->SFDTO = temp & 0xFFF;
3197

    
3198
    temp = dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_FWTO_OFFSET); // Read RX TO (31-16), TXFRAME (15-0)
3199
    counters->TXF = (temp >> 16) & 0xFFF;
3200
    counters->RTO = temp & 0xFFF;
3201

    
3202
    temp = dwt_read32bitoffsetreg(DIG_DIAG_ID, EVC_HPW_OFFSET); // Read half period warning events
3203
    counters->HPW = temp & 0xFFF;
3204
    counters->TXW = (temp >> 16) & 0xFFF;                       // Power-up warning events
3205

    
3206
}
3207

    
3208
/*! ------------------------------------------------------------------------------------------------------------------
3209
 * @fn dwt_rxreset()
3210
 *
3211
 * @brief this function resets the receiver of the DW1000
3212
 *
3213
 * input parameters:
3214
 *
3215
 * output parameters
3216
 *
3217
 * no return value
3218
 */
3219
void dwt_rxreset(void)
3220
{
3221
    // Set RX reset
3222
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_SOFTRESET_OFFSET, PMSC_CTRL0_RESET_RX);
3223

    
3224
    // Clear RX reset
3225
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_SOFTRESET_OFFSET, PMSC_CTRL0_RESET_CLEAR);
3226
}
3227

    
3228
/*! ------------------------------------------------------------------------------------------------------------------
3229
 * @fn dwt_softreset()
3230
 *
3231
 * @brief this function resets the DW1000
3232
 *
3233
 * input parameters:
3234
 *
3235
 * output parameters
3236
 *
3237
 * no return value
3238
 */
3239
void dwt_softreset(void)
3240
{
3241
    _dwt_disablesequencing();
3242

    
3243
    // Clear any AON auto download bits (as reset will trigger AON download)
3244
    dwt_write16bitoffsetreg(AON_ID, AON_WCFG_OFFSET, 0x00);
3245
    // Clear the wake-up configuration
3246
    dwt_write8bitoffsetreg(AON_ID, AON_CFG0_OFFSET, 0x00);
3247
    // Upload the new configuration
3248
    _dwt_aonarrayupload();
3249

    
3250
    // Reset HIF, TX, RX and PMSC (set the reset bits)
3251
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_SOFTRESET_OFFSET, PMSC_CTRL0_RESET_ALL);
3252

    
3253
    // DW1000 needs a 10us sleep to let clk PLL lock after reset - the PLL will automatically lock after the reset
3254
    // Could also have polled the PLL lock flag, but then the SPI needs to be < 3MHz !! So a simple delay is easier
3255
    deca_sleep(1);
3256

    
3257
    // Clear the reset bits
3258
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_SOFTRESET_OFFSET, PMSC_CTRL0_RESET_CLEAR);
3259

    
3260
    pdw1000local->wait4resp = 0;
3261
}
3262

    
3263
/*! ------------------------------------------------------------------------------------------------------------------
3264
 * @fn dwt_setxtaltrim()
3265
 *
3266
 * @brief This is used to adjust the crystal frequency
3267
 *
3268
 * input parameters:
3269
 * @param   value - crystal trim value (in range 0x0 to 0x1F) 31 steps (~1.5ppm per step)
3270
 *
3271
 * output parameters
3272
 *
3273
 * no return value
3274
 */
3275
void dwt_setxtaltrim(uint8 value)
3276
{
3277
    // The 3 MSb in this 8-bit register must be kept to 0b011 to avoid any malfunction.
3278
    uint8 reg_val = (3 << 5) | (value & FS_XTALT_MASK);
3279
    dwt_write8bitoffsetreg(FS_CTRL_ID, FS_XTALT_OFFSET, reg_val);
3280
}
3281

    
3282
/*! ------------------------------------------------------------------------------------------------------------------
3283
 * @fn dwt_getxtaltrim()
3284
 *
3285
 * @brief This function returns current value of XTAL trim. If this is called after dwt_initalise it will return the OTP value
3286
 * if OTP value is non-zero or FS_XTALT_MIDRANGE if OTP value is zero (not programmed).
3287
 *
3288
 * input parameters
3289
 *
3290
 * output parameters
3291
 *
3292
 * returns the current XTAL trim value
3293
 */
3294
uint8 dwt_getxtaltrim(void)
3295
{
3296
    return (dwt_read8bitoffsetreg(FS_CTRL_ID, FS_XTALT_OFFSET) & FS_XTALT_MASK);
3297
}
3298

    
3299
/*! ------------------------------------------------------------------------------------------------------------------
3300
 * @fn dwt_configcwmode()
3301
 *
3302
 * @brief this function sets the DW1000 to transmit cw signal at specific channel frequency
3303
 *
3304
 * input parameters:
3305
 * @param chan - specifies the operating channel (e.g. 1, 2, 3, 4, 5, 6 or 7)
3306
 *
3307
 * output parameters
3308
 *
3309
 * no return value
3310
 */
3311
void dwt_configcwmode(uint8 chan)
3312
{
3313
#ifdef DWT_API_ERROR_CHECK
3314
    assert((chan >= 1) && (chan <= 7) && (chan != 6));
3315
#endif
3316

    
3317
    //
3318
    // Disable TX/RX RF block sequencing (needed for cw frame mode)
3319
    //
3320
    _dwt_disablesequencing();
3321

    
3322
    // Config RF pll (for a given channel)
3323
    // Configure PLL2/RF PLL block CFG/TUNE
3324
    dwt_write32bitoffsetreg(FS_CTRL_ID, FS_PLLCFG_OFFSET, fs_pll_cfg[chan_idx[chan]]);
3325
    dwt_write8bitoffsetreg(FS_CTRL_ID, FS_PLLTUNE_OFFSET, fs_pll_tune[chan_idx[chan]]);
3326
    // PLL wont be enabled until a TX/RX enable is issued later on
3327
    // Configure RF TX blocks (for specified channel and prf)
3328
    // Config RF TX control
3329
    dwt_write32bitoffsetreg(RF_CONF_ID, RF_TXCTRL_OFFSET, tx_config[chan_idx[chan]]);
3330

    
3331
    //
3332
    // Enable RF PLL
3333
    //
3334
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXPLLPOWEN_MASK); // Enable LDO and RF PLL blocks
3335
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXALLEN_MASK); // Enable the rest of TX blocks
3336

    
3337
    //
3338
    // Configure TX clocks
3339
    //
3340
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, 0x22);
3341
    dwt_write8bitoffsetreg(PMSC_ID, 0x1, 0x07);
3342

    
3343
    // Disable fine grain TX sequencing
3344
    dwt_setfinegraintxseq(0);
3345

    
3346
    // Configure CW mode
3347
    dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGTEST_OFFSET, TC_PGTEST_CW);
3348
}
3349

    
3350
/*! ------------------------------------------------------------------------------------------------------------------
3351
 * @fn dwt_configcontinuousframemode()
3352
 *
3353
 * @brief this function sets the DW1000 to continuous tx frame mode for regulatory approvals testing.
3354
 *
3355
 * input parameters:
3356
 * @param framerepetitionrate - This is a 32-bit value that is used to set the interval between transmissions.
3357
*  The minimum value is 4. The units are approximately 8 ns. (or more precisely 512/(499.2e6*128) seconds)).
3358
 *
3359
 * output parameters
3360
 *
3361
 * no return value
3362
 */
3363
void dwt_configcontinuousframemode(uint32 framerepetitionrate)
3364
{
3365
    //
3366
    // Disable TX/RX RF block sequencing (needed for continuous frame mode)
3367
    //
3368
    _dwt_disablesequencing();
3369

    
3370
    //
3371
    // Enable RF PLL and TX blocks
3372
    //
3373
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXPLLPOWEN_MASK); // Enable LDO and RF PLL blocks
3374
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXALLEN_MASK); // Enable the rest of TX blocks
3375

    
3376
    //
3377
    // Configure TX clocks
3378
    //
3379
    _dwt_enableclocks(FORCE_SYS_PLL);
3380
    _dwt_enableclocks(FORCE_TX_PLL);
3381

    
3382
    // Set the frame repetition rate
3383
    if(framerepetitionrate < 4)
3384
    {
3385
        framerepetitionrate = 4;
3386
    }
3387
    dwt_write32bitreg(DX_TIME_ID, framerepetitionrate);
3388

    
3389
    //
3390
    // Configure continuous frame TX
3391
    //
3392
    dwt_write8bitoffsetreg(DIG_DIAG_ID, DIAG_TMC_OFFSET, (uint8)(DIAG_TMC_TX_PSTM)); // Turn the tx power spectrum test mode - continuous sending of frames
3393
}
3394

    
3395
/*! ------------------------------------------------------------------------------------------------------------------
3396
 * @fn dwt_readtempvbat()
3397
 *
3398
 * @brief this function reads the raw battery voltage and temperature values of the DW IC.
3399
 * The values read here will be the current values sampled by DW IC AtoD converters.
3400
 *
3401
 * NB: To correctly read the temperature this read should be done with xtal clock
3402
 * however that means that the receiver will be switched off, if receiver needs to be on then
3403
 * the timer is used to make sure the value is stable before reading
3404
 *
3405
 * input parameters:
3406
 * @param fastSPI - set to 1 if SPI rate > than 3MHz is used
3407
 *
3408
 * output parameters
3409
 *
3410
 * returns  (temp_raw<<8)|(vbat_raw)
3411
 */
3412
uint16 dwt_readtempvbat(uint8 fastSPI)
3413
{
3414
    uint8 wr_buf[2];
3415
    uint8 vbat_raw;
3416
    uint8 temp_raw;
3417

    
3418
    // These writes should be single writes and in sequence
3419
    wr_buf[0] = 0x80; // Enable TLD Bias
3420
    dwt_writetodevice(RF_CONF_ID,0x11,1,wr_buf);
3421

    
3422
    wr_buf[0] = 0x0A; // Enable TLD Bias and ADC Bias
3423
    dwt_writetodevice(RF_CONF_ID,0x12,1,wr_buf);
3424

    
3425
    wr_buf[0] = 0x0f; // Enable Outputs (only after Biases are up and running)
3426
    dwt_writetodevice(RF_CONF_ID,0x12,1,wr_buf);    //
3427

    
3428
    if(fastSPI == 1)
3429
    {
3430
        // Reading All SAR inputs
3431
        wr_buf[0] = 0x00;
3432
        dwt_writetodevice(TX_CAL_ID, TC_SARL_SAR_C,1,wr_buf);
3433
        wr_buf[0] = 0x01; // Set SAR enable
3434
        dwt_writetodevice(TX_CAL_ID, TC_SARL_SAR_C,1,wr_buf);
3435

    
3436
        deca_sleep(1); // If using PLL clocks(and fast SPI rate) then this sleep is needed
3437
        // Read voltage and temperature.
3438
        dwt_readfromdevice(TX_CAL_ID, TC_SARL_SAR_LVBAT_OFFSET,2,wr_buf);
3439
    }
3440
    else //change to a slow clock
3441
    {
3442
        _dwt_enableclocks(FORCE_SYS_XTI); // NOTE: set system clock to XTI - this is necessary to make sure the values read are reliable
3443
        // Reading All SAR inputs
3444
        wr_buf[0] = 0x00;
3445
        dwt_writetodevice(TX_CAL_ID, TC_SARL_SAR_C,1,wr_buf);
3446
        wr_buf[0] = 0x01; // Set SAR enable
3447
        dwt_writetodevice(TX_CAL_ID, TC_SARL_SAR_C,1,wr_buf);
3448

    
3449
        // Read voltage and temperature.
3450
        dwt_readfromdevice(TX_CAL_ID, TC_SARL_SAR_LVBAT_OFFSET,2,wr_buf);
3451
        // Default clocks (ENABLE_ALL_SEQ)
3452
        _dwt_enableclocks(ENABLE_ALL_SEQ); // Enable clocks for sequencing
3453
    }
3454

    
3455
    vbat_raw = wr_buf[0];
3456
    temp_raw = wr_buf[1];
3457

    
3458
    wr_buf[0] = 0x00; // Clear SAR enable
3459
    dwt_writetodevice(TX_CAL_ID, TC_SARL_SAR_C,1,wr_buf);
3460

    
3461
    return (((uint16)temp_raw<<8)|(vbat_raw));
3462
}
3463

    
3464
/*! ------------------------------------------------------------------------------------------------------------------
3465
 * @fn dwt_convertrawtemperature()
3466
 *
3467
 * @brief  this function takes in a raw temperature value and applies the conversion factor
3468
 * to give true temperature. The dwt_initialise needs to be called before call to this to
3469
 * ensure pdw1000local->tempP contains the SAR_LTEMP value from OTP.
3470
 *
3471
 * input parameters:
3472
 * @param raw_temp - this is the 8-bit raw temperature value as read by dwt_readtempvbat
3473
 *
3474
 * output parameters:
3475
 *
3476
 * returns: temperature sensor value in degrees
3477
 */
3478
float dwt_convertrawtemperature(uint8 raw_temp)
3479
{
3480
    float realtemp;
3481
#ifdef DWT_API_ERROR_CHECK
3482
    assert(pdw1000local->otp_mask & DWT_READ_OTP_TMP);
3483
#endif
3484
    // the User Manual formula is: Temperature (?C) = ( (SAR_LTEMP ? OTP_READ(Vtemp @ 23?C) ) x 1.14) + 23
3485
    realtemp = ((raw_temp - pdw1000local->tempP) * SAR_TEMP_TO_CELCIUS_CONV) + 23 ;
3486

    
3487
    return realtemp;
3488
}
3489

    
3490
/*! ------------------------------------------------------------------------------------------------------------------
3491
 * @fn dwt_convertdegtemptoraw()
3492
 *
3493
 * @brief  this function takes in an externally measured temperature in 10ths of degrees Celcius
3494
 * and applies the conversion factor to give a value in IC temperature units, as produced by the SAR A/D.
3495
 * The dwt_initialise needs to be called before call to this to ensure pdw1000local->tempP contains the SAR_LTEMP value from OTP.
3496
 *
3497
 * input parameters:
3498
 * @param externaltemp - this is the an externally measured temperature in 10ths of degrees Celcius to convert
3499
 *
3500
 * output parameters:
3501
 *
3502
 * returns: temperature sensor value in DW IC temperature units (1.14?C steps)
3503
 */
3504
uint8 dwt_convertdegtemptoraw(int16 externaltemp)
3505
{
3506
    int32 raw_temp;
3507
#ifdef DWT_API_ERROR_CHECK
3508
    assert(pdw1000local->otp_mask & DWT_READ_OTP_TMP);
3509
    assert((externaltemp > -800) && (externaltemp < 1500))
3510
#endif
3511
    // the User Manual formula is: Temperature (?C) = ( (SAR_LTEMP ? OTP_READ(Vtemp @ 23?C) ) x 1.14) + 23
3512
    raw_temp = ((externaltemp - 230 + 5) * DCELCIUS_TO_SAR_TEMP_CONV) ; //+5 for better rounding
3513

    
3514
    if(raw_temp < 0) //negative
3515
    {
3516
        raw_temp = (-raw_temp >> 8)  ;
3517
        raw_temp = -raw_temp ;
3518
    }
3519
    else
3520
        raw_temp = raw_temp >> 8  ;
3521

    
3522
    return (uint8) (raw_temp + pdw1000local->tempP);
3523
}
3524

    
3525
/*! ------------------------------------------------------------------------------------------------------------------
3526
 * @fn dwt_convertrawvoltage()
3527
 *
3528
 * @brief this function takes in a raw voltage value and applies the conversion factor
3529
 * to give true voltage. The dwt_initialise needs to be called before call to this to
3530
 * ensure pdw1000local->vBatP contains the SAR_LVBAT value from OTP
3531
 *
3532
 * input parameters:
3533
 * @param raw_voltage - this is the 8-bit raw voltage value as read by dwt_readtempvbat
3534
 *
3535
 * output parameters:
3536
 *
3537
 * returns: voltage sensor value in volts
3538
 */
3539
float dwt_convertrawvoltage(uint8 raw_voltage)
3540
{
3541
    float realvolt;
3542

    
3543
#ifdef DWT_API_ERROR_CHECK
3544
    assert(pdw1000local->otp_mask & DWT_READ_OTP_BAT);
3545
#endif
3546
    // the User Manual formula is: Voltage (V) = ( (SAR_LVBAT ? OTP_READ(Vmeas @ 3.3 V) ) / 173 ) + 3.3
3547
    realvolt = ((float)(raw_voltage - pdw1000local->vBatP) * SAR_VBAT_TO_VOLT_CONV) + 3.3 ;
3548

    
3549
    return realvolt;
3550
}
3551

    
3552
/*! ------------------------------------------------------------------------------------------------------------------
3553
 * @fn dwt_convertvoltstoraw()
3554
 *
3555
 * @brief  this function takes in a true voltage in millivolts and applies the conversion factor to
3556
 * give a raw DW IC value. The dwt_initialise needs to be called before call to this to
3557
 * ensure pdw1000local->vBatP contains the SAR_LVBAT value from OTP.
3558
 *
3559
 * input parameters:
3560
 * @param realvolt - this is a true voltage in millivolts to convert
3561
 *
3562
 * output parameters:
3563
 *
3564
 * returns: voltage sensor value in DW IC voltage units
3565
 */
3566
uint8 dwt_convertvoltstoraw(int32 externalmvolt)
3567
{
3568
    uint32 raw_voltage;
3569
#ifdef DWT_API_ERROR_CHECK
3570
    assert(pdw1000local->otp_mask & DWT_READ_OTP_BAT);
3571
#endif
3572
    // the User Manual formula is: Voltage (V) = ( (SAR_LVBAT ? OTP_READ(Vmeas @ 3.3 V) ) / 173 ) + 3.3
3573
    raw_voltage = ((externalmvolt - 3300) * MVOLT_TO_SAR_VBAT_CONV) + pdw1000local->vBatP ;
3574

    
3575
    return (uint8) raw_voltage;
3576
}
3577

    
3578
/*! ------------------------------------------------------------------------------------------------------------------
3579
 * @fn dwt_readwakeuptemp()
3580
 *
3581
 * @brief this function reads the temperature of the DW1000 that was sampled
3582
 * on waking from Sleep/Deepsleep. They are not current values, but read on last
3583
 * wakeup if DWT_TANDV bit is set in mode parameter of dwt_configuresleep
3584
 *
3585
 * input parameters:
3586
 *
3587
 * output parameters:
3588
 *
3589
 * returns: 8-bit raw temperature sensor value
3590
 */
3591
uint8 dwt_readwakeuptemp(void)
3592
{
3593
    return dwt_read8bitoffsetreg(TX_CAL_ID, TC_SARL_SAR_LTEMP_OFFSET);
3594
}
3595

    
3596
/*! ------------------------------------------------------------------------------------------------------------------
3597
 * @fn dwt_readwakeupvbat()
3598
 *
3599
 * @brief this function reads the battery voltage of the DW1000 that was sampled
3600
 * on waking from Sleep/Deepsleep. They are not current values, but read on last
3601
 * wakeup if DWT_TANDV bit is set in mode parameter of dwt_configuresleep
3602
 *
3603
 * input parameters:
3604
 *
3605
 * output parameters:
3606
 *
3607
 * returns: 8-bit raw battery voltage sensor value
3608
 */
3609
uint8 dwt_readwakeupvbat(void)
3610
{
3611
    return dwt_read8bitoffsetreg(TX_CAL_ID, TC_SARL_SAR_LVBAT_OFFSET);
3612
}
3613

    
3614
/*! ------------------------------------------------------------------------------------------------------------------
3615
 * @fn dwt_calcbandwidthtempadj()
3616
 *
3617
 * @brief this function determines the corrected bandwidth setting (PG_DELAY register setting)
3618
 * of the DW1000 which changes over temperature.
3619
 *
3620
 * NOTE 1: SPI Frequency must be < 3MHz.
3621
 * NOTE 2: The sleep to allow the calibration to complete is set to 1ms here, but can be as low as 10us.
3622
 *
3623
 * input parameters:
3624
 * @param target_count - uint16 - the PG count target to reach in order to correct the bandwidth
3625
 *
3626
 * output parameters:
3627
 *
3628
 * returns: (uint32) The setting to be programmed into the PG_DELAY value
3629
 */
3630
uint32 dwt_calcbandwidthtempadj(uint16 target_count)
3631
{
3632
    int i;
3633
    uint8 bit_field, curr_bw;
3634
    int32 delta_count = 0;
3635
    uint32 best_bw = 0;
3636
    uint16 raw_count = 0;
3637
    int32 delta_lowest;
3638

    
3639
    // Used to store the current values of the registers so that they can be restored after
3640
    uint8 old_pmsc_ctrl0;
3641
    uint16 old_pmsc_ctrl1;
3642
    uint32 old_rf_conf_txpow_mask;
3643

    
3644
    // Record the current values of these registers, to restore later
3645
    old_pmsc_ctrl0 = dwt_read8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET);
3646
    old_pmsc_ctrl1 = dwt_read16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET);
3647
    old_rf_conf_txpow_mask = dwt_read32bitreg(RF_CONF_ID);
3648

    
3649
    //  Set clock to XTAL
3650
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, PMSC_CTRL0_SYSCLKS_19M);
3651

    
3652
    //  Disable sequencing
3653
    dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, PMSC_CTRL1_PKTSEQ_DISABLE);
3654

    
3655
    //  Turn on CLK PLL, Mix Bias and PG
3656
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXPOW_MASK | RF_CONF_PGMIXBIASEN_MASK);
3657

    
3658
    //  Set sys and TX clock to PLL
3659
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, PMSC_CTRL0_SYSCLKS_125M | PMSC_CTRL0_TXCLKS_125M);
3660

    
3661
    // Set the MSB high for first guess
3662
    curr_bw = 0x80;
3663
    // Set starting bit
3664
    bit_field = 0x80;
3665
    // Initial lowest delta is the maximum difference that we should allow the count value to be from the target.
3666
    // If the algorithm is successful, it will be overwritten by a smaller value where the count value is closer
3667
    // to the target
3668
    delta_lowest = 300;
3669

    
3670
    for (i = 0; i < 7; i++)
3671
    {
3672
        // start with 0xc0 and test.
3673
        bit_field = bit_field >> 1;
3674
        curr_bw = curr_bw | bit_field;
3675

    
3676
        // Write bw setting to PG_DELAY register
3677
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGDELAY_OFFSET, curr_bw);
3678

    
3679
        // Set cal direction and time
3680
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGCCTRL_OFFSET, TC_PGCCTRL_DIR_CONV | TC_PGCCTRL_TMEAS_MASK);
3681

    
3682
        // Start cal
3683
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGCCTRL_OFFSET, TC_PGCCTRL_DIR_CONV | TC_PGCCTRL_TMEAS_MASK | TC_PGCCTRL_CALSTART);
3684
        // Allow cal to complete
3685
        deca_sleep(1);
3686

    
3687
        // Read count value from the PG cal block
3688
        raw_count = dwt_read16bitoffsetreg(TX_CAL_ID, TC_PGCAL_STATUS_OFFSET) & TC_PGCAL_STATUS_DELAY_MASK;
3689

    
3690
        // lets keep track of the closest value to the target in case we overshoot
3691
        delta_count = abs((int)raw_count - (int)target_count);
3692
        if (delta_count < delta_lowest)
3693
        {
3694
            delta_lowest = delta_count;
3695
            best_bw = curr_bw;
3696
        }
3697

    
3698
        // Test the count results
3699
        if (raw_count > target_count)
3700
            // Count was lower, BW was lower so increase PG DELAY
3701
            curr_bw = curr_bw | bit_field;
3702
        else
3703
            // Count was higher
3704
            curr_bw = curr_bw & (~(bit_field));
3705
    }
3706

    
3707
    // Restore old register values
3708
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, old_pmsc_ctrl0);
3709
    dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, old_pmsc_ctrl1);
3710
    dwt_write32bitreg(RF_CONF_ID, old_rf_conf_txpow_mask);
3711

    
3712
    // Returns the best PG_DELAY setting
3713
    return best_bw;
3714
}
3715

    
3716

    
3717
/*! ------------------------------------------------------------------------------------------------------------------
3718
 * @fn _dwt_computetxpowersetting()
3719
 *
3720
 * @brief this function calculates the appropriate change to the TX_POWER register to compensate
3721
 * the TX power output at different temperatures.
3722
 *
3723
 * input parameters:
3724
 * @param ref_powerreg - uint32 - the TX_POWER register value recorded when reference measurements were made
3725
 * @param power_adj - uint32 - the adjustment in power level to be made, in 0.5dB steps
3726
 *
3727
 * output parameters:
3728
 *
3729
 * returns: (uint32) The setting to be programmed into the TX_POWER register
3730
 */
3731
uint32 _dwt_computetxpowersetting(uint32 ref_powerreg, int32 power_adj)
3732
{
3733
    int8 da_attn_change, mixer_gain_change;
3734
    uint8 current_da_attn, current_mixer_gain;
3735
    uint8 new_da_attn, new_mixer_gain;
3736
    uint32 new_regval = 0;
3737
    int i;
3738

    
3739
    for(i = 0; i < 4; i++)
3740
    {
3741
        da_attn_change = 0;
3742
        mixer_gain_change = power_adj;
3743
        current_da_attn = ((ref_powerreg >> (i*8)) & 0xE0) >> 5;
3744
        current_mixer_gain = (ref_powerreg >> (i*8)) & 0x1F;
3745

    
3746
        // Mixer gain gives best performance between gain value of 4 and 20
3747
        while((current_mixer_gain + mixer_gain_change < 4) ||
3748
              (current_mixer_gain + mixer_gain_change > 20))
3749
        {
3750
            // If mixer gain goes outside bounds, adjust the DA attenuation to compensate
3751
            if(current_mixer_gain + mixer_gain_change > 20)
3752
            {
3753
                da_attn_change -= 1;
3754

    
3755
                if(da_attn_change == 0) //DA attenuation has reached the max value
3756
                {
3757
                    da_attn_change = 1; //restore the value and exit the loop - DA is at max allowed
3758
                    break;
3759
                }
3760

    
3761
                mixer_gain_change -= (int8) (MIX_DA_FACTOR);
3762
            }
3763
            else if(current_mixer_gain + mixer_gain_change < 4)
3764
            {
3765
                da_attn_change += 1;
3766

    
3767
                if(da_attn_change == 0x8) //DA attenuation has reached the min value
3768
                {
3769
                    da_attn_change = 7; //restore the value and exit the loop - DA is at min allowed
3770
                    break;
3771
                }
3772

    
3773
                mixer_gain_change += (int8) (MIX_DA_FACTOR);
3774
            }
3775
        }
3776

    
3777
        new_da_attn = (current_da_attn + da_attn_change) & 0x7;
3778
        new_mixer_gain = (current_mixer_gain + mixer_gain_change) & 0x1F;
3779

    
3780
        new_regval |= ((uint32) ((new_da_attn << 5) | new_mixer_gain)) << (i * 8);
3781
    }
3782

    
3783
    return (uint32)new_regval;
3784
}
3785

    
3786
/*! ------------------------------------------------------------------------------------------------------------------
3787
 * @fn dwt_calcpowertempadj()
3788
 *
3789
 * @brief this function determines the corrected power setting (TX_POWER setting) for the
3790
 * DW1000 which changes over temperature.
3791
 *
3792
 * Note: only ch2 or ch5 are supported, if other channel is used - the COMP factor should be calculated and adjusted
3793
 *
3794
 * input parameters:
3795
 * @param channel - uint8 - the channel at which compensation of power level will be applied: 2 or 5
3796
 * @param ref_powerreg - uint32 - the TX_POWER register value recorded when reference measurements were made
3797
 * @param delta_temp - int - the difference between current ambient temperature (raw value units)
3798
 *                                  and the temperature at which reference measurements were made (raw value units)
3799

3800
 * output parameters: None
3801
 *
3802
 * returns: (uint32) The corrected TX_POWER register value
3803
 */
3804
 uint32 dwt_calcpowertempadj(uint8 channel, uint32 ref_powerreg, int delta_temp)
3805
{
3806
    int8 delta_power;
3807
    int negative = 0;
3808

    
3809
    if(delta_temp < 0)
3810
    {
3811
        negative = 1;
3812
        delta_temp = -delta_temp; //make (-)ve into (+)ve number
3813
    }
3814

    
3815
    // Calculate the expected power differential at the current temperature
3816
    if(channel == 5)
3817
    {
3818
        delta_power = ((delta_temp * TEMP_COMP_FACTOR_CH5) >> 12); //>>12 is same as /4096
3819
    }
3820
    else if(channel == 2)
3821
    {
3822
        delta_power = ((delta_temp * TEMP_COMP_FACTOR_CH2) >> 12); //>>12 is same as /4096
3823
    }
3824
    else
3825
        delta_power = 0;
3826

    
3827
    if(negative == 1)
3828
    {
3829
        delta_power = -delta_power; //restore the sign
3830
    }
3831

    
3832
    if(delta_power == 0)
3833
        return ref_powerreg ; //no change to power register
3834

    
3835
    // Adjust the TX_POWER register value
3836
    return _dwt_computetxpowersetting(ref_powerreg, delta_power);
3837
}
3838

    
3839
/*! ------------------------------------------------------------------------------------------------------------------
3840
 * @fn dwt_calcpgcount()
3841
 *
3842
 * @brief this function calculates the value in the pulse generator counter register (PGC_STATUS) for a given PG_DELAY
3843
 * This is used to take a reference measurement, and the value recorded as the reference is used to adjust the
3844
 * bandwidth of the device when the temperature changes.
3845
 *
3846
 * NOTE 1: SPI Frequency must be < 3MHz.
3847
 * NOTE 2: The sleep to allow the calibration to complete is set to 1ms here, but can be as low as 10us.
3848
 *
3849
 * input parameters:
3850
 * @param pgdly - uint8 - the PG_DELAY to set (to control bandwidth), and to find the corresponding count value for
3851
 * output parameters: None
3852
 *
3853
 * returns: (uint16) PGC_STATUS count value calculated from the provided PG_DELAY value - used as reference for later
3854
 * bandwidth adjustments
3855
 */
3856
uint16 dwt_calcpgcount(uint8 pgdly)
3857
{
3858
    // Perform PG count read ten times and take an average to smooth out any noise
3859
    const int NUM_SAMPLES = 10;
3860
    uint32 sum_count = 0;
3861
    uint16 average_count = 0, count = 0;
3862
    int i = 0;
3863

    
3864
    // Used to store the current values of the registers so that they can be restored after
3865
    uint8 old_pmsc_ctrl0;
3866
    uint16 old_pmsc_ctrl1;
3867
    uint32 old_rf_conf_txpow_mask;
3868

    
3869
    // Record the current values of these registers, to restore later
3870
    old_pmsc_ctrl0 = dwt_read8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET);
3871
    old_pmsc_ctrl1 = dwt_read16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET);
3872
    old_rf_conf_txpow_mask = dwt_read32bitreg(RF_CONF_ID);
3873

    
3874
    //  Set clock to XTAL
3875
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, PMSC_CTRL0_SYSCLKS_19M);
3876
    //  Disable sequencing
3877
    dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, PMSC_CTRL1_PKTSEQ_DISABLE);
3878
    //  Turn on CLK PLL, Mix Bias and PG
3879
    dwt_write32bitreg(RF_CONF_ID, RF_CONF_TXPOW_MASK | RF_CONF_PGMIXBIASEN_MASK);
3880
    //  Set sys and TX clock to PLL
3881
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, PMSC_CTRL0_SYSCLKS_125M | PMSC_CTRL0_TXCLKS_125M);
3882

    
3883
    for(i = 0; i < NUM_SAMPLES; i++) {
3884
        // Write bw setting to PG_DELAY register
3885
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGDELAY_OFFSET, pgdly);
3886

    
3887
        // Set cal direction and time
3888
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGCCTRL_OFFSET, TC_PGCCTRL_DIR_CONV | TC_PGCCTRL_TMEAS_MASK);
3889

    
3890
        // Start cal
3891
        dwt_write8bitoffsetreg(TX_CAL_ID, TC_PGCCTRL_OFFSET, TC_PGCCTRL_DIR_CONV | TC_PGCCTRL_TMEAS_MASK | TC_PGCCTRL_CALSTART);
3892

    
3893
        // Allow cal to complete - the TC_PGCCTRL_CALSTART bit will clear automatically
3894
        deca_sleep(1);
3895

    
3896
        // Read count value from the PG cal block
3897
        count = dwt_read16bitoffsetreg(TX_CAL_ID, TC_PGCAL_STATUS_OFFSET) & TC_PGCAL_STATUS_DELAY_MASK;
3898

    
3899
        sum_count += count;
3900
    }
3901

    
3902
     // Restore old register values
3903
    dwt_write8bitoffsetreg(PMSC_ID, PMSC_CTRL0_OFFSET, old_pmsc_ctrl0);
3904
    dwt_write16bitoffsetreg(PMSC_ID, PMSC_CTRL1_OFFSET, old_pmsc_ctrl1);
3905
    dwt_write32bitreg(RF_CONF_ID, old_rf_conf_txpow_mask);
3906

    
3907
    average_count = (int)(sum_count / NUM_SAMPLES);
3908
    return average_count;
3909
}
3910

    
3911

    
3912
/* ===============================================================================================
3913
   List of expected (known) device ID handled by this software
3914
   ===============================================================================================
3915

3916
    0xDECA0130                               // DW1000 - MP
3917

3918
   ===============================================================================================
3919
*/
3920