fast-feedback virtual target task code on STM Nucleo

Dependencies:   mbed

Committer:
gwappa
Date:
Mon May 14 18:07:57 2018 +0000
Revision:
2:0c241937eabd
Parent:
0:f736749c33d2
Child:
13:8ea85a33e37a
add (part of) trial implementation

Who changed what in which revision?

UserRevisionLine numberNew contents of line
gwappa 0:f736749c33d2 1 #include "random.h"
gwappa 0:f736749c33d2 2 #include "mbed.h"
gwappa 0:f736749c33d2 3 #include <limits.h>
gwappa 0:f736749c33d2 4
gwappa 0:f736749c33d2 5 namespace random
gwappa 0:f736749c33d2 6 {
gwappa 0:f736749c33d2 7 AnalogIn noise(RANDOM_NOISE_PIN);
gwappa 2:0c241937eabd 8 bool initialized = false;
gwappa 0:f736749c33d2 9
gwappa 0:f736749c33d2 10 void init() {
gwappa 0:f736749c33d2 11 srand(noise.read_u16());
gwappa 2:0c241937eabd 12 initialized = true;
gwappa 2:0c241937eabd 13 }
gwappa 2:0c241937eabd 14
gwappa 2:0c241937eabd 15 uint16_t unif(const uint16_t& nlevels) {
gwappa 2:0c241937eabd 16 if (!initialized) {
gwappa 2:0c241937eabd 17 init();
gwappa 2:0c241937eabd 18 }
gwappa 2:0c241937eabd 19 return ((uint16_t)rand()) % nlevels;
gwappa 0:f736749c33d2 20 }
gwappa 0:f736749c33d2 21
gwappa 0:f736749c33d2 22 uint16_t exponential(const uint16_t& tau_ms, const uint16_t& cutoff, const unsigned int& resolution){
gwappa 2:0c241937eabd 23 if (!initialized) {
gwappa 2:0c241937eabd 24 init();
gwappa 2:0c241937eabd 25 }
gwappa 2:0c241937eabd 26
gwappa 0:f736749c33d2 27 double ftau = (double)tau_ms;
gwappa 0:f736749c33d2 28 double fcutoff = (double)cutoff;
gwappa 0:f736749c33d2 29 double cumulativeFraction = ((double)(rand() & resolution))/resolution;
gwappa 0:f736749c33d2 30
gwappa 0:f736749c33d2 31 // calculate the point (in exponential distribution) from the inverse of its cumulative density function
gwappa 0:f736749c33d2 32 double point = -ftau * log(1-cumulativeFraction);
gwappa 0:f736749c33d2 33
gwappa 0:f736749c33d2 34 // return as uint16 value.
gwappa 0:f736749c33d2 35 // if `point` is unreasonably long, then return `cutoff` instead.
gwappa 0:f736749c33d2 36 if (point > fcutoff) {
gwappa 0:f736749c33d2 37 return cutoff;
gwappa 0:f736749c33d2 38 } else {
gwappa 0:f736749c33d2 39 return (uint16_t)(point+0.5);
gwappa 0:f736749c33d2 40 }
gwappa 0:f736749c33d2 41 }
gwappa 0:f736749c33d2 42 }