Skip to content

Commit aac6931

Browse files
TfFromInternet example
1 parent d34940c commit aac6931

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
#include <SPI.h>
2+
#include <WiFiNINA.h>
3+
// use WiFi.h when using an ESP32
4+
// #include <WiFi.h>
5+
#include <HttpClient.h>
6+
#include <EloquentTinyML.h>
7+
8+
#define NUMBER_OF_INPUTS 1
9+
#define NUMBER_OF_OUTPUTS 1
10+
#define TENSOR_ARENA_SIZE 2*1024
11+
12+
char SSID[] = "NetworkSSID";
13+
char PASS[] = "Password";
14+
15+
// this is a server I owe that doesn't require HTTPS, you can replace with whatever server you have
16+
const char server[] = "152.228.173.213";
17+
const char path[] = "/sine.bin";
18+
19+
WiFiClient client;
20+
HttpClient http(client);
21+
22+
uint8_t *model;
23+
Eloquent::TinyML::TfLite<NUMBER_OF_INPUTS, NUMBER_OF_OUTPUTS, TENSOR_ARENA_SIZE> ml;
24+
25+
26+
27+
void setup() {
28+
Serial.begin(115200);
29+
delay(2000);
30+
31+
wifi_connect();
32+
http_get();
33+
34+
// init Tf from loaded model
35+
if (!ml.begin(model)) {
36+
Serial.println("Cannot inialize model");
37+
Serial.println(ml.errorMessage());
38+
delay(60000);
39+
}
40+
else {
41+
Serial.println("Model loaded, starting inference");
42+
}
43+
}
44+
45+
46+
void loop() {
47+
// pick up a random x and predict its sine
48+
float x = 3.14 * random(100) / 100;
49+
float y = sin(x);
50+
float input[1] = { x };
51+
float predicted = ml.predict(input);
52+
53+
Serial.print("sin(");
54+
Serial.print(x);
55+
Serial.print(") = ");
56+
Serial.print(y);
57+
Serial.print("\t predicted: ");
58+
Serial.println(predicted);
59+
delay(1000);
60+
}
61+
62+
63+
/**
64+
* Connect to wifi
65+
*/
66+
void wifi_connect() {
67+
int status = WL_IDLE_STATUS;
68+
69+
while (status != WL_CONNECTED) {
70+
Serial.print("Attempting to connect to SSID: ");
71+
Serial.println(SSID);
72+
status = WiFi.begin(SSID, PASS);
73+
74+
delay(1000);
75+
}
76+
77+
Serial.println("Connected to wifi");
78+
}
79+
80+
81+
/**
82+
* Download model from URL
83+
*/
84+
void http_get() {
85+
http.get(server, path);
86+
http.responseStatusCode();
87+
http.skipResponseHeaders();
88+
89+
int modelSize = http.contentLength();
90+
91+
Serial.print("Model size is: ");
92+
Serial.println(modelSize);
93+
Serial.println();
94+
95+
model = (uint8_t*) malloc(modelSize);
96+
97+
http.read(model, modelSize);
98+
print_model(modelSize);
99+
}
100+
101+
102+
/**
103+
* Dump model content
104+
*/
105+
void print_model(int modelSize) {
106+
Serial.print("Model content: ");
107+
108+
for (int i = 0; i < 20; i++) {
109+
Serial.print(model[i], HEX);
110+
Serial.print(' ');
111+
}
112+
113+
Serial.print(" ... ");
114+
115+
for (int i = modelSize - 20; i < modelSize; i++) {
116+
Serial.print(model[i], HEX);
117+
Serial.print(' ');
118+
}
119+
120+
Serial.println();
121+
}

0 commit comments

Comments
 (0)