1
26
27#include <Arduino_KNN.h>
28#include <Arduino_APDS9960.h>
29
30const int INPUTS = 3;
31const int CLASSES = 3;
32const int EXAMPLES_PER_CLASS = 1;
33
34
35const int K = 1;
36
37
38KNNClassifier myKNN(INPUTS);
39
40
41String label[CLASSES];
42
43
44float color[INPUTS];
45
46
47const float THRESHOLD = 0.98;
48int initialAmbient = 0;
49
50void setup() {
51
52 Serial.begin(9600);
53 while (!Serial);
54
55
56 pinMode(LEDR, OUTPUT);
57 pinMode(LEDG, OUTPUT);
58 pinMode(LEDB, OUTPUT);
59
60 if (!APDS.begin()) {
61 Serial.println("Failled to initialized APDS!");
62 while (1);
63 }
64
65 initialAmbient = readAmbient();
66
67 Serial.println("Arduino k-NN color classifier");
68
69
70 for (int currentClass = 0; currentClass < CLASSES; currentClass++) {
71
72 Serial.println("Enter an object name:");
73 label[currentClass] = readName();
74
75
76 for (int currentExample = 0; currentExample < EXAMPLES_PER_CLASS; currentExample++) {
77
78 Serial.print("Show me an example ");
79 Serial.println(label[currentClass]);
80
81
82 readColor(color);
83
84
85 myKNN.addExample(color, currentClass);
86
87 }
88 }
89}
90
91
92void loop() {
93
94 int classification;
95
96
97 while (!APDS.proximityAvailable() || APDS.readProximity() == 0) {}
98
99 Serial.println("Let me guess your object");
100
101
102 readColor(color);
103
104
105 classification = myKNN.classify(color, K);
106
107
108 Serial.println(label[classification]);
109 Serial.println();
110
111}
112
113int readAmbient() {
114 int red, green, blue, ambient;
115 while (!APDS.colorAvailable()) {};
116 APDS.readColor(red, green, blue, ambient);
117 return ambient;
118}
119
120void readColor(float color[]) {
121 int red, green, blue, ambient = 0, colorTotal = 0;
122
123
124 while (readAmbient() > initialAmbient * THRESHOLD) {}
125
126
127 while (ambient < initialAmbient * THRESHOLD) {
128
129
130 if (APDS.colorAvailable()) {
131
132
133 APDS.readColor(red, green, blue, ambient);
134 colorTotal = (red + green + blue);
135 }
136 }
137
138
139 color[0] = (float)red / colorTotal;
140 color[1] = (float)green / colorTotal;
141 color[2] = (float)blue / colorTotal;
142
143
144 Serial.print(color[0]);
145 Serial.print(",");
146 Serial.print(color[1]);
147 Serial.print(",");
148 Serial.println(color[2]);
149}
150
151
152
153String readName() {
154 String line;
155
156 while (1) {
157 if (Serial.available()) {
158 char c = Serial.read();
159
160 if (c == '\r') {
161
162 continue;
163 } else if (c == '\n') {
164 break;
165 }
166
167 line += c;
168 }
169 }
170
171 return line;
172}
Anonymous user
2 years ago
nice