% outputs c code to load weights data onto the flash memory from the
% microcontroller.
function flash_send_weights(net, com_port)

s = size(net.hidden_layer_weights);
s2 = size(net.output_layer_weights);

fclose(instrfind);

ser = serial(com_port);
%set(ser, 'BaudRate', 38400);
fopen(ser);

page_size = 528;
byte_num = -4;

clc
fprintf('SERIAL PORT OPEN\n\n');
fprintf('Sending hidden layer matrix values to serial.\n\n');

for node=1:s(2)
    for wt=1:s(1)
        % send as its value * 1000000 (6 digits of precision)
        % will need to convert back on other end
        fprintf('|');
        fprintf(ser,'%d\r', round(1000000*net.hidden_layer_weights(wt,node)));
        byte_num = byte_num+4;
        if(byte_num == page_size)
            pause(1);
            byte_num = 0;
        end
        pause(0.05);
    end
    fprintf('\nWeights for node %d sent.\n', node);
end

pause(3);
fprintf('\nSending output layer matrix values to serial.\n\n');

% send all weights for a given output node before sending those for the
% next
for node=1:s2(2)
    for wt=1:s2(1)
        % send as its value * 1000000 (6 digits of precision)
        % will need to convert back on other end
        fprintf('|');
        fprintf(ser,'%d\r', round(1000000*net.output_layer_weights(wt,node)));
        if(byte_num == page_size)
            pause(1);
            byte_num = 0;
        end
        pause(0.05);
    end
    fprintf('\nWeights for node %d sent.\n', node);
end

% send extra value. (For some reason the other end needs this)
fprintf(ser,'1234567\r');

fclose(ser);
printf('Complete!\n');
end