7

(avery) #1
FORGE

the LED. To achieve this with Arduino code we can
create the two arrays to store ambient light sensor
data and LED state data. Using a variable to track
the current index of the arrays to write to next, and
a variable to track if the arrays have been filled yet,
we effectively create a circular array that will begin to
overwrite the old data when the whole array is filled.


const   int data_store_size =   10;

int sensor_val_store[data_store_size];
int state_store[data_store_size];

int store_cursor    =   0;
bool store_filled = false;

void    save_data_point(int sensor_val, bool    led_
state){
sensor_val_store[store_cursor] = sensor_val;
state_store[store_cursor] = led_state;

        store_cursor++;

    if  (store_cursor   >=  data_store_size){
store_filled = true;
store_cursor = 0;

}
}
The reading of the data is done when we want to
score a set of prediction model variables:


int score(int   thresh, bool    direction_is_greater){

        int correct_count   =   0;

        //  if  the store   array   isn’t   full,   then    only    read
upto the store_cursor
int count_to = store_filled ? data_store_size :

store_cursor;

        for (int    i   =   0;  i   <=  count_to;   i++){
bool pred = predict_with_params(sensor_val_
store[i], thresh, direction_is_greater);
if (pred == state_store[i]){
correct_count++;
}
}
return correct_count;
}
Finally, we can tie all of the processes together. First
we’ll take a reading of our light sensor and feed it into
our predictor function. Feed the output of the predictor
(which will be a Boolean representative if the LED
should be on or off) and set the LED to it. If the user
presses the toggle button, we want to save the new
data point and then run the model optimisation process
(because you have just added new data).
void loop(){
sensor_value = analogRead(sensor);
led_state = predict(sensor_value);
led_state= predict(sensor_val, learnt_thresh,
learnt_flip_behaviour_flag)
digitalWrite(led, led_state);

        if  (button_pressed()){
debounce_button();
save_data_point(sensor_value, !led_state);
optimise();
}
}

Play around with a night light to see how the
system quickly learns whatever your night light
preferences are!
The full code can be found ready for your tinkering
delight over at hsmag.cc/sqSuaL.

Left
These days,
marketers tell us
that every item with
digital electronics
is smart, but can it
learn? Our light can!
Free download pdf