├── LICENSE
├── README.md
├── SENSORY_BRIDGE_FIRMWARE
├── GDFT.h
├── SENSORY_BRIDGE_FIRMWARE.ino
├── audio_transfer.h
├── bridge_fs.h
├── buttons.h
├── constants.h
├── globals.h
├── i2s_audio.h
├── knobs.h
├── led_utilities.h
├── lightshow_modes.h
├── noise_cal.h
├── p2p.h
├── presets.h
├── serial_menu.h
├── strings.h
├── system.h
├── user_config.h
└── utilities.h
└── extras
├── OSHW
├── 3D Printing
│ ├── MINI_MAST_MOUNT.stl
│ └── SENSORY_BRIDGE_BASE.stl
└── PCB
│ ├── MINI_MAST.brd
│ ├── MINI_MAST.sch
│ ├── SENSORY_BRIDGE.brd
│ └── SENSORY_BRIDGE.sch
├── img
├── 0.jpg
├── 1.jpg
├── 10.jpg
├── 11.jpg
├── 12.jpg
├── 13.jpg
├── 14.jpg
├── 15.jpg
├── 16.jpg
├── 17.png
├── 2.jpg
├── 3.jpg
├── 4.jpg
├── 5.jpg
├── 6.jpg
├── 7.jpg
├── 8.jpg
├── 9.jpg
├── app_icon.jpg
├── firmware_settings.png
├── firmware_settings_300.png
├── get_you.jpg
├── nina.jpg
├── on_the_run.jpg
├── oshw_facts.svg
├── plantasia.jpg
├── street_by_street.jpg
└── trustful_hands.jpg
└── misc
├── audio_transfer.html
├── bpm.h
├── fft_fixed.h
├── fix_fft.c
├── fix_fft.h
└── onsets.h
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 | https://github.com/connornishijima/SensoryBridge/assets/5051485/211737f4-0c69-49b0-99c4-2fa3d6a7a65e
2 |
3 | # SENSORY BRIDGE is **DIFFERENT**
4 |
5 | **This isn't the usual "sound-reactive LEDs" you've seen for years.**
6 |
7 | **Sensory Bridge is built from the ground up as an open, powerful bridge between sight and sound.** With a show that's reactive to notation, vibrato and more, it produces very unique and pleasant-to-look-at light shows which synchronize to your music without any visible latency. (A built-in MEMS microphone constantly studies what it hears using a special-sauce Goertzel-based Discrete Fourier Transform, at 100 FPS!)
8 |
9 | It has to be seen to be believed, *which the video demos below can help with:*
10 |
11 | [](https://www.youtube.com/watch?v=trJYa3U8nCU)
12 | [](https://www.youtube.com/watch?v=0EICjxSjveM)
13 | [](https://www.youtube.com/watch?v=RWJjWcHplGc)
14 | [](https://www.youtube.com/watch?v=lk1oRJr7TGo)
15 | [](https://www.youtube.com/watch?v=Hz8LxBKy5SI)
16 | [](https://www.youtube.com/watch?v=OXu3x7s3SVE)
17 |
18 | #
19 |
20 | 
21 |
22 | # SENSORY BRIDGE is **SIMPLE**
23 |
24 | **Easy controls provide quick access to changing the brightness, color, and smoothing of the display!**
25 |
26 | # **KNOBS**
27 |
28 | ## PHOTONS KNOB
29 |
30 | Too bright? *Dim down the show* with the **PHOTONS** knob. The FastLED code in the firmware will use dithering to keep producing color nicely at lower brightness levels.
31 |
32 | ## CHROMA KNOB
33 |
34 | Custom color or automated color based on the music's notation? Choose with the **CHROMA** knob, where turning it all the way to the top enables automated color changes.
35 |
36 | ## MOOD KNOB
37 |
38 | This knob is special. **MOOD** controls *how quickly your LEDs will react to changes in pitch and volume!* A low "mood" will be very soft and gradual, only showing things like the underlying chord progression of a song, whereas a *high* "mood" will be extremely reactive, and can be a little too flashy for some people's liking. Luckily, you can blend the value to anywhere between those two extremes whenever you want to find what look you prefer!
39 |
40 | #
41 |
42 | 
43 |
44 | # **BUTTONS**
45 |
46 | ## NOISE BUTTON
47 |
48 | Running the A/C? Is the washing machine suddenly on the spin cycle? Don't worry, just pause the music for a moment and press the **NOISE BUTTON** to run a 3-second calibration to *automagically* have noisy background ambience removed from your light show.
49 |
50 | ## MODE BUTTON
51 |
52 | Sensory Bridge currently has 6 built-in light show modes that you can cycle through:
53 |
54 | ### "Spectrogram Mode"
55 |
56 | This is the default show seen in the videos, based on Discrete Fourier Transform data. Each octave of notation shown on the display has a spectrum of colors for the individual notes, which are lit in sync with your music!
57 |
58 | ### "Chromagram Mode"
59 |
60 | Similar to Spectrogram Mode, but all octaves of notes are rolled into one! Best with the **MOOD** knob at a low to medium setting.
61 |
62 | ### "Bloom Mode"
63 |
64 | This mode differs from the others. The intensity of the audio is shown in the center of the LED strip, and is diffused outward in a non-linear fashion as time passes, leading to a 2001 "Stargate Sequence" effect!. Color is derived from the notes your music is playing.
65 |
66 | ### "Bloom Mode" (Faster)
67 |
68 | Same as above, but double the speed for when you're partying hard!
69 |
70 | ### "VU Meter Mode"
71 |
72 | It's a classic! A bouncing bar graph represents the current loudness of the music.
73 |
74 | ### "VU Meter Mode (Dot)"
75 |
76 | Same as above, but represented with a dot instead of a bar, staying a constant brightness.
77 |
78 | ## ***MORE MODES WILL BE RELEASED IN FUTURE FIRMWARE UPDATES!***
79 |
80 | #
81 |
82 | 
83 |
84 | # **SWEET SPOT**
85 |
86 | At the front of the base unit are three LEDs, which indicate if your music is playing too quietly for the auto-ranger to account for, or if it's too loud! (Close to clipping!)
87 |
88 | #
89 |
90 | 
91 |
92 | # SENSORY BRIDGE is **FLEXIBLE**
93 |
94 | While compatible with any WS2812B or APA102/SK9822-based LED strip (just use the screw terminals at the back!) there's also the option of using the **"Mini Mast"**, a dense strip of 128 1.5mm RGB LEDs on a 260mm long PCB! It just plugs directly into the Sensory Bridge accessory port, making for a very portable solution!
95 |
96 | #
97 |
98 | 
99 |
100 | # SENSORY BRIDGE is **OPEN**
101 |
102 | --------------------------------------------------------
103 |
104 | ### NOTE: This repo is used for active development.
105 |
106 | For the latest stable release of the Sensory Bridge firmware, **[visit the Releases page](https://github.com/connornishijima/SensoryBridge/releases)**! (Cloning straight from this repo is much like a "nightly" build, and may be broken code!)
107 |
108 | --------------------------------------------------------
109 |
110 | Powered by an ESP32-S2, Sensory Bridge can be easily reprogrammed for any purpose you'd like! The firmware is [open source](https://github.com/connornishijima/SensoryBridge) under the [MIT License](https://github.com/connornishijima/SensoryBridge/blob/main/LICENSE), so modifying it for your own purposes is quick and easy with the Arduino IDE. You can even download the [board](https://github.com/connornishijima/SensoryBridge/tree/main/extras/OSHW/PCB) and [case STLs](https://github.com/connornishijima/SensoryBridge/tree/main/extras/OSHW/3D%20Printing) to build one yourself!
111 |
112 | 
113 |
114 | #
115 |
116 | 
117 |
118 | # WHAT'S **INCLUDED:**
119 |
120 | For $50, you'll receive a ***fully assembled Sensory Bridge***, with the latest firmware already installed. For $25 extra, you can have a **Mini Mast** (128 micro-LED PCB, seen above) sent as well, with an accompanying brace that provides rigidity. (It just plugs right into the accessory port on top of Sensory Bridge!)
121 |
122 | # EXTRAS YOU **MIGHT NEED:**
123 |
124 | ## **PAY CLOSE ATTENTION TO THIS SECTION!**
125 |
126 | To save on redundant materials you might already own, **your Sensory Bridge does *not* come with the following items:**
127 |
128 | - **WS2812B LED Strip** - "144-LEDs per meter" variants are recommended, you can cut the 16 excess LEDs off of the end of the strip or reconfigure your device to interpolate to the 144-LED length at a slightly lower frame rate. ([AMAZON LINK](https://www.amazon.com/WS2812B-Individual-Addressable-144Pixels-Non-Waterproof/dp/B09PBHJG6G/ref=sr_1_5?crid=3KPXUN3NEV06Q&keywords=ws2812b%2Bled%2Bstrip%2B144&qid=1662389723&sprefix=ws2812b%2Bled%2Bstrip%2B144%2Caps%2C128&sr=8-5&th=1))
129 | - **USB-C Cable** ([AMAZON LINK](https://www.amazon.com/JSAUX-Charger-Braided-Compatible-Samsung/dp/B076FPGWNZ/ref=sr_1_9?crid=2YG0J3B874G73&keywords=usb-c+cable&qid=1662388265&sprefix=usb-c+cable%2Caps%2C137&sr=8-9))
130 | - **5V, 2A USB Power Adapter** ([AMAZON LINK](https://www.amazon.com/Certified-Charger-FONKEN-Universal-Compatible/dp/B07DF782WQ/ref=sr_1_4?crid=1WJDP9XHVR3QC&keywords=2a+usb+adapter&qid=1662388344&sprefix=2a+usb+adapter%2Caps%2C131&sr=8-4))
131 | - **Wire Stripper** - If you'd like to use your Sensory Bridge with your own LED strip, you'll either need a wire stripper or strong teeth to get it hooked up neatly! These clamp-style strippers make that process a breeze, so please don't use your teeth: ([AMAZON LINK](https://www.amazon.com/Self-Adjusting-Stripper-Klein-Tools-11061/dp/B00CXKOEQ6/ref=sr_1_5?crid=UIAP8SCLPER3&keywords=wire+strippers&qid=1662390513&sprefix=wire+strippers%2Caps%2C141&sr=8-5))
132 |
133 | #
134 |
135 | 
136 |
137 | # FUTURE **PLANS**
138 |
139 | Sensory Bridge is going to undergo some upgrades in the following months! You'll be able to easily [update to the latest firmware in minutes with this guide](DEAD LINK).
140 |
141 | **Currently planned features are:**
142 |
143 | ## WiFi Features
144 |
145 | Planned for Q1 2023 is a mobile / web app for iOS and Android that will allow users to remotely tweak their display from the couch! This will provide a way to adjust dozens of settings that otherwise couldn't be accessed through just two physical buttons.
146 |
147 | ## More Lightshow Modes
148 |
149 | Currently in development is a system of determining and synchronizing to the BPM of the playing music. Combining this data with the GDFT could mean deducing time signatures, along with musical keys and chord progressions - just another avenue for providing an immersive show!
150 |
151 | 
152 |
153 | ## Support For Line-In Audio
154 |
155 | The accessory port exposes GPIO 17/18 of the ESP32-S2, which are analog inputs. In the future, a PCB can be made to allow Sensory Bridge to use hardwired, passthrough audio via two 3.5mm jacks. This concept does not interfere with the Mini Mast, and the two accessories will be stackable with a modified brace.
156 |
157 | 
158 |
159 | # **GETTING STARTED**
160 |
161 | The **[GETTING STARTED](https://sensorybridge.rocks/tutorial/) GUIDE** will walk you through the quick-and-easy setup process!
162 |
163 | # **DISCLAIMER**
164 |
165 | ## **Those with [Photosensitive Epilepsy](https://en.wikipedia.org/wiki/Photosensitive_epilepsy) (PSE) should NOT purchase, operate, or otherwise view Sensory Bridge under any condition.**
166 |
167 | ## **The seller assumes no legal liability for injury caused to persons with PSE that have ignored this warning.**
168 |
169 | # **SPONSORS**
170 |
171 | - **[mlctrez](https://github.com/mlctrez)**
172 | - **[zxcasd](https://github.com/zxcasd-zxcasd)**
173 |
174 | # **CREDITS**
175 |
176 | Developed by Connor Nishijima for Lixie Labs (2022)
177 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/GDFT.h:
--------------------------------------------------------------------------------
1 | //
2 | // Welcome to the GDFT file: this is the core of Sensory Bridge.
3 | // This is where time-domain audio is converted into a
4 | // frequency-domain representation for your viewing pleasure. This
5 | // file doesn't actually contain LED code. That's lightshow_modes.h,
6 | // which references values calculated here on each frame.
7 | //
8 | // It's not FFT. It's a Goertzel-based Discrete Fourier Transform,
9 | // or what I'm calling a "GDFT". The Goertzel algorithm detects the
10 | // presence/magnitude of a single frequency in a signal, and in
11 | // this case I'm running 64 instances of Goertzel at once on the
12 | // 64 frequencies set in constants.h.
13 | //
14 | // https://en.wikipedia.org/wiki/Goertzel_algorithm
15 | //
16 | // This is slightly slower than FFT, but allows for two really
17 | // neat tricks:
18 | //
19 | // 1. I can scale the frequency range however I'd like.
20 | //
21 | // With an FFT of size 128 at a sample rate of 10KHz, you'd get
22 | // back 64 bins between 0Hz (useless) and 5KHz. These aren't
23 | // evenly spaced bins though, with frequency increasing by a
24 | // linear amount between bins, unlike the keys of a piano where
25 | // every 12th note is doubled in frequency.
26 | //
27 | // By running Goertzel's algorithm 64 times in parallel I can
28 | // choose my own bin spacing, and in this case Sensory Bridge is
29 | // watching the upper 64 keys of an 88-key piano's frequency
30 | // range: 110Hz to 4186Hz (by default).
31 | //
32 | // This means that every "half-step" up in pitch in an
33 | // instrument is it's own distinct frequency bin, with only
34 | // a small amount of spectral leakage.
35 | //
36 | // 2. Each bin can get their own settings that are best for it
37 | //
38 | // I can individually control the window length (which doesn't
39 | // have to be a power of two like FFT) of each bin, to keep
40 | // a good balance between temporal and pitch resolution across
41 | // the frequency range. This also helps with speed, as the
42 | // higher frequencies require smaller window lengths and thus
43 | // have less work to do solving the magnitudes than the lower
44 | // frequencies.
45 | //
46 | //
47 | // This GDFT method, which operates on a sliding window with 256
48 | // new samples per frame, (i2s_audio.h) combined with a shitload
49 | // of interesting post-processing methods I've documented below
50 | // are what's behind the eye-catching shows on Sensory Bridge!
51 | //
52 | // If you like that I've shared this code, *please* support my work
53 | // by purchasing genuine hardware or telling your friends about it!
54 | //
55 | // https://github.com/sponsors/connornishijima
56 | // LIXIE LABS
57 |
58 | // Obscure audio magic happens here
59 | void IRAM_ATTR process_GDFT() {
60 | float MOOD_VAL = CONFIG.MOOD;
61 | if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_BLOOM) {
62 | MOOD_VAL = 1.0;
63 | }
64 |
65 | static bool interlace_flip = false;
66 | interlace_flip = !interlace_flip; // Switch field every frame on lower notes to save execution time
67 |
68 | // Reset magnitude caps every frame
69 | for (uint8_t i = 0; i < NUM_ZONES; i++) {
70 | max_mags[i] = 0.0; // Higher than the average noise floor
71 | }
72 |
73 | // Increment spectrogram history index
74 | spectrogram_history_index++;
75 | if (spectrogram_history_index >= spectrogram_history_length) {
76 | spectrogram_history_index = 0; // wrap to index zero at end
77 | }
78 |
79 | // Run GDFT (Goertzel-based Discrete Fourier Transform) with 64 frequencies
80 | // Fixed-point code adapted from example here: https://sourceforge.net/p/freetel/code/HEAD/tree/misc/goertzal/goertzal.c
81 | for (uint16_t i = 0; i < NUM_FREQS; i++) { // Run 64 times
82 | int32_t q0, q1, q2;
83 | int64_t mult;
84 |
85 | q1 = 0;
86 | q2 = 0;
87 |
88 | float window_pos = 0.0;
89 | for (uint16_t n = 0; n < frequencies[i].block_size; n++) { // Run Goertzel for "block_size" iterations
90 | int32_t sample = 0;
91 | //sample = ((int32_t)sample_window[SAMPLE_HISTORY_LENGTH - 1 - n] * (int32_t)window_lookup[uint16_t(window_pos)]) >> 16;
92 | sample = (int32_t)sample_window[SAMPLE_HISTORY_LENGTH - 1 - n];
93 | mult = (int32_t)frequencies[i].coeff_q14 * (int32_t)q1;
94 | q0 = (sample >> 6) + (mult >> 14) - q2;
95 | q2 = q1;
96 | q1 = q0;
97 |
98 | window_pos += frequencies[i].window_mult;
99 | }
100 |
101 | mult = (int32_t)frequencies[i].coeff_q14 * (int32_t)q1;
102 | magnitudes[i] = q2 * q2 + q1 * q1 - ((int32_t)(mult >> 14)) * q2; // Calculate raw magnitudes
103 |
104 | if (magnitudes[i] < 0) { // Prevent negative values
105 | magnitudes[i] = 0;
106 | }
107 |
108 | magnitudes[i] = sqrt(magnitudes[i]);
109 |
110 | // Normalizing the magnitude
111 | float normalized_magnitude = magnitudes[i] / float(frequencies[i].block_size / 2.0);
112 | magnitudes_normalized[i] = normalized_magnitude;
113 |
114 | if (frequencies[i].target_freq == 440.0) {
115 | //USBSerial.println(magnitudes_normalized[i]);
116 | }
117 |
118 | magnitudes_normalized_avg[i] = (magnitudes_normalized[i] * 0.3) + (magnitudes_normalized_avg[i] * (1.0 - 0.3));
119 | }
120 |
121 | // Gather noise data if noise_complete == false
122 | if (noise_complete == false) {
123 | for (uint8_t i = 0; i < NUM_FREQS; i += 1) {
124 | if (magnitudes_normalized_avg[i] > noise_samples[i]) {
125 | noise_samples[i] = magnitudes_normalized_avg[i];
126 | }
127 | }
128 | noise_iterations++;
129 | if (noise_iterations >= 256) { // Calibration complete
130 | noise_complete = true;
131 | USBSerial.println("NOISE CAL COMPLETE");
132 | CONFIG.DC_OFFSET = dc_offset_sum / 256.0; // Calculate average DC offset and store it
133 | save_ambient_noise_calibration(); // Save results to noise_cal.bin
134 | save_config(); // Save config to config.bin
135 | }
136 | }
137 |
138 | // Apply noise reduction data
139 | for (uint8_t i = 0; i < NUM_FREQS; i += 1) {
140 | if (noise_complete == true) {
141 | magnitudes_normalized_avg[i] -= float(noise_samples[i] * SQ15x16(1.5)); // Treat noise 1.5x louder than calibration
142 | if (magnitudes_normalized_avg[i] < 0.0) {
143 | magnitudes_normalized_avg[i] = 0.0;
144 | }
145 | }
146 | }
147 |
148 | memcpy(magnitudes_final, magnitudes_normalized_avg, sizeof(float) * NUM_FREQS);
149 | low_pass_array(magnitudes_final, magnitudes_last, NUM_FREQS, SYSTEM_FPS, 1.0 + (10.0 * MOOD_VAL));
150 | memcpy(magnitudes_last, magnitudes_final, sizeof(float) * NUM_FREQS);
151 |
152 | /*
153 | // When enabled, streams magnitudes[] array over Serial
154 | if (stream_magnitudes == true) {
155 | if (serial_iter >= 2) { // Don't print every frame
156 | serial_iter = 0;
157 | USBSerial.print("sbs((magnitudes=");
158 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
159 | USBSerial.print(uint32_t(magnitudes[i]));
160 | if (i < NUM_FREQS - 1) {
161 | USBSerial.print(',');
162 | }
163 | }
164 | USBSerial.println("))");
165 | }
166 | }
167 | */
168 |
169 | static SQ15x16 goertzel_max_value = 0.0001;
170 | SQ15x16 max_value = 0.00001;
171 |
172 | for (uint8_t i = 0; i < NUM_FREQS; i += 1) { // 64 freqs
173 | if (magnitudes_final[i] > max_value) {
174 | max_value = magnitudes_final[i];
175 | }
176 | }
177 |
178 | max_value *= SQ15x16(0.995);
179 |
180 | if (max_value > goertzel_max_value) {
181 | SQ15x16 delta = max_value - goertzel_max_value;
182 | goertzel_max_value += delta * SQ15x16(0.0050);
183 | } else if (goertzel_max_value > max_value) {
184 | SQ15x16 delta = goertzel_max_value - max_value;
185 | goertzel_max_value -= delta * SQ15x16(0.0025);
186 | }
187 |
188 | if (goertzel_max_value < 4.0) {
189 | goertzel_max_value = 4.0;
190 | }
191 |
192 | // Normalize output using goertzel_max_val
193 | SQ15x16 multiplier = SQ15x16(1.0) / goertzel_max_value;
194 | //multiplier += SQ15x16(0.10); // Overshoot by 10%
195 |
196 | for (uint16_t i = 0; i < NUM_FREQS; i += 1) {
197 | spectrogram[i] = magnitudes_final[i] * multiplier;
198 | }
199 | }
200 |
201 | void calculate_novelty(uint32_t t_now) {
202 | static uint32_t iter = 0;
203 | iter++;
204 |
205 | // Calculate "novelty" (positive change) in this moment by marking the positive changes from the previous frame
206 | // Sum in a column-wise fashion into novelty_now
207 | SQ15x16 novelty_now = 0.0;
208 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
209 | int16_t rounded_index = spectral_history_index - 1;
210 | while (rounded_index < 0) {
211 | rounded_index += SPECTRAL_HISTORY_LENGTH;
212 | }
213 | SQ15x16 novelty_bin = spectrogram[i] - spectral_history[rounded_index][i];
214 |
215 | if (novelty_bin < 0.0) {
216 | novelty_bin = 0.0;
217 | }
218 |
219 | novelty_now += novelty_bin;
220 | }
221 | novelty_now /= NUM_FREQS; // Normalize result
222 |
223 | // Append current spectrogram to last place in history:
224 | for (uint16_t b = 0; b < NUM_FREQS; b += 8) {
225 | spectral_history[spectral_history_index][b + 0] = spectrogram[b + 0];
226 | spectral_history[spectral_history_index][b + 1] = spectrogram[b + 1];
227 | spectral_history[spectral_history_index][b + 2] = spectrogram[b + 2];
228 | spectral_history[spectral_history_index][b + 3] = spectrogram[b + 3];
229 | spectral_history[spectral_history_index][b + 4] = spectrogram[b + 4];
230 | spectral_history[spectral_history_index][b + 5] = spectrogram[b + 5];
231 | spectral_history[spectral_history_index][b + 6] = spectrogram[b + 6];
232 | spectral_history[spectral_history_index][b + 7] = spectrogram[b + 7];
233 | }
234 |
235 | // Append new novelty measurement to novelty curve history
236 | novelty_curve[spectral_history_index] = sqrt(float(novelty_now));
237 |
238 | spectral_history_index++;
239 | if (spectral_history_index >= SPECTRAL_HISTORY_LENGTH) {
240 | spectral_history_index -= SPECTRAL_HISTORY_LENGTH;
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/SENSORY_BRIDGE_FIRMWARE.ino:
--------------------------------------------------------------------------------
1 | /*------------------------------------------------------------------------------------------------------------------------------------
2 |
3 | ###### ######## ## ## ###### #### ####### ## ## ###### ####### #### ####### ###### ########
4 | ## ## ## ### ## ## ## ## ## ## ## ### ### ## ## ## ## ## ## ## ### ### ##
5 | ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
6 | ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ### ## ## ## ## ##
7 | ## ###### ## ## ## ## ## ## ###### #### ###### ###### ## ## ## ## ######
8 | ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ##
9 | ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
10 | ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ### ##
11 | ###### ######## ## ## ###### #### ## ## ## ###### ## ## #### ####### ###### ########
12 |
13 | by @lixielabs (2022 - 2023)
14 |
15 | ####################################################################
16 |
17 | Welcome to the Sensory Bridge firmware files!
18 |
19 | WARNING:
20 |
21 | If the above ASCII art is not showing "SENSORY BRIDGE" correctly,
22 | you're probably on < Arduino 2.1.0. This means you'll need to make a
23 | few changes for this firmware to work.
24 |
25 | ####################################################################
26 |
27 | 1. DISABLE WORD WRAPPING -------------------------------------------
28 |
29 | (This will guarantee code and docs are more readable)
30 |
31 | - In the Arduino 2.0.x IDE, hit F1
32 | - In the textbox that appears, type "wrap"
33 | - You'll see a result for "View - Toggle Word Wrap"
34 | - Click this item
35 | - Repeat at least once until buggy word-wrapping is actually disabled
36 | - This is a painful change that the IDE 1.x didn't do
37 | (In fact no other IDE I've ever used does this, ugh.)
38 |
39 | 2. DISABLE DEFAULT COMPILATION WARNING BEHAVIOR --------------------
40 |
41 | (This will make the firmware actually usable)
42 |
43 | - In the Arduino 2.0.x IDE, click "File > Preferences"
44 | - Set "Compiler Warnings" to "Default"
45 | - This is because some dependencies below trigger ignorable warnings
46 | - Arduino IDE 2.0.0 treats all warnings as errors by default.
47 | - This is a *painful* change that the IDE 1.x didn't do
48 |
49 | Anyways, let's begin!
50 |
51 | ---------------------------------------------------------------------*/
52 |
53 | #define FIRMWARE_VERSION 40101 // Try "V" on the Serial port for this!
54 | // MmmPP M = Major version, m = Minor version, P = Patch version
55 | // (i.e 3.5.4 would be 30504)
56 |
57 | // Lightshow modes by name -----------------------------------------------------------
58 | enum lightshow_modes {
59 | LIGHT_MODE_GDFT, // ------------- GDFT - Goertzel-based Discrete Fourier Transform
60 | // (I made this name up. Saved you a search.)
61 | LIGHT_MODE_GDFT_CHROMAGRAM, // -- Chromagram of GDFT
62 | LIGHT_MODE_GDFT_CHROMAGRAM_DOTS, // -- Chromagram of GDFT
63 | LIGHT_MODE_BLOOM, // -- Bloom Mode
64 | LIGHT_MODE_VU_DOT, // -- Not a real VU for any measurement sake, just a dance-y LED show
65 | LIGHT_MODE_KALEIDOSCOPE, // -- Three color channels 2D Perlin noise affected by the onsets of low, mid and high pitches
66 |
67 | NUM_MODES // used to know the length of this list if it changes in the future
68 | };
69 |
70 | // External dependencies -------------------------------------------------------------
71 | #include // Needed for Station Mode
72 | #include // P2P wireless communication library (p2p.h below)
73 | #include // RNG Functions
74 | #include // Handles LED color data and display
75 | #include // Filesystem functions (bridge_fs.h below)
76 | #include // LittleFS implementation
77 | #include // Scheduled tasks library
78 | #include // USB Connection handling
79 | #include // Allows firmware updates via USB MSC
80 | #include
81 | #include
82 |
83 | // Include Sensory Bridge firmware files, sorted high to low, by boringness ;) -------
84 | #include "strings.h" // Strings for printing
85 | #include "user_config.h" // Nothing for now
86 | #include "constants.h" // Global constants
87 | #include "globals.h" // Global variables
88 | #include "presets.h" // Configuration presets by name
89 | #include "bridge_fs.h" // Filesystem access (save/load configuration)
90 | #include "utilities.h" // Misc. math and other functions
91 | #include "i2s_audio.h" // I2S Microphone audio capture
92 | #include "led_utilities.h" // LED color/transform utility functions
93 | #include "noise_cal.h" // Background noise removal
94 | #include "p2p.h" // Sensory Sync handling
95 | #include "buttons.h" // Watch the status of buttons
96 | #include "knobs.h" // Watch the status of knobs...
97 | #include "serial_menu.h" // Watch the Serial port... *sigh*
98 | #include "system.h" // Watch how fast I can check if settings were updated... yada yada..
99 | #include "GDFT.h" // Conversion to (and post-processing of) frequency data! (hey, something cool!)
100 | #include "lightshow_modes.h" // --- FINALLY, the FUN STUFF!
101 |
102 | // Setup, runs only one time ---------------------------------------------------------
103 | void setup() {
104 | init_system(); // (system.h) Initialize all hardware and arrays
105 |
106 | // Create thread specifically for LED updates
107 | xTaskCreatePinnedToCore(led_thread, "led_task", 8192, NULL, tskIDLE_PRIORITY + 1, &led_task, 1);
108 | }
109 |
110 | // Loop, runs forever after setup() --------------------------------------------------
111 | void loop() {
112 | uint32_t t_now_us = micros(); // Timestamp for this loop, used by some core functions
113 | uint32_t t_now = t_now_us / 1000.0; // Millisecond version
114 |
115 | function_id = 0; // These are for debug_function_timing() in system.h to see what functions take up the most time
116 | check_knobs(t_now); // (knobs.h)
117 | // Check if the knobs have changed
118 |
119 | function_id = 1;
120 | check_buttons(t_now); // (buttons.h)
121 | // Check if the buttons have changed
122 |
123 | function_id = 2;
124 | check_settings(t_now); // (system.h)
125 | // Check if the settings have changed
126 |
127 | function_id = 3;
128 | check_serial(t_now); // (serial_menu.h)
129 | // Check if UART commands are available
130 |
131 | function_id = 4;
132 | run_p2p(); // (p2p.h)
133 | // Process P2P network packets to synchronize units
134 |
135 | function_id = 5;
136 | acquire_sample_chunk(t_now); // (i2s_audio.h)
137 | // Capture a frame of I2S audio (holy crap, FINALLY something about sound)
138 |
139 | function_id = 6;
140 | run_sweet_spot(); // (led_utilities.h)
141 | // Based on the current audio volume, alter the Sweet Spot indicator LEDs
142 |
143 | // Calculates audio loudness (VU) using RMS, adjusting for noise floor based on calibration
144 | calculate_vu();
145 |
146 | function_id = 7;
147 | process_GDFT(); // (GDFT.h)
148 | // Execute GDFT and post-process
149 | // (If you're wondering about that weird acronym, check out the source file)
150 |
151 | // Watches the rate of change in the Goertzel bins to guide decisions for auto-color shifting
152 | calculate_novelty(t_now);
153 |
154 | if (CONFIG.AUTO_COLOR_SHIFT == true) { // Automatically cycle color based on density of positive spectral changes
155 | // Use the "novelty" findings of the above function to affect color shifting when auto-color shifts are enabled
156 | process_color_shift();
157 | } else {
158 | hue_position = 0;
159 | hue_shifting_mix = -0.35;
160 | }
161 |
162 | function_id = 8;
163 | //lookahead_smoothing(); // (GDFT.h)
164 | // Peek at upcoming frames to study/prevent flickering
165 |
166 | function_id = 8;
167 | log_fps(t_now_us); // (system.h)
168 | // Log the audio system FPS
169 |
170 | if (debug_mode == true) {
171 | function_id = 31;
172 | debug_function_timing(t_now);
173 | }
174 |
175 | yield(); // Otherwise the ESP32 will collapse into a black hole or something
176 | }
177 |
178 | // Run the lights in their own thread! -------------------------------------------------------------
179 | void led_thread(void* arg) {
180 | while (true) {
181 | if (led_thread_halt == false) { // If we're not gathering ambient noise data
182 | if (mode_transition_queued == true || noise_transition_queued == true) { // If transition queued
183 | run_transition_fade(); // (led_utilities.h) Fade to black between modes
184 | }
185 |
186 | get_smooth_spectrogram();
187 | make_smooth_chromagram();
188 |
189 | // Based on the value of CONFIG.LIGHTSHOW_MODE, we call a
190 | // different rendering function from lightshow_modes.h:
191 |
192 | if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_GDFT) {
193 | light_mode_gdft(); // (lightshow_modes.h) GDFT spectrogram display
194 | } else if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_GDFT_CHROMAGRAM) {
195 | light_mode_chromagram_gradient(); //light_mode_chromagram_gradient(); // (lightshow_modes.h) GDFT chromagram display
196 | } else if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_GDFT_CHROMAGRAM_DOTS) {
197 | light_mode_chromagram_dots(); //light_mode_chromagram_dots(); // (lightshow_modes.h) GDFT chromagram display
198 | } else if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_BLOOM) {
199 | light_mode_bloom(); // (lightshow_modes.h) Bloom Mode display
200 | } else if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_VU_DOT) {
201 | light_mode_vu_dot(); // (lightshow_modes.h) VU Mode display (dot version)
202 | } else if (CONFIG.LIGHTSHOW_MODE == LIGHT_MODE_KALEIDOSCOPE) {
203 | light_mode_kaleidoscope(); // (lightshow_modes.h) Kaleidoscope Mode display
204 | }
205 |
206 | if (CONFIG.PRISM_COUNT > 0) {
207 | apply_prism_effect(CONFIG.PRISM_COUNT, 0.25);
208 | }
209 |
210 | // Render bulb filter
211 | if (CONFIG.BULB_OPACITY > 0.00) {
212 | render_bulb_cover();
213 | }
214 |
215 | // If forcing monochromatic incandescent output
216 | if (CONFIG.INCANDESCENT_MODE == true) {
217 | for (uint8_t i = 0; i < NATIVE_RESOLUTION; i++) {
218 | leds_16[i] = adjust_hue_and_saturation(leds_16[i], 0.05, 0.95);
219 | }
220 | }
221 |
222 | if (CONFIG.MIRROR_ENABLED == false) { // Mirroring logic
223 | unmirror();
224 | }
225 |
226 | show_leds(); // This sends final RGB data to the LEDS (led_utilities.h)
227 | LED_FPS = FastLED.getFPS();
228 | }
229 | vTaskDelay(1);
230 | }
231 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/audio_transfer.h:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #define DATA_SAMPLE_RATE 24400
4 | #define DATA_SAMPLES_PER_CHUNK 128
5 | #define DATA_HISTORY_LENGTH (SAMPLE_HISTORY_LENGTH/2)
6 | #define BYTE_LENGTH 128
7 | #define BIT_LENGTH (BYTE_LENGTH*8)
8 | #define WATCHDOG_TIMEOUT_US 1000000
9 |
10 | uint8_t tone_freq_range = 3;
11 |
12 | float readout_brightness = 0.25;
13 |
14 | short sample_window_data[DATA_HISTORY_LENGTH] = { 0 };
15 |
16 | uint8_t bit_data[BIT_LENGTH] = { 0 };
17 | uint16_t total_bits = 0;
18 |
19 | char character_data[BYTE_LENGTH] = { 0 };
20 |
21 | enum step_names {
22 | WAITING,
23 | PULSE_MEASUREMENT,
24 | TONAL_MEASUREMENT,
25 | EMPTY_TONE_MEASUREMENT,
26 | DATA_TRANSMISSION,
27 | COMPLETE
28 | };
29 |
30 | freq data_frequencies[9];
31 | const uint16_t data_frequencies_hz[9] = {
32 | 697, 770, 852, 941,
33 | 1209, 1336, 1477, 1633,
34 |
35 | 440, // "EMPTY" frequency
36 | };
37 |
38 | uint32_t data_magnitudes[9] = { 0 };
39 | float magnitude_multipliers[9] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
40 | float magnitude_multipliers_temp[9] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
41 | uint16_t top_frequencies[9] = { 0 };
42 |
43 | float magnitude_base_level = 100000;
44 |
45 | bool magic_tone_present = false;
46 | uint32_t measured_pulse_duration = 0;
47 | uint32_t measured_pulse_duration_sum = 0;
48 | uint8_t measured_pulse_count = 0;
49 |
50 | bool tone_measurement_started = false;
51 | uint32_t tone_measurement_started_time = -1;
52 | uint8_t measured_tone_count = 0;
53 |
54 | bool rx_begun = false;
55 |
56 | uint32_t pulse_measurement_start_time = 0;
57 | bool got_pulse = false;
58 | uint32_t recent_pulse_time = 0;
59 |
60 | uint8_t current_step = WAITING;
61 |
62 | uint32_t last_watchdog_time = 0;
63 |
64 | uint8_t recv_checksum = 0;
65 | uint8_t calc_checksum = 0;
66 | bool checksum_passed = false;
67 |
68 | uint8_t current_nibble = 255;
69 | uint32_t complete_time = 0;
70 |
71 | float led_expansion = 0.0;
72 |
73 | uint8_t convert_bit_data_to_string() {
74 | uint16_t bit_index = 0;
75 | uint16_t byte_index = 0;
76 | uint8_t checksum = 0;
77 | for (uint16_t i = 0; i < total_bits; i++) {
78 | if (i <= total_bits - 8) {
79 | bitWrite(character_data[byte_index], 7 - bit_index, bit_data[i]);
80 | }
81 | else {
82 | bitWrite(checksum, 7 - bit_index, bit_data[i]);
83 | }
84 |
85 | bit_index++;
86 | if (bit_index >= 8) {
87 | bit_index = 0;
88 | byte_index++;
89 | }
90 | }
91 |
92 | return checksum;
93 | }
94 |
95 | void reset_vars() {
96 | for (uint16_t i = 0; i < BIT_LENGTH; i++) {
97 | bit_data[i] = 0;
98 | }
99 | for (uint16_t i = 0; i < BYTE_LENGTH; i++) {
100 | character_data[i] = 0;
101 | }
102 | total_bits = 0;
103 |
104 | magic_tone_present = false;
105 | pulse_measurement_start_time = 0;
106 | measured_pulse_duration = 0;
107 | measured_pulse_duration_sum = 0;
108 | measured_pulse_count = 0;
109 |
110 | tone_measurement_started = false;
111 | tone_measurement_started_time = 0;
112 | measured_tone_count = 0;
113 |
114 | current_nibble = 255;
115 | checksum_passed = false;
116 | complete_time = 0;
117 |
118 | got_pulse = false;
119 | for (uint8_t i = 0; i < 9; i++) {
120 | data_magnitudes[i] = 0;
121 | magnitude_multipliers[i] = 1.0;
122 | magnitude_multipliers_temp[i] = 1.0;
123 | top_frequencies[i] = 0;
124 | }
125 |
126 | last_watchdog_time = 0;
127 |
128 | led_expansion = 0.0;
129 | rx_begun = false;
130 |
131 | current_step = WAITING;
132 | }
133 |
134 | void watchdog_notify(uint32_t t_now_us) {
135 | last_watchdog_time = t_now_us;
136 | }
137 |
138 | void watch_timeout(uint32_t t_now_us) {
139 | if (t_now_us - last_watchdog_time > WATCHDOG_TIMEOUT_US) {
140 | USBSerial.println("!-- TIMEOUT!");
141 |
142 | current_step = COMPLETE;
143 | checksum_passed = false;
144 | complete_time = t_now_us;
145 | }
146 | }
147 |
148 | void init_i2s_for_data() {
149 | const i2s_config_t i2s_config = { // This version is different from i2s_audio.h, with values that best suit this use-case
150 | .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
151 | .sample_rate = DATA_SAMPLE_RATE,
152 | .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
153 | .channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT,
154 | .communication_format = (i2s_comm_format_t) (I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
155 | .dma_buf_count = 1024 / (DATA_SAMPLES_PER_CHUNK * 2),
156 | .dma_buf_len = (DATA_SAMPLES_PER_CHUNK * 2)
157 | };
158 |
159 | const i2s_pin_config_t pin_config = { // These too
160 | .bck_io_num = I2S_BCLK_PIN,
161 | .ws_io_num = I2S_LRCLK_PIN,
162 | .data_out_num = -1, // not used (only for outputs)
163 | .data_in_num = I2S_DIN_PIN
164 | };
165 |
166 | // Init I2S Driver
167 | esp_err_t result = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
168 | USBSerial.print("INIT I2S: ");
169 | USBSerial.println(result == ESP_OK ? PASS : FAIL);
170 |
171 | if (result != ESP_OK) {
172 | pinMode(8, OUTPUT);
173 | while (true) {
174 | USBSerial.println("INIT FAIL");
175 | digitalWrite(8, HIGH);
176 | delay(100);
177 | digitalWrite(8, LOW);
178 | delay(100);
179 | }
180 | }
181 |
182 | // ESP32-S2 changes to help SPH0645 mic
183 | REG_SET_BIT(I2S_TIMING_REG(I2S_PORT), BIT(9));
184 | REG_SET_BIT(I2S_CONF_REG(I2S_PORT), I2S_RX_MSB_SHIFT);
185 |
186 | // Set I2S pins
187 | result = i2s_set_pin(I2S_PORT, &pin_config);
188 | USBSerial.print("I2S SET PINS: ");
189 | USBSerial.println(result == ESP_OK ? PASS : FAIL);
190 | }
191 |
192 | void init_data_frequencies() {
193 | for (uint8_t i = 0; i < 9; i++) {
194 | data_frequencies[i].target_freq = data_frequencies_hz[i];
195 | data_frequencies[i].block_size = 300;
196 | data_frequencies[i].block_size_recip = 1.0 / float(data_frequencies[i].block_size);
197 |
198 | float w = 2.0 * PI * ((float)data_frequencies[i].target_freq / DATA_SAMPLE_RATE);
199 | float coeff = 2.0 * cos(w);
200 | data_frequencies[i].coeff_q14 = (1 << 14) * coeff;
201 | }
202 | }
203 |
204 | void acquire_data_chunk() {
205 | size_t bytes_read = 0;
206 | i2s_read(I2S_PORT, i2s_samples_raw, DATA_SAMPLES_PER_CHUNK * sizeof(int32_t), &bytes_read, portMAX_DELAY);
207 |
208 | // Scale I2S samples and store into history
209 | for (uint16_t i = 0; i < DATA_SAMPLES_PER_CHUNK; i++) {
210 | int32_t sample = (i2s_samples_raw[i] * 0.000512) + 56000 - 5120;
211 |
212 | sample = sample >> 2; // Helps prevent overflow in fixed-point math coming up
213 |
214 | if (sample > 32767) { // clipping
215 | sample = 32767;
216 | } else if (sample < -32767) {
217 | sample = -32767;
218 | }
219 |
220 | waveform[i] = sample - CONFIG.DC_OFFSET;
221 | }
222 |
223 | for (int i = 0; i < DATA_HISTORY_LENGTH - DATA_SAMPLES_PER_CHUNK; i++) {
224 | sample_window_data[i] = sample_window_data[i + DATA_SAMPLES_PER_CHUNK];
225 | }
226 | for (int i = DATA_HISTORY_LENGTH - DATA_SAMPLES_PER_CHUNK; i < DATA_HISTORY_LENGTH; i++) {
227 | sample_window_data[i] = waveform[i - (DATA_HISTORY_LENGTH - DATA_SAMPLES_PER_CHUNK)];
228 | }
229 | }
230 |
231 | void fast_gdft() {
232 | // Run GDFT (Goertzel - based Discrete Fourier Transform) with 9 frequencies
233 | for (uint16_t i = 0; i < 9; i++) {
234 | int32_t q0, q1, q2;
235 | int64_t mult;
236 |
237 | q1 = 0;
238 | q2 = 0;
239 |
240 | for (uint16_t n = 0; n < data_frequencies[i].block_size; n++) { // Run Goertzel for "block_size" iterations
241 | int32_t sample = sample_window_data[DATA_HISTORY_LENGTH - 1 - n];
242 | mult = (int64_t)data_frequencies[i].coeff_q14 * (int64_t)q1;
243 | q0 = (sample >> 6) + (mult >> 14) - q2;
244 | q2 = q1;
245 | q1 = q0;
246 | }
247 |
248 | mult = (int64_t)data_frequencies[i].coeff_q14 * (int64_t)q1;
249 | data_magnitudes[i] = q2 * q2 + q1 * q1 - ((int32_t)(mult >> 14)) * q2; // Calculate raw magnitudes
250 |
251 | // Normalize output
252 | data_magnitudes[i] *= float(data_frequencies[i].block_size_recip);
253 |
254 | if (data_magnitudes[i] < 0.0) { // Prevent negative values
255 | data_magnitudes[i] = 0.0;
256 | }
257 |
258 | data_magnitudes[i] *= magnitude_multipliers[i];
259 | }
260 | }
261 |
262 | unsigned char checksum(char *data, uint8_t len) {
263 | unsigned char result = 0;
264 | for (uint8_t i = 0; i < len; i++) {
265 | result ^= data[i];
266 | }
267 | return result;
268 | }
269 |
270 | bool top_frequency(uint16_t freq, uint8_t range) {
271 | bool found = false;
272 | for (uint8_t i = 0; i < range; i++) {
273 | if (top_frequencies[i] == freq) {
274 | found = true;
275 | }
276 | }
277 |
278 | return found;
279 | }
280 |
281 | void sort_top_frequencies() {
282 | bool freqs_found[9] = { false };
283 | uint8_t current_index = 0;
284 |
285 | for (uint8_t i = 0; i < 9; i++) {
286 | top_frequencies[i] = 0;
287 | }
288 |
289 | while (current_index < 9) {
290 | uint32_t max_val = 0;
291 | uint8_t max_index = 255;
292 | for (uint8_t i = 0; i < 9; i++) {
293 | if (freqs_found[i] == false) {
294 | if ((data_magnitudes[i]) > max_val || (data_magnitudes[i]) == 0) {
295 | max_val = (data_magnitudes[i]);
296 | max_index = i;
297 | }
298 | }
299 | }
300 |
301 | if (max_index != 255) {
302 | top_frequencies[current_index] = data_frequencies_hz[max_index];
303 | freqs_found[max_index] = true;
304 | current_index++;
305 | }
306 | }
307 | }
308 |
309 | void append_two_bits(uint8_t bit_0, uint8_t bit_1) {
310 | bit_data[total_bits + 0] = bit_0;
311 | bit_data[total_bits + 1] = bit_1;
312 |
313 | total_bits += 2;
314 | }
315 |
316 | void calculate_tone_multiplier(uint8_t index) {
317 | magnitude_multipliers_temp[index] = magnitude_base_level / float(data_magnitudes[index]);
318 | }
319 |
320 | void parse_data() {
321 | static uint32_t iter = 0;
322 | uint32_t t_now_us = micros();
323 | iter++;
324 |
325 | /*
326 | for (uint8_t i = 0; i < 4; i++) {
327 | USBSerial.print(top_frequencies[i]);
328 | USBSerial.print("\t");
329 | }
330 | USBSerial.println();
331 | */
332 |
333 | if (current_step == WAITING) {
334 | if (top_frequency(697, 4) && top_frequency(1209, 4) && top_frequency(941, 4) && top_frequency(1633, 4)) {
335 | if (magic_tone_present == false) {
336 | USBSerial.println("MAGIC TONE!");
337 | magic_tone_present = true;
338 | }
339 | }
340 | else if (top_frequency(440, 2)) { // Hearing "empty" air
341 | if (magic_tone_present == true) {
342 | magic_tone_present = false;
343 |
344 | //USBSerial.println("MEASURING PULSE LENGTH...");
345 | current_step = PULSE_MEASUREMENT;
346 | led_expansion = 0.0;
347 | watchdog_notify(t_now_us);
348 | }
349 | }
350 | }
351 |
352 | else if (current_step == PULSE_MEASUREMENT) {
353 | if (top_frequency(697, 4) && top_frequency(1209, 4) && top_frequency(941, 4) && top_frequency(1633, 4)) {
354 | if (magic_tone_present == false) {
355 | magic_tone_present = true;
356 | pulse_measurement_start_time = t_now_us;
357 | }
358 | }
359 | else {
360 | if (magic_tone_present == true) {
361 | if (top_frequency(440, 2)) { // Hearing "empty" air
362 | magic_tone_present = false;
363 |
364 | measured_pulse_duration = t_now_us - pulse_measurement_start_time;
365 |
366 | measured_pulse_duration_sum += measured_pulse_duration;
367 | measured_pulse_count++;
368 | watchdog_notify(t_now_us);
369 |
370 | if (measured_pulse_count == 4) {
371 | measured_pulse_duration = measured_pulse_duration_sum / float(measured_pulse_count);
372 | measured_pulse_duration /= 4.0;
373 | measured_pulse_count = 0;
374 | measured_pulse_duration_sum = 0;
375 |
376 | //USBSerial.print("PULSE LENGTH: ");
377 | //USBSerial.print(measured_pulse_duration);
378 | //USBSerial.println("us");
379 |
380 | //USBSerial.println("MEASURING TONAL RESPONSE...");
381 | current_step = TONAL_MEASUREMENT;
382 | watchdog_notify(t_now_us);
383 | }
384 | }
385 | }
386 | }
387 |
388 | watch_timeout(t_now_us);
389 | }
390 |
391 | else if (current_step == TONAL_MEASUREMENT) {
392 | if (top_frequency(440, 2)) { // Hearing "empty" air
393 | if (got_pulse == true) {
394 | got_pulse = false;
395 | }
396 | if (tone_measurement_started == true) {
397 | tone_measurement_started = false;
398 | }
399 |
400 | bool solved = true;
401 | for (uint8_t i = 0; i < 8; i++) {
402 | if (magnitude_multipliers_temp[i] == 1.0000) {
403 | solved = false;
404 | }
405 | }
406 |
407 | if (solved == true) {
408 | tone_measurement_started_time = -1; // max
409 |
410 | //USBSerial.println("MEASURING EMPTY TONE...");
411 | current_step = EMPTY_TONE_MEASUREMENT;
412 | watchdog_notify(t_now_us);
413 | delay(10);
414 | }
415 | }
416 | else { // hearing tone
417 | if (tone_measurement_started == false) {
418 | tone_measurement_started = true;
419 | tone_measurement_started_time = t_now_us;
420 | }
421 | if (got_pulse == false) {
422 | bool tones_valid = false;
423 | bool time_to_measure = false;
424 | if (t_now_us >= tone_measurement_started_time + (measured_pulse_duration)) {
425 | time_to_measure = true;
426 | }
427 |
428 | if (time_to_measure == true) {
429 | if (top_frequency(697, 3) && top_frequency(1209, 3)) {
430 | tones_valid = true;
431 | //USBSerial.println("GOT PAIR 1");
432 | calculate_tone_multiplier(0);
433 | calculate_tone_multiplier(4);
434 | measured_tone_count++;
435 | watchdog_notify(t_now_us);
436 | tone_measurement_started_time = -1; // max
437 | }
438 | else if (top_frequency(770, 3) && top_frequency(1336, 3)) {
439 | tones_valid = true;
440 | //USBSerial.println("GOT PAIR 2");
441 | calculate_tone_multiplier(1);
442 | calculate_tone_multiplier(5);
443 | measured_tone_count++;
444 | watchdog_notify(t_now_us);
445 | tone_measurement_started_time = -1; // max
446 | }
447 |
448 | else if (top_frequency(852, 3) && top_frequency(1477, 3)) {
449 | tones_valid = true;
450 | //USBSerial.println("GOT PAIR 3");
451 | calculate_tone_multiplier(2);
452 | calculate_tone_multiplier(6);
453 | measured_tone_count++;
454 | watchdog_notify(t_now_us);
455 | tone_measurement_started_time = -1; // max
456 | }
457 |
458 | else if (top_frequency(941, 3) && top_frequency(1633, 3)) {
459 | tones_valid = true;
460 | //USBSerial.println("GOT PAIR 4");
461 | calculate_tone_multiplier(3);
462 | calculate_tone_multiplier(7);
463 | measured_tone_count++;
464 | watchdog_notify(t_now_us);
465 | tone_measurement_started_time = -1; // max
466 | }
467 |
468 | if (tones_valid) {
469 | // print tone count
470 | }
471 | }
472 |
473 | got_pulse = tones_valid;
474 | }
475 | }
476 |
477 | watch_timeout(t_now_us);
478 | }
479 |
480 | else if (current_step == EMPTY_TONE_MEASUREMENT) {
481 | if (top_frequency(440, 2)) { // Hearing "empty" air
482 | // Get "empty tone" measurement
483 | magnitude_multipliers_temp[8] = magnitude_base_level / float(data_magnitudes[8]);
484 | for (uint8_t i = 0; i < 9; i++) {
485 | magnitude_multipliers[i] = magnitude_multipliers_temp[i];
486 | }
487 |
488 | USBSerial.print("BEGIN RX...");
489 | current_step = DATA_TRANSMISSION;
490 | rx_begun = false;
491 | watchdog_notify(t_now_us);
492 | }
493 |
494 | watch_timeout(t_now_us);
495 | }
496 |
497 | else if (current_step == DATA_TRANSMISSION) {
498 | if (top_frequency(440, 2)) { // Hearing "empty" air
499 | if (got_pulse == true) {
500 | got_pulse = false;
501 | }
502 |
503 | if (total_bits >= 8) {
504 | if (t_now_us - recent_pulse_time >= (measured_pulse_duration * 4)) { // if >= pulse_duration*4 since last pulse
505 | USBSerial.println("DONE!");
506 | recv_checksum = convert_bit_data_to_string();
507 | calc_checksum = checksum(character_data, strlen(character_data));
508 |
509 | if (recv_checksum == calc_checksum) {
510 | checksum_passed = true;
511 | }
512 |
513 | current_step = COMPLETE;
514 | complete_time = t_now_us;
515 | }
516 | }
517 | }
518 | else { // Hearing data
519 | if (rx_begun == false) {
520 | rx_begun = true;
521 | led_expansion = 0.0;
522 | }
523 |
524 | if (got_pulse == false) {
525 | bool tones_valid = false;
526 | if (top_frequency(697, tone_freq_range) && top_frequency(1209, tone_freq_range)) {
527 | tones_valid = true;
528 | current_nibble = 0;
529 | append_two_bits(0, 0);
530 | }
531 | else if (top_frequency(770, tone_freq_range) && top_frequency(1336, tone_freq_range)) {
532 | tones_valid = true;
533 | current_nibble = 1;
534 | append_two_bits(0, 1);
535 | }
536 | else if (top_frequency(852, tone_freq_range) && top_frequency(1477, tone_freq_range)) {
537 | tones_valid = true;
538 | current_nibble = 2;
539 | append_two_bits(1, 0);
540 | }
541 | else if (top_frequency(941, tone_freq_range) && top_frequency(1633, tone_freq_range)) {
542 | tones_valid = true;
543 | current_nibble = 3;
544 | append_two_bits(1, 1);
545 | }
546 |
547 | if (tones_valid) {
548 | recent_pulse_time = t_now_us;
549 | }
550 |
551 | got_pulse = tones_valid;
552 | }
553 | }
554 | }
555 |
556 | else if (current_step == COMPLETE) {
557 | if (t_now_us - complete_time >= 500000) {
558 | reset_vars();
559 | current_step = WAITING;
560 | }
561 | else {
562 | USBSerial.print("MESSAGE: |");
563 | USBSerial.print(character_data);
564 | USBSerial.println("|");
565 | }
566 | }
567 | }
568 |
569 | void pass_animation() {
570 | uint32_t t_start = millis();
571 | float width = 0.0;
572 | float iter = 0.0;
573 | float wiggle_strength = 1.0;
574 | while (millis() < t_start + 1000) {
575 | iter += 0.15;
576 |
577 | if(width < 1.0){
578 | float delta = 1.0-width;
579 | width += delta*0.05;
580 | }
581 |
582 | clear_all_led_buffers();
583 | draw_line(leds, CRGB(0,255*width*width,0), 64, 64+(16*width)+(12*(sin(iter)+1.0)*(1.0-width)));
584 | mirror_image_downwards();
585 | show_leds();
586 | }
587 |
588 | while (width > 0.001) {
589 | width *= 0.95;
590 | clear_all_led_buffers();
591 | draw_line(leds, CRGB(0,255*width*width,0), 64, 64+(16*width)+(12*(sin(iter)+1.0)*(1.0-width)));
592 | mirror_image_downwards();
593 | show_leds();
594 | }
595 | }
596 |
597 | void fail_animation() {
598 | uint32_t t_start = millis();
599 | float width = 0.0;
600 | float midpoint = (NATIVE_RESOLUTION/2.0)-0.5;
601 |
602 | while (fabs(width - 1.0) > 0.01){
603 | if(width < 1.0){
604 | float delta = 1.0-width;
605 | width += delta*0.2;
606 | }
607 |
608 | float line_size = 16*width;
609 |
610 | clear_all_led_buffers();
611 | draw_line(leds, CRGB(255*width*width,0,0), midpoint+line_size, midpoint-line_size);
612 | show_leds();
613 | }
614 | width = 1.0;
615 |
616 | float iter = 0.0;
617 | while(iter < 20.0){
618 | iter += 0.2;
619 | float line_size = 16;
620 |
621 | float line_offset = sin(iter)*5.0;
622 |
623 | clear_all_led_buffers();
624 | draw_line(leds, CRGB(255*width*width,0,0), (midpoint+line_size) + line_offset, (midpoint-line_size) + line_offset);
625 | show_leds();
626 | }
627 |
628 | while (width > 0.005) {
629 | width *= 0.95;
630 |
631 | float line_size = 16*width;
632 |
633 | clear_all_led_buffers();
634 | draw_line(leds, CRGB(255*width*width,0,0), midpoint+line_size, midpoint-line_size);
635 | mirror_image_downwards();
636 | show_leds();
637 | }
638 | clear_all_led_buffers();
639 | show_leds();
640 | }
641 |
642 | void run_leds() {
643 | fadeToBlackBy(leds, NATIVE_RESOLUTION, 32);
644 |
645 | if (led_expansion < 1.0) {
646 | float delta = 1.0 - led_expansion;
647 |
648 | led_expansion += delta * 0.025;
649 | }
650 |
651 | if (current_step == WAITING) {
652 | static float iter = 0;
653 | iter += 0.03;
654 | float led_pos = sin(iter);
655 | led_pos += 1.0;
656 | led_pos /= 2.0;
657 | led_pos *= ((NATIVE_RESOLUTION / 2) - 1);
658 |
659 | leds[64 + uint16_t(led_pos)] = CRGB(0, 92, 255);
660 | }
661 |
662 | /*
663 | WAITING,
664 | PULSE_MEASUREMENT,
665 | TONAL_MEASUREMENT,
666 | EMPTY_TONE_MEASUREMENT,
667 | DATA_TRANSMISSION,
668 | COMPLETE
669 | */
670 |
671 | else if (current_step == PULSE_MEASUREMENT) {
672 | if (magic_tone_present == true) {
673 | for (uint8_t i = 0; i < 4; i++) {
674 | leds[64 + 6 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness, 0);
675 | leds[64 + 7 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness, 0);
676 | leds[64 + 8 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness, 0);
677 | leds[64 + 9 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness, 0);
678 | }
679 | }
680 | else {
681 | for (uint8_t i = 0; i < 4; i++) {
682 | leds[64 + 6 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness*0.25, 0);
683 | leds[64 + 7 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness*0.25, 0);
684 | leds[64 + 8 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness*0.25, 0);
685 | leds[64 + 9 + uint16_t(i * 16 * led_expansion)] = CRGB(0, 255*readout_brightness*0.25, 0);
686 | }
687 | }
688 | }
689 |
690 | else if (current_step == TONAL_MEASUREMENT) {
691 | for (uint8_t i = 0; i < measured_tone_count; i++) {
692 | leds[64 + 6 + uint16_t(i * 16 * led_expansion)] = CRGB(255*readout_brightness, 32*readout_brightness, 0);
693 | leds[64 + 7 + uint16_t(i * 16 * led_expansion)] = CRGB(255*readout_brightness, 32*readout_brightness, 0);
694 | leds[64 + 8 + uint16_t(i * 16 * led_expansion)] = CRGB(255*readout_brightness, 32*readout_brightness, 0);
695 | leds[64 + 9 + uint16_t(i * 16 * led_expansion)] = CRGB(255*readout_brightness, 32*readout_brightness, 0);
696 | }
697 | }
698 |
699 | else if (current_step == DATA_TRANSMISSION) {
700 | for(uint8_t i = 0; i < 4; i++){
701 | leds[64 + 6 + uint16_t(16 * i * led_expansion)] = CRGB(0, 92*readout_brightness*0.25, 255*readout_brightness*0.25);
702 | leds[64 + 7 + uint16_t(16 * i * led_expansion)] = CRGB(0, 92*readout_brightness*0.25, 255*readout_brightness*0.25);
703 | leds[64 + 8 + uint16_t(16 * i * led_expansion)] = CRGB(0, 92*readout_brightness*0.25, 255*readout_brightness*0.25);
704 | leds[64 + 9 + uint16_t(16 * i * led_expansion)] = CRGB(0, 92*readout_brightness*0.25, 255*readout_brightness*0.25);
705 | }
706 |
707 | leds[64 + 6 + uint16_t(16 * current_nibble * led_expansion)] = CRGB(0, 92*readout_brightness*2.0, 255*readout_brightness*2.0);
708 | leds[64 + 7 + uint16_t(16 * current_nibble * led_expansion)] = CRGB(0, 92*readout_brightness*2.0, 255*readout_brightness*2.0);
709 | leds[64 + 8 + uint16_t(16 * current_nibble * led_expansion)] = CRGB(0, 92*readout_brightness*2.0, 255*readout_brightness*2.0);
710 | leds[64 + 9 + uint16_t(16 * current_nibble * led_expansion)] = CRGB(0, 92*readout_brightness*2.0, 255*readout_brightness*2.0);
711 | current_nibble = 255;
712 | }
713 |
714 | else if (current_step == COMPLETE) {
715 | if (checksum_passed == true) {
716 | pass_animation();
717 | }
718 | else {
719 | fail_animation();
720 | }
721 | }
722 |
723 | mirror_image_downwards();
724 | show_leds();
725 | }
726 |
727 | void enable_audio_transfer_mode() {
728 | init_i2s_for_data();
729 | init_data_frequencies();
730 |
731 | while (true) {
732 | acquire_data_chunk();
733 | fast_gdft();
734 | sort_top_frequencies();
735 | parse_data();
736 | run_leds();
737 |
738 | yield();
739 | }
740 | }
741 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/bridge_fs.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge FILESYSTEM ACCESS
3 | ----------------------------------------*/
4 |
5 | extern void reboot(); // system.h
6 |
7 | void update_config_filename(uint32_t input) {
8 | snprintf(config_filename, 24, "/CONFIG_%05lu.BIN", input);
9 | }
10 |
11 | // Restore all defaults defined in globals.h by removing saved data and rebooting
12 | void factory_reset() {
13 | lock_leds();
14 | USBSerial.print("Deleting ");
15 | USBSerial.print(config_filename);
16 | USBSerial.print(": ");
17 |
18 | if (LittleFS.remove(config_filename)) {
19 | USBSerial.println("file deleted");
20 | } else {
21 | USBSerial.println("delete failed");
22 | }
23 |
24 | USBSerial.print("Deleting noise_cal.bin: ");
25 | if (LittleFS.remove("/noise_cal.bin")) {
26 | USBSerial.println("file deleted");
27 | } else {
28 | USBSerial.println("delete failed");
29 | }
30 |
31 | reboot();
32 | }
33 |
34 | // Restore only configuration defaults
35 | void restore_defaults() {
36 | lock_leds();
37 | USBSerial.print("Deleting ");
38 | USBSerial.print(config_filename);
39 | USBSerial.print(": ");
40 |
41 | if (LittleFS.remove(config_filename)) {
42 | USBSerial.println("file deleted");
43 | } else {
44 | USBSerial.println("delete failed");
45 | }
46 |
47 | reboot();
48 | }
49 |
50 | // Save configuration to LittleFS
51 | void save_config() {
52 | lock_leds();
53 | if (debug_mode) {
54 | USBSerial.print("LITTLEFS: ");
55 | }
56 | File file = LittleFS.open(config_filename, FILE_WRITE);
57 | if (!file) {
58 | if (debug_mode) {
59 | USBSerial.print("Failed to open ");
60 | USBSerial.print(config_filename);
61 | USBSerial.println(" for writing!");
62 | }
63 | return;
64 | } else {
65 | file.seek(0);
66 | uint8_t config_buffer[512];
67 | memcpy(config_buffer, &CONFIG, sizeof(CONFIG));
68 |
69 | for (uint16_t i = 0; i < 512; i++) {
70 | file.write(config_buffer[i]);
71 | }
72 |
73 | if (debug_mode) {
74 | USBSerial.print("WROTE ");
75 | USBSerial.print(config_filename);
76 | USBSerial.println(" SUCCESSFULLY");
77 | }
78 | }
79 | file.close();
80 | unlock_leds();
81 | }
82 |
83 | // Save configuration to LittleFS 10 seconds from now
84 | void save_config_delayed() {
85 | if(debug_mode == true){
86 | USBSerial.println("CONFIG SAVE QUEUED");
87 | }
88 | next_save_time = millis()+5000;
89 | settings_updated = true;
90 | }
91 |
92 | // Load configuration from LittleFS
93 | void load_config() {
94 | lock_leds();
95 | if (debug_mode) {
96 | USBSerial.print("LITTLEFS: ");
97 | }
98 |
99 | bool queue_factory_reset = false;
100 | File file = LittleFS.open(config_filename, FILE_READ);
101 | if (!file) {
102 | if (debug_mode) {
103 | USBSerial.print("Failed to open ");
104 | USBSerial.print(config_filename);
105 | USBSerial.println(" for reading!");
106 | }
107 | return;
108 | } else {
109 | file.seek(0);
110 | uint8_t config_buffer[512];
111 | for (uint16_t i = 0; i < sizeof(CONFIG); i++) {
112 | config_buffer[i] = file.read();
113 | }
114 |
115 | memcpy(&CONFIG, config_buffer, sizeof(CONFIG));
116 |
117 | if (debug_mode) {
118 | USBSerial.println("READ CONFIG SUCCESSFULLY");
119 | }
120 | }
121 | file.close();
122 |
123 | if (queue_factory_reset == true) {
124 | factory_reset();
125 | }
126 | unlock_leds();
127 | }
128 |
129 | // Save noise calibration to LittleFS
130 | void save_ambient_noise_calibration() {
131 | lock_leds();
132 | if (debug_mode) {
133 | USBSerial.print("SAVING AMBIENT_NOISE PROFILE... ");
134 | }
135 | File file = LittleFS.open("/noise_cal.bin", FILE_WRITE);
136 | if (!file) {
137 | if (debug_mode) {
138 | USBSerial.println("Failed to open file for writing!");
139 | }
140 | return;
141 | }
142 |
143 | bytes_32 temp;
144 |
145 | file.seek(0);
146 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
147 | float in_val = float(noise_samples[i]);
148 |
149 | temp.long_val_float = in_val;
150 |
151 | file.write(temp.bytes[0]);
152 | file.write(temp.bytes[1]);
153 | file.write(temp.bytes[2]);
154 | file.write(temp.bytes[3]);
155 | }
156 |
157 | file.close();
158 | if (debug_mode) {
159 | USBSerial.println("SAVE COMPLETE");
160 | }
161 |
162 | unlock_leds();
163 | }
164 |
165 | // Load noise calibration from LittleFS
166 | void load_ambient_noise_calibration() {
167 | lock_leds();
168 | if (debug_mode) {
169 | USBSerial.print("LOADING AMBIENT_NOISE PROFILE... ");
170 | }
171 | File file = LittleFS.open("/noise_cal.bin", FILE_READ);
172 | if (!file) {
173 | if (debug_mode) {
174 | USBSerial.println("Failed to open file for reading!");
175 | }
176 | return;
177 | }
178 |
179 | bytes_32 temp;
180 |
181 | file.seek(0);
182 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
183 | temp.bytes[0] = file.read();
184 | temp.bytes[1] = file.read();
185 | temp.bytes[2] = file.read();
186 | temp.bytes[3] = file.read();
187 |
188 | noise_samples[i] = SQ15x16(temp.long_val_float);
189 | }
190 |
191 | file.close();
192 | if (debug_mode) {
193 | USBSerial.println("LOAD COMPLETE");
194 | }
195 |
196 | unlock_leds();
197 | }
198 |
199 | // Initialize LittleFS
200 | void init_fs() {
201 | lock_leds();
202 | USBSerial.print("INIT FILESYSTEM: ");
203 | USBSerial.println(LittleFS.begin(true) == true ? PASS : FAIL);
204 |
205 | update_config_filename(FIRMWARE_VERSION);
206 |
207 | load_ambient_noise_calibration();
208 | load_config();
209 | unlock_leds();
210 | }
211 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/buttons.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge BUTTON FUNCTIONS
3 | ----------------------------------------*/
4 |
5 | // Every frame, we check both buttons for two types of input:
6 | //
7 | // NOISE BUTTON:
8 | // SHORT PRESS: BEGIN CALIBRATION
9 | // LONG PRESS: CLEAR CALIBRATION
10 | //
11 | // MODE BUTTON:
12 | // SHORT PRESS: INCREMENT LIGHTSHOW MODE
13 | // LONG PRESS: TOGGLE MIRRORING
14 | //
15 | // If buttons are touched on a unit that isn't set to MAIN,
16 | // it will flash all units in the network (p2p.h) to identify
17 | // which unit's buttons to touch instead to affect changes.
18 |
19 | void check_buttons(uint32_t t_now) {
20 | if (digitalRead(noise_button.pin) == LOW) { // currently pressed
21 | if (noise_button.pressed == false) { // if just started
22 | noise_button.pressed = true;
23 | noise_button.last_down = t_now; // mark button-down time
24 | }
25 |
26 | if (t_now - noise_button.last_down > 250 && noise_button.last_up < noise_button.last_down) { // Still held, and for more than 250ms (long press)
27 | if (CONFIG.IS_MAIN_UNIT || main_override) { // If main, clear noise cal
28 | clear_noise_cal();
29 | } else { // if not, complain
30 | identify_main_unit();
31 | }
32 |
33 | noise_button.last_up = t_now; // count this event as a release time to prevent this function from repeating
34 | }
35 | } else if (digitalRead(noise_button.pin) == HIGH) { // button is not currently pressed
36 | if (noise_button.pressed == true) { // if it was just barely released
37 | noise_button.pressed = false;
38 | noise_button.last_up = t_now;
39 |
40 | uint32_t press_duration = noise_button.last_up - noise_button.last_down; // Get press duration
41 |
42 | if (press_duration <= 250) { // if it was a short press
43 | if (CONFIG.IS_MAIN_UNIT || main_override) { // if main unit, start noise cal
44 | noise_transition_queued = true; // See run_transition_fade() in led_utilities.h
45 | }
46 | else { // Otherwise, complain
47 | identify_main_unit();
48 | }
49 | }
50 | }
51 | }
52 |
53 | // Same as above, different button!
54 | if (digitalRead(mode_button.pin) == LOW) {
55 | if (mode_button.pressed == false) {
56 | mode_button.pressed = true;
57 | mode_button.last_down = t_now;
58 | }
59 |
60 | if (t_now - mode_button.last_down > 250 && mode_button.last_up < mode_button.last_down) {
61 | if (CONFIG.IS_MAIN_UNIT || main_override) {
62 | CONFIG.MIRROR_ENABLED = !CONFIG.MIRROR_ENABLED;
63 | save_config_delayed();
64 | } else {
65 | identify_main_unit();
66 | }
67 | mode_button.last_up = t_now;
68 | }
69 | } else if (digitalRead(mode_button.pin) == HIGH) {
70 | if (mode_button.pressed == true) {
71 | mode_button.pressed = false;
72 | mode_button.last_up = t_now;
73 | bool skip_click = false;
74 |
75 | if (mode_transition_queued == true) {
76 | skip_click = true;
77 | mode_transition_queued = false;
78 | MASTER_BRIGHTNESS = 1.0;
79 | if(debug_mode){USBSerial.println("DOUBLE CLICK");}
80 | }
81 |
82 | uint32_t press_duration = mode_button.last_up - mode_button.last_down;
83 |
84 | if (press_duration <= 250 && skip_click == false) {
85 | if (mode_transition_queued == false) {
86 | if (CONFIG.IS_MAIN_UNIT || main_override) {
87 | mode_transition_queued = true; // See run_transition_fade() in led_utilities.h
88 | mode_destination = -1;
89 |
90 | save_config_delayed();
91 | } else {
92 | identify_main_unit();
93 | }
94 | }
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/constants.h:
--------------------------------------------------------------------------------
1 | // AUDIO #######################################################
2 |
3 | #define SERIAL_BAUD 230400
4 | #define DEFAULT_SAMPLE_RATE 12800
5 | #define SAMPLE_HISTORY_LENGTH 4096
6 |
7 | // Don't change this unless you're willing to do a lot of other work on the code :/
8 | #define NATIVE_RESOLUTION 128
9 | #define NUM_FREQS 64
10 | #define NUM_ZONES 2
11 |
12 | #define I2S_PORT I2S_NUM_0
13 |
14 | #define SPECTRAL_HISTORY_LENGTH 5
15 |
16 | #define MAX_DOTS 128
17 |
18 | enum reserved_dots {
19 | GRAPH_NEEDLE,
20 | GRAPH_DOT_1,
21 | GRAPH_DOT_2,
22 | GRAPH_DOT_3,
23 | GRAPH_DOT_4,
24 | GRAPH_DOT_5,
25 | RIPPLE_LEFT,
26 | RIPPLE_RIGHT,
27 |
28 | RESERVED_DOTS
29 | };
30 |
31 | enum knob_names {
32 | K_NONE,
33 | K_PHOTONS,
34 | K_CHROMA,
35 | K_MOOD
36 | };
37 |
38 | struct CRGB16 { // Unsigned Q8.8 Fixed-point color channels
39 | SQ15x16 r;
40 | SQ15x16 g;
41 | SQ15x16 b;
42 | };
43 |
44 | struct DOT {
45 | SQ15x16 position;
46 | SQ15x16 last_position;
47 | };
48 |
49 | struct KNOB {
50 | SQ15x16 value;
51 | SQ15x16 last_value;
52 | SQ15x16 change_rate;
53 | uint32_t last_change;
54 | };
55 |
56 | const float notes[] = {
57 | 55.00000, 58.27047, 61.73541, 65.40639, 69.29566, 73.41619, 77.78175, 82.40689, 87.30706, 92.49861, 97.99886, 103.8262,
58 | 110.0000, 116.5409, 123.4708, 130.8128, 138.5913, 146.8324, 155.5635, 164.8138, 174.6141, 184.9972, 195.9977, 207.6523,
59 | 220.0000, 233.0819, 246.9417, 261.6256, 277.1826, 293.6648, 311.1270, 329.6276, 349.2282, 369.9944, 391.9954, 415.3047,
60 | 440.0000, 466.1638, 493.8833, 523.2511, 554.3653, 587.3295, 622.2540, 659.2551, 698.4565, 739.9888, 783.9909, 830.6094,
61 | 880.0000, 932.3275, 987.7666, 1046.502, 1108.731, 1174.659, 1244.508, 1318.510, 1396.913, 1479.978, 1567.982, 1661.219,
62 | 1760.000, 1864.655, 1975.533, 2093.005, 2217.461, 2349.318, 2489.016, 2637.020, 2793.825, 2959.956, 3135.964, 3322.437,
63 | 3520.000, 3729.310, 3951.065, 4186.009, 4434.922, 4698.636, 4978.032, 5274.041, 5587.652, 5919.911, 6271.927, 6644.875,
64 | 7040.000, 7458.620, 7902.130, 8372.018, 8869.844, 9397.272, 9956.064, 10548.08, 11175.30, 11839.82, 12543.85, 13289.75
65 | };
66 |
67 | // GPIO PINS #######################################################
68 |
69 | #define PHOTONS_PIN 1
70 | #define CHROMA_PIN 2
71 | #define MOOD_PIN 3
72 |
73 | #define I2S_BCLK_PIN 33
74 | #define I2S_LRCLK_PIN 34
75 | #define I2S_DIN_PIN 35
76 |
77 | #define LED_DATA_PIN 36
78 | #define LED_CLOCK_PIN 37
79 |
80 | #define RNG_SEED_PIN 10
81 |
82 | #define NOISE_CAL_PIN 11
83 | #define MODE_PIN 45
84 |
85 | #define SWEET_SPOT_LEFT_PIN 7
86 | #define SWEET_SPOT_CENTER_PIN 8
87 | #define SWEET_SPOT_RIGHT_PIN 9
88 |
89 | // OTHER #######################################################
90 |
91 | const SQ15x16 dither_table[4] = {
92 | 0.25,
93 | 0.50,
94 | 0.75,
95 | 1.00
96 | /*
97 | 0.166666,
98 | 0.333333,
99 | 0.500000,
100 | 0.666666,
101 | 0.833333,
102 | 1.000000
103 | */
104 | };
105 |
106 | SQ15x16 note_colors[12] = {
107 | 0.0000,
108 | 0.0833,
109 | 0.1666,
110 | 0.2499,
111 | 0.3333,
112 | 0.4166,
113 | 0.4999,
114 | 0.5833,
115 | 0.6666,
116 | 0.7499,
117 | 0.8333,
118 | 0.9166
119 | };
120 |
121 | const SQ15x16 hue_lookup[64][3] = {
122 | { 1.0000, 0.0000, 0.0000 },
123 | { 0.9608, 0.0392, 0.0000 },
124 | { 0.9176, 0.0824, 0.0000 },
125 | { 0.8745, 0.1255, 0.0000 },
126 | { 0.8314, 0.1686, 0.0000 },
127 | { 0.7922, 0.2078, 0.0000 },
128 | { 0.7490, 0.2510, 0.0000 },
129 | { 0.7059, 0.2941, 0.0000 },
130 | { 0.6706, 0.3333, 0.0000 },
131 | { 0.6706, 0.3725, 0.0000 },
132 | { 0.6706, 0.4157, 0.0000 },
133 | { 0.6706, 0.4588, 0.0000 },
134 | { 0.6706, 0.5020, 0.0000 },
135 | { 0.6706, 0.5412, 0.0000 },
136 | { 0.6706, 0.5843, 0.0000 },
137 | { 0.6706, 0.6275, 0.0000 },
138 | { 0.6706, 0.6667, 0.0000 },
139 | { 0.5882, 0.7059, 0.0000 },
140 | { 0.5059, 0.7490, 0.0000 },
141 | { 0.4196, 0.7922, 0.0000 },
142 | { 0.3373, 0.8353, 0.0000 },
143 | { 0.2549, 0.8745, 0.0000 },
144 | { 0.1686, 0.9176, 0.0000 },
145 | { 0.0863, 0.9608, 0.0000 },
146 | { 0.0000, 1.0000, 0.0000 },
147 | { 0.0000, 0.9608, 0.0392 },
148 | { 0.0000, 0.9176, 0.0824 },
149 | { 0.0000, 0.8745, 0.1255 },
150 | { 0.0000, 0.8314, 0.1686 },
151 | { 0.0000, 0.7922, 0.2078 },
152 | { 0.0000, 0.7490, 0.2510 },
153 | { 0.0000, 0.7059, 0.2941 },
154 | { 0.0000, 0.6706, 0.3333 },
155 | { 0.0000, 0.5882, 0.4157 },
156 | { 0.0000, 0.5059, 0.4980 },
157 | { 0.0000, 0.4196, 0.5843 },
158 | { 0.0000, 0.3373, 0.6667 },
159 | { 0.0000, 0.2549, 0.7490 },
160 | { 0.0000, 0.1686, 0.8353 },
161 | { 0.0000, 0.0863, 0.9176 },
162 | { 0.0000, 0.0000, 1.0000 },
163 | { 0.0392, 0.0000, 0.9608 },
164 | { 0.0824, 0.0000, 0.9176 },
165 | { 0.1255, 0.0000, 0.8745 },
166 | { 0.1686, 0.0000, 0.8314 },
167 | { 0.2078, 0.0000, 0.7922 },
168 | { 0.2510, 0.0000, 0.7490 },
169 | { 0.2941, 0.0000, 0.7059 },
170 | { 0.3333, 0.0000, 0.6706 },
171 | { 0.3725, 0.0000, 0.6314 },
172 | { 0.4157, 0.0000, 0.5882 },
173 | { 0.4588, 0.0000, 0.5451 },
174 | { 0.5020, 0.0000, 0.5020 },
175 | { 0.5412, 0.0000, 0.4627 },
176 | { 0.5843, 0.0000, 0.4196 },
177 | { 0.6275, 0.0000, 0.3765 },
178 | { 0.6667, 0.0000, 0.3333 },
179 | { 0.7059, 0.0000, 0.2941 },
180 | { 0.7490, 0.0000, 0.2510 },
181 | { 0.7922, 0.0000, 0.2078 },
182 | { 0.8353, 0.0000, 0.1647 },
183 | { 0.8745, 0.0000, 0.1255 },
184 | { 0.9176, 0.0000, 0.0824 },
185 | { 0.9608, 0.0000, 0.0392 },
186 | };
187 |
188 | #define SWEET_SPOT_LEFT_CHANNEL 0
189 | #define SWEET_SPOT_CENTER_CHANNEL 1
190 | #define SWEET_SPOT_RIGHT_CHANNEL 2
191 |
192 | #define TWOPI 6.28318530
193 | #define FOURPI 12.56637061
194 | #define SIXPI 18.84955593
195 |
196 | enum led_types {
197 | LED_NEOPIXEL,
198 | LED_NEOPIXEL_X2,
199 | LED_DOTSTAR
200 | };
201 |
202 | CRGB16 incandescent_lookup = { 1.0000, 0.4453, 0.1562 };
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/globals.h:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------
2 | // Configuration structure ------------------------------------
3 |
4 | struct conf {
5 | // Synced values
6 | float PHOTONS;
7 | float CHROMA;
8 | float MOOD;
9 | uint8_t LIGHTSHOW_MODE;
10 | bool MIRROR_ENABLED;
11 |
12 | // Private values
13 | uint32_t SAMPLE_RATE;
14 | uint8_t NOTE_OFFSET;
15 | uint8_t SQUARE_ITER;
16 | uint8_t LED_TYPE;
17 | uint16_t LED_COUNT;
18 | uint16_t LED_COLOR_ORDER;
19 | bool LED_INTERPOLATION;
20 | uint16_t SAMPLES_PER_CHUNK;
21 | float SENSITIVITY;
22 | bool BOOT_ANIMATION;
23 | uint32_t SWEET_SPOT_MIN_LEVEL;
24 | uint32_t SWEET_SPOT_MAX_LEVEL;
25 | int32_t DC_OFFSET;
26 | uint8_t CHROMAGRAM_RANGE;
27 | bool STANDBY_DIMMING;
28 | bool REVERSE_ORDER;
29 | bool IS_MAIN_UNIT;
30 | uint32_t MAX_CURRENT_MA;
31 | bool TEMPORAL_DITHERING;
32 | bool AUTO_COLOR_SHIFT;
33 | float INCANDESCENT_FILTER;
34 | bool INCANDESCENT_MODE;
35 | float BULB_OPACITY;
36 | float SATURATION;
37 | uint8_t PRISM_COUNT;
38 | bool BASE_COAT;
39 | float VU_LEVEL_FLOOR;
40 | };
41 |
42 | // ------------------------------------------------------------
43 | // Defaults of the CONFIG struct (factory_reset values) -------
44 |
45 | conf CONFIG = {
46 | // Synced values
47 | 1.00, // PHOTONS
48 | 0.00, // CHROMA
49 | 0.05, // MOOD
50 | LIGHT_MODE_GDFT, // LIGHTSHOW_MODE
51 | true, // MIRROR_ENABLED
52 |
53 | // Private values
54 | DEFAULT_SAMPLE_RATE, // SAMPLE_RATE
55 | 12, // NOTE_OFFSET
56 | 1, // SQUARE_ITER
57 | LED_NEOPIXEL, // LED_TYPE
58 | 128, // LED_COUNT
59 | GRB, // LED_COLOR_ORDER
60 | true, // LED_INTERPOLATION
61 | 96, // SAMPLES_PER_CHUNK
62 | 1.0, // SENSITIVITY
63 | true, // BOOT_ANIMATION
64 | 750, // SWEET_SPOT_MIN_LEVEL
65 | 30000, // SWEET_SPOT_MAX_LEVEL
66 | 0, // DC_OFFSET
67 | 60, // CHROMAGRAM_RANGE
68 | true, // STANDBY_DIMMING
69 | false, // REVERSE_ORDER
70 | false, // IS_MAIN_UNIT
71 | 1500, // MAX_CURRENT_MA
72 | true, // TEMPORAL_DITHERING
73 | false, // AUTO_COLOR_SHIFT
74 | 0.50, // INCANDESCENT_FILTER
75 | false, // INCANDESCENT_MODE
76 | 0.00, // BULB_OPACITY
77 | 1.00, // SATURATION
78 | 0, // PRISM_COUNT
79 | false, // BASE_COAT
80 | 0.00, // VU_LEVEL_FLOOR
81 | };
82 |
83 | conf CONFIG_DEFAULTS; // Used for resetting to default values at runtime
84 |
85 | char mode_names[NUM_MODES*32] = { 0 };
86 |
87 | // ------------------------------------------------------------
88 | // Goertzel structure (generated in system.h) -----------------
89 |
90 | struct freq {
91 | float target_freq;
92 | int32_t coeff_q14;
93 |
94 | uint16_t block_size;
95 | float block_size_recip;
96 | uint8_t zone;
97 |
98 | float a_weighting_ratio;
99 | float window_mult;
100 | };
101 | freq frequencies[NUM_FREQS];
102 |
103 | // ------------------------------------------------------------
104 | // Hann window lookup table (generated in system.h) -----------
105 |
106 | int16_t window_lookup[4096] = { 0 };
107 |
108 | // ------------------------------------------------------------
109 | // A-weighting lookup table (parsed in system.h) --------------
110 |
111 | float a_weight_table[13][2] = {
112 | { 10, -70.4 }, // hz, db
113 | { 20, -50.5 },
114 | { 40, -34.6 },
115 | { 80, -22.5 },
116 | { 160, -13.4 },
117 | { 315, -6.6 },
118 | { 630, -1.9 },
119 | { 1000, 0.0 },
120 | { 1250, 0.6 },
121 | { 2500, 1.3 },
122 | { 5000, 0.5 },
123 | { 10000, -2.5 },
124 | { 20000, -9.3 }
125 | };
126 |
127 | // ------------------------------------------------------------
128 | // Spectrograms (GDFT.h) --------------------------------------
129 |
130 | SQ15x16 spectrogram[NUM_FREQS] = { 0.0 };
131 | SQ15x16 spectrogram_smooth[NUM_FREQS] = { 0.0 };
132 | SQ15x16 chromagram_smooth[12] = { 0.0 };
133 |
134 | SQ15x16 spectral_history[SPECTRAL_HISTORY_LENGTH][NUM_FREQS];
135 | SQ15x16 novelty_curve[SPECTRAL_HISTORY_LENGTH] = { 0.0 };
136 |
137 | uint8_t spectral_history_index = 0;
138 |
139 | float note_spectrogram[NUM_FREQS] = {0};
140 | float note_spectrogram_smooth[NUM_FREQS] = {0};
141 | float note_spectrogram_smooth_frame_blending[NUM_FREQS] = {0};
142 | float note_spectrogram_long_term[NUM_FREQS] = {0};
143 | float note_chromagram[12] = {0};
144 | float chromagram_max_val = 0.0;
145 | float chromagram_bass_max_val = 0.0;
146 |
147 | float smoothing_follower = 0.0;
148 | float smoothing_exp_average = 0.0;
149 |
150 | SQ15x16 chroma_val = 1.0;
151 | bool chromatic_mode = true;
152 |
153 | // ------------------------------------------------------------
154 | // Audio samples (i2s_audio.h) --------------------------------
155 |
156 | int32_t i2s_samples_raw[1024] = { 0 };
157 | short sample_window[SAMPLE_HISTORY_LENGTH] = { 0 };
158 | short waveform[1024] = { 0 };
159 | SQ15x16 waveform_fixed_point[1024] = { 0 };
160 | short waveform_history[4][1024] = { 0 };
161 | uint8_t waveform_history_index = 0;
162 | float max_waveform_val_raw = 0.0;
163 | float max_waveform_val = 0.0;
164 | float max_waveform_val_follower = 0.0;
165 | float waveform_peak_scaled = 0.0;
166 | int32_t dc_offset_sum = 0;
167 | bool silence = false;
168 | float silent_scale = 1.0;
169 | float current_punch = 0.0;
170 |
171 | // ------------------------------------------------------------
172 | // Sweet Spot (i2s_audio.h, led_utilities.h) ------------------
173 |
174 | float sweet_spot_state = 0;
175 | float sweet_spot_state_follower = 0;
176 | float sweet_spot_min_temp = 0;
177 |
178 | // ------------------------------------------------------------
179 | // Noise calibration (noise_cal.h) ----------------------------
180 |
181 | bool noise_complete = true;
182 | SQ15x16 noise_samples[NUM_FREQS] = { 1 };
183 | uint16_t noise_iterations = 0;
184 |
185 | // ------------------------------------------------------------
186 | // Display buffers (led_utilities.h) --------------------------
187 |
188 | /*
189 | CRGB leds[128];
190 | CRGB leds_frame_blending[128];
191 | CRGB leds_fx[128];
192 | CRGB leds_temp[128];
193 | CRGB leds_last[128];
194 | CRGB leds_aux [128];
195 | CRGB leds_fade[128];
196 | */
197 |
198 | CRGB16 leds_16[128];
199 | CRGB16 leds_16_prev[128];
200 | CRGB16 leds_16_fx[128];
201 | CRGB16 leds_16_fx_2[128];
202 | CRGB16 leds_16_temp[128];
203 | CRGB16 leds_16_ui[128];
204 |
205 | SQ15x16 ui_mask[128];
206 | SQ15x16 ui_mask_height = 0.0;
207 |
208 | CRGB16 *leds_scaled;
209 | CRGB *leds_out;
210 |
211 | SQ15x16 hue_shift = 0.0; // Used in auto color cycling
212 |
213 | uint8_t dither_step = 0;
214 | bool led_thread_halt = false;
215 | TaskHandle_t led_task;
216 |
217 | // ------------------------------------------------------------
218 | // Benchmarking (system.h) ------------------------------------
219 |
220 | Ticker cpu_usage;
221 | volatile uint16_t function_id = 0;
222 | volatile uint16_t function_hits[32] = {0};
223 | float SYSTEM_FPS = 0.0;
224 | float LED_FPS = 0.0;
225 |
226 | // ------------------------------------------------------------
227 | // SensorySync P2P network (p2p.h) ----------------------------
228 |
229 | bool main_override = true;
230 | uint32_t last_rx_time = 0;
231 |
232 | // ------------------------------------------------------------
233 | // Buttons (buttons.h) ----------------------------------------
234 |
235 | // TODO: Similar structs for knobs
236 | struct button{
237 | uint8_t pin = 0;
238 | uint32_t last_down = 0;
239 | uint32_t last_up = 0;
240 | bool pressed = false;
241 | };
242 |
243 | button noise_button;
244 | button mode_button;
245 |
246 | bool mode_transition_queued = false;
247 | int16_t mode_destination = -1;
248 |
249 | bool noise_transition_queued = false;
250 |
251 | // ------------------------------------------------------------
252 | // Settings tracking (system.h) -------------------------------
253 |
254 | uint32_t next_save_time = 0;
255 | bool settings_updated = false;
256 |
257 | // ------------------------------------------------------------
258 | // Serial buffer (serial_menu.h) ------------------------------
259 |
260 | char command_buf[128] = {0};
261 | uint8_t command_buf_index = 0;
262 |
263 | bool stream_audio = false;
264 | bool stream_fps = false;
265 | bool stream_max_mags = false;
266 | bool stream_max_mags_followers = false;
267 | bool stream_magnitudes = false;
268 | bool stream_spectrogram = false;
269 | bool stream_chromagram = false;
270 |
271 | bool debug_mode = false;
272 | uint64_t chip_id = 0;
273 | uint32_t chip_id_high = 0;
274 | uint32_t chip_id_low = 0;
275 |
276 | uint32_t serial_iter = 0;
277 |
278 | // ------------------------------------------------------------
279 | // Spectrogram normalization (GDFT.h) -------------------------
280 |
281 | float max_mags[NUM_ZONES] = { 0.000 };
282 | float max_mags_followers[NUM_ZONES] = { 0.000 };
283 | float mag_targets[NUM_FREQS] = { 0.000 };
284 | float mag_followers[NUM_FREQS] = { 0.000 };
285 | float mag_float_last[NUM_FREQS] = { 0.000 };
286 | int32_t magnitudes[NUM_FREQS] = { 0 };
287 | float magnitudes_normalized[NUM_FREQS] = { 0.000 };
288 | float magnitudes_normalized_avg[NUM_FREQS] = { 0.000 };
289 | float magnitudes_last[NUM_FREQS] = { 0.000 };
290 | float magnitudes_final[NUM_FREQS] = { 0.000 };
291 |
292 | // ------------------------------------------------------------
293 | // Look-ahead smoothing (GDFT.h) ------------------------------
294 |
295 | const uint8_t spectrogram_history_length = 3;
296 | float spectrogram_history[spectrogram_history_length][64];
297 | uint8_t spectrogram_history_index = 0;
298 |
299 | // ------------------------------------------------------------
300 | // Used for converting for storage in LittleFS (bridge_fs.h) --
301 |
302 | union bytes_32 {
303 | uint32_t long_val;
304 | int32_t long_val_signed;
305 | float long_val_float;
306 | uint8_t bytes[4];
307 | };
308 |
309 | // ------------------------------------------------------------
310 | // Used for GDFT mode (lightshow_modes.h) ---------------------
311 |
312 | uint8_t brightness_levels[NUM_FREQS] = { 0 };
313 |
314 | // ------------------------------------------------------------
315 | // Used for USB updates (system.h) ----------------------------
316 |
317 | FirmwareMSC MSC_Update;
318 | USBCDC USBSerial;
319 | bool msc_update_started = false;
320 |
321 | // DOTS
322 | DOT dots[MAX_DOTS];
323 |
324 | // Auto Color Shift
325 | SQ15x16 hue_position = 0.0;
326 | SQ15x16 hue_shift_speed = 0.0;
327 | SQ15x16 hue_push_direction = -1.0;
328 | SQ15x16 hue_destination = 0.0;
329 | SQ15x16 hue_shifting_mix = -0.35;
330 | SQ15x16 hue_shifting_mix_target = 1.0;
331 |
332 | // VU Calculation
333 | SQ15x16 audio_vu_level = 0.0;
334 | SQ15x16 audio_vu_level_average = 0.0;
335 | SQ15x16 audio_vu_level_last = 0.0;
336 |
337 | // Knobs
338 | KNOB knob_photons;
339 | KNOB knob_chroma;
340 | KNOB knob_mood;
341 | uint8_t current_knob = K_NONE;
342 |
343 | // Base Coat
344 | SQ15x16 base_coat_width = 0.0;
345 | SQ15x16 base_coat_width_target = 1.0;
346 |
347 | // Config File
348 | char config_filename[24];
349 |
350 | // WIP BELOW --------------------------------------------------
351 |
352 | float MASTER_BRIGHTNESS = 0.0;
353 | float last_sample = 0;
354 |
355 | void lock_leds(){
356 | //led_thread_halt = true;
357 | //delay(20); // Potentially waiting for LED thread to finish its loop
358 | }
359 |
360 | void unlock_leds(){
361 | //led_thread_halt = false;
362 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/i2s_audio.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge I2S FUNCTIONS
3 | ----------------------------------------*/
4 |
5 | #include
6 |
7 | const i2s_config_t i2s_config = {
8 | // Many of these settings are defined in (constants.h)
9 | .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
10 | .sample_rate = CONFIG.SAMPLE_RATE,
11 | .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
12 | .channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT,
13 | .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
14 | //.intr_alloc_flags = 0,
15 | .dma_buf_count = 2,
16 | .dma_buf_len = CONFIG.SAMPLES_PER_CHUNK,
17 | //.use_apll = true,
18 | };
19 |
20 | const i2s_pin_config_t pin_config = { // These too
21 | .bck_io_num = I2S_BCLK_PIN,
22 | .ws_io_num = I2S_LRCLK_PIN,
23 | .data_out_num = -1, // not used (only for outputs)
24 | .data_in_num = I2S_DIN_PIN
25 | };
26 |
27 | void init_i2s() {
28 | // Init I2S Driver
29 | esp_err_t result = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
30 | USBSerial.print("INIT I2S: ");
31 | USBSerial.println(result == ESP_OK ? PASS : FAIL);
32 |
33 | // ESP32-S2 changes to help SPH0645 mic
34 | #if defined(CONFIG_IDF_TARGET_ESP32S2)
35 | REG_SET_BIT(I2S_TIMING_REG(I2S_PORT), BIT(9));
36 | REG_SET_BIT(I2S_CONF_REG(I2S_PORT), I2S_RX_MSB_SHIFT);
37 | #endif
38 |
39 | // Set I2S pins
40 | result = i2s_set_pin(I2S_PORT, &pin_config);
41 | USBSerial.print("I2S SET PINS: ");
42 | USBSerial.println(result == ESP_OK ? PASS : FAIL);
43 | }
44 |
45 | void acquire_sample_chunk(uint32_t t_now) {
46 | static int8_t sweet_spot_state_last = 0;
47 | static bool silence_temp = false;
48 | static uint32_t silence_switched = 0;
49 | static float silent_scale_last = 1.0;
50 |
51 | size_t bytes_read = 0;
52 | i2s_read(I2S_PORT, i2s_samples_raw, CONFIG.SAMPLES_PER_CHUNK * sizeof(int32_t), &bytes_read, portMAX_DELAY);
53 |
54 | max_waveform_val = 0.0;
55 | max_waveform_val_raw = 0.0;
56 | waveform_history_index++;
57 | if (waveform_history_index >= 4) {
58 | waveform_history_index = 0;
59 | }
60 |
61 | // Scale I2S samples and store into history
62 | for (uint16_t i = 0; i < CONFIG.SAMPLES_PER_CHUNK; i++) {
63 | int32_t sample = (i2s_samples_raw[i] * 0.000512) + 56000 - 5120;
64 |
65 | //USBSerial.println(sample);
66 |
67 | sample = sample >> 2; // Helps prevent overflow in fixed-point math coming up
68 |
69 | sample *= CONFIG.SENSITIVITY; // Set sensitivity gain
70 |
71 | if (sample > 32767) { // clipping
72 | sample = 32767;
73 | } else if (sample < -32767) {
74 | sample = -32767;
75 | }
76 |
77 | waveform[i] = sample - CONFIG.DC_OFFSET;
78 | waveform_history[waveform_history_index][i] = waveform[i];
79 |
80 | uint32_t sample_abs = abs(sample);
81 | if (sample_abs > max_waveform_val_raw) {
82 | max_waveform_val_raw = sample_abs;
83 | }
84 | }
85 |
86 | if (stream_audio == true) {
87 | USBSerial.print("sbs((audio=");
88 | for (uint16_t i = 0; i < CONFIG.SAMPLES_PER_CHUNK; i++) {
89 | USBSerial.print(waveform[i]);
90 | if (i < CONFIG.SAMPLES_PER_CHUNK - 1) {
91 | USBSerial.print(',');
92 | }
93 | }
94 | USBSerial.println("))");
95 | }
96 |
97 | if (noise_complete == false) {
98 | dc_offset_sum += waveform[0];
99 |
100 | silent_scale = 1.0; // Force LEDs on during calibration
101 |
102 | if (noise_iterations >= 64 && noise_iterations <= 192) { // sample in the middle of noise cal
103 | if (max_waveform_val_raw * 1.10 > CONFIG.SWEET_SPOT_MIN_LEVEL) { // Sweet Spot Min threshold should be the silence level + 15%
104 | CONFIG.SWEET_SPOT_MIN_LEVEL = max_waveform_val_raw * 1.10;
105 | }
106 | }
107 | } else {
108 | max_waveform_val = (max_waveform_val_raw - (CONFIG.SWEET_SPOT_MIN_LEVEL));
109 |
110 | if (max_waveform_val > max_waveform_val_follower) {
111 | float delta = max_waveform_val - max_waveform_val_follower;
112 | max_waveform_val_follower += delta * 0.25;
113 | } else if (max_waveform_val < max_waveform_val_follower) {
114 | float delta = max_waveform_val_follower - max_waveform_val;
115 | max_waveform_val_follower -= delta * 0.005;
116 |
117 | if (max_waveform_val_follower < CONFIG.SWEET_SPOT_MIN_LEVEL) {
118 | max_waveform_val_follower = CONFIG.SWEET_SPOT_MIN_LEVEL;
119 | }
120 | }
121 | float waveform_peak_scaled_raw = max_waveform_val / max_waveform_val_follower;
122 |
123 | if (waveform_peak_scaled_raw > waveform_peak_scaled) {
124 | float delta = waveform_peak_scaled_raw - waveform_peak_scaled;
125 | waveform_peak_scaled += delta * 0.25;
126 | } else if (waveform_peak_scaled_raw < waveform_peak_scaled) {
127 | float delta = waveform_peak_scaled - waveform_peak_scaled_raw;
128 | waveform_peak_scaled -= delta * 0.25;
129 | }
130 |
131 | // Use the maximum amplitude of the captured frame to set
132 | // the Sweet Spot state. Think of this like a coordinate
133 | // space where 0 is the center LED, -1 is the left, and
134 | // +1 is the right. See run_sweet_spot() in led_utilities.h
135 | // for how this value translates to the final LED brightnesses
136 |
137 | if (max_waveform_val_raw <= CONFIG.SWEET_SPOT_MIN_LEVEL * 1.10) {
138 | sweet_spot_state = -1;
139 | if (sweet_spot_state_last != -1) { // Just became silent
140 | silence_temp = true;
141 | silence_switched = t_now;
142 | }
143 | } else if (max_waveform_val_raw >= CONFIG.SWEET_SPOT_MAX_LEVEL) {
144 | sweet_spot_state = 1;
145 | if (sweet_spot_state_last != 1) { // No longer silent
146 | silence_temp = false;
147 | silence_switched = t_now;
148 | }
149 | } else {
150 | sweet_spot_state = 0;
151 | if (sweet_spot_state_last != 0) { // No longer silent
152 | silence_temp = false;
153 | silence_switched = t_now;
154 | }
155 | }
156 |
157 | if (silence_temp == true) {
158 | if (t_now - silence_switched >= 10000) {
159 | silence = true;
160 | }
161 | } else {
162 | silence = false;
163 | }
164 |
165 |
166 | if (CONFIG.STANDBY_DIMMING == true) {
167 | // Make silent_scale more slowly track instant change in reality
168 | float silent_scale_raw = 1.0 - silence; // Turn off when quiet
169 | silent_scale = silent_scale_raw * 0.1 + silent_scale_last * 0.9;
170 | silent_scale_last = silent_scale;
171 | } else {
172 | silent_scale = 1.0;
173 | }
174 |
175 | for (int i = 0; i < SAMPLE_HISTORY_LENGTH - CONFIG.SAMPLES_PER_CHUNK; i++) {
176 | sample_window[i] = sample_window[i + CONFIG.SAMPLES_PER_CHUNK];
177 | }
178 | for (int i = SAMPLE_HISTORY_LENGTH - CONFIG.SAMPLES_PER_CHUNK; i < SAMPLE_HISTORY_LENGTH; i++) {
179 | sample_window[i] = waveform[i - (SAMPLE_HISTORY_LENGTH - CONFIG.SAMPLES_PER_CHUNK)];
180 | }
181 |
182 | for (uint16_t i = 0; i < CONFIG.SAMPLES_PER_CHUNK; i++) {
183 | waveform_fixed_point[i] = SQ15x16(waveform[i]) / SQ15x16(32768.0);
184 | }
185 |
186 | sweet_spot_state_last = sweet_spot_state;
187 | }
188 | }
189 |
190 | void calculate_vu() {
191 | /*
192 | Calculates perceived audio loudness or Volume Unit (VU). Uses root mean square (RMS) method
193 | for accurate representation of perceived loudness and incorporates a noise floor calibration.
194 | If calibration is active, updates noise floor level. If not, subtracts the noise floor from
195 | the calculated volume and normalizes the volume level.
196 |
197 | Parameters:
198 | - audio_samples[]: Audio samples to process.
199 | - sample_count: Number of samples in audio_samples array.
200 |
201 | Global variables:
202 | - audio_vu_level: Current VU level.
203 | - audio_vu_level_last: Last calculated VU level.
204 | - CONFIG.VU_LEVEL_FLOOR: Quietest level considered as audio signal.
205 | - audio_vu_level_average: Average of the current and the last VU level.
206 | - noise_cal_active: Indicator of active noise floor calibration.
207 | */
208 |
209 | // Store last volume level
210 | audio_vu_level_last = audio_vu_level;
211 |
212 | float sum = 0.0;
213 |
214 | // Compute sum of squares
215 | for (uint16_t i = 0; i < CONFIG.SAMPLES_PER_CHUNK; i++) {
216 | sum += float(waveform_fixed_point[i] * waveform_fixed_point[i]);
217 | }
218 |
219 | // Compute RMS
220 | SQ15x16 rms = sqrt(float(sum / CONFIG.SAMPLES_PER_CHUNK));
221 |
222 | // Update volume level
223 | audio_vu_level = rms;
224 |
225 | // Check noise calibration
226 | if (noise_complete == false) {
227 | // If volume level exceeds noise floor, update noise floor
228 | if (float(audio_vu_level * 1.5) > CONFIG.VU_LEVEL_FLOOR) {
229 | CONFIG.VU_LEVEL_FLOOR = float(audio_vu_level * 1.5);
230 | }
231 | } else {
232 | // Subtract noise floor from volume level
233 | audio_vu_level -= CONFIG.VU_LEVEL_FLOOR;
234 |
235 | // Zero out negative volume
236 | if (audio_vu_level < 0.0) {
237 | audio_vu_level = 0.0;
238 | }
239 |
240 | // Normalize volume level
241 | CONFIG.VU_LEVEL_FLOOR = min(0.99f, CONFIG.VU_LEVEL_FLOOR);
242 | audio_vu_level /= (1.0 - CONFIG.VU_LEVEL_FLOOR);
243 | }
244 |
245 | // Compute average volume level
246 | audio_vu_level_average = (audio_vu_level + audio_vu_level_last) / (2.0);
247 | }
248 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/knobs.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge KNOB FUNCTIONS
3 | ----------------------------------------*/
4 |
5 | uint16_t avg_read(uint8_t pin) {
6 | uint32_t sum = 0;
7 | sum += analogRead(pin);
8 | sum += analogRead(pin);
9 | return sum >> 1;
10 | }
11 |
12 | void check_knobs(uint32_t t_now) {
13 | // On every 10th frame, the knobs are read. The resulting
14 | // values are put through the same "follower" smoothing
15 | // algorithm detailed in GDFT.h.
16 | //
17 | // If a knob value changes more than 5% and this unit is
18 | // not set to the MAIN unit, it will flash all units in the
19 | // network (p2p.h) to identify which unit's knobs to modify
20 | // instead to affect changes.
21 |
22 | static uint32_t iter = 0;
23 | static float PHOTONS_TARGET = 1.0;
24 | static float CHROMA_TARGET = 1.0;
25 | static float MOOD_TARGET = 1.0;
26 |
27 | static float PHOTONS_OUTPUT = 1.0;
28 | static float CHROMA_OUTPUT = 1.0;
29 | static float MOOD_OUTPUT = 1.0;
30 |
31 | static float PHOTONS_TARGET_LAST = 1.0;
32 | static float CHROMA_TARGET_LAST = 1.0;
33 | static float MOOD_TARGET_LAST = 1.0;
34 |
35 | iter++;
36 |
37 | if (iter % 1 == 0) { // If frame count is multiple of 2
38 | PHOTONS_TARGET = (1.0 - (avg_read(PHOTONS_PIN) / 8192.0));
39 | CHROMA_TARGET = (1.0 - (avg_read(CHROMA_PIN) / 8192.0));
40 | MOOD_TARGET = (1.0 - (avg_read(MOOD_PIN) / 8192.0));
41 | }
42 |
43 | // Happens every frame:
44 | if (PHOTONS_TARGET > PHOTONS_OUTPUT) {
45 | float delta = fabs(PHOTONS_TARGET - PHOTONS_OUTPUT);
46 | PHOTONS_OUTPUT += (delta * 0.1);
47 | } else if (PHOTONS_TARGET < PHOTONS_OUTPUT) {
48 | float delta = fabs(PHOTONS_TARGET - PHOTONS_OUTPUT);
49 | PHOTONS_OUTPUT -= (delta * 0.1);
50 | }
51 |
52 | if (CHROMA_TARGET > CHROMA_OUTPUT) {
53 | float delta = fabs(CHROMA_TARGET - CHROMA_OUTPUT);
54 | CHROMA_OUTPUT += (delta * 0.1);
55 | } else if (CHROMA_TARGET < CHROMA_OUTPUT) {
56 | float delta = fabs(CHROMA_TARGET - CHROMA_OUTPUT);
57 | CHROMA_OUTPUT -= (delta * 0.1);
58 | }
59 |
60 | if (MOOD_TARGET > MOOD_OUTPUT) {
61 | float delta = fabs(MOOD_TARGET - MOOD_OUTPUT);
62 | MOOD_OUTPUT += (delta * 0.1);
63 | } else if (MOOD_TARGET < MOOD_OUTPUT) {
64 | float delta = fabs(MOOD_TARGET - MOOD_OUTPUT);
65 | MOOD_OUTPUT -= (delta * 0.1);
66 | }
67 |
68 | if (CONFIG.IS_MAIN_UNIT || main_override) { // If we're MAIN unit, show changed values
69 | CONFIG.PHOTONS = PHOTONS_OUTPUT;
70 | CONFIG.CHROMA = CHROMA_OUTPUT;
71 | CONFIG.MOOD = MOOD_OUTPUT;
72 | } else { // If NOT MAIN, ignored changed values, flash all units to identify MAIN unit
73 | if (fabs(PHOTONS_TARGET - PHOTONS_TARGET_LAST) >= 0.05) {
74 | PHOTONS_TARGET_LAST = PHOTONS_TARGET;
75 | if (CONFIG.IS_MAIN_UNIT == false && main_override == false) {
76 | identify_main_unit();
77 | }
78 | }
79 | if (fabs(CHROMA_TARGET - CHROMA_TARGET_LAST) >= 0.05) {
80 | CHROMA_TARGET_LAST = CHROMA_TARGET;
81 | if (CONFIG.IS_MAIN_UNIT == false && main_override == false) {
82 | identify_main_unit();
83 | }
84 | }
85 | if (fabs(MOOD_TARGET - MOOD_TARGET_LAST) >= 0.05) {
86 | MOOD_TARGET_LAST = MOOD_TARGET;
87 | if (CONFIG.IS_MAIN_UNIT == false && main_override == false) {
88 | identify_main_unit();
89 | }
90 | }
91 | }
92 |
93 | // CHROMA Knob handling
94 | chroma_val = 1.0;
95 | if (CONFIG.CHROMA < 0.95) {
96 | chroma_val = CONFIG.CHROMA * 1.05263157; // Reciprocal of 0.95 above
97 | chromatic_mode = false;
98 | } else {
99 | chromatic_mode = true;
100 | }
101 |
102 | // Mood knob processing
103 | float smoothing_top_half = (CONFIG.MOOD - 0.5);
104 | if (smoothing_top_half < 0.0) {
105 | smoothing_top_half = 0.0;
106 | }
107 | smoothing_top_half *= 2.0;
108 | // Top half of knob now has range of 0.0 (knob is centered) to 1.0 (knob fully right) accesible through this variable (stays 0.0 when in bottom half)
109 |
110 | float smoothing_bottom_half = (CONFIG.MOOD - 0.5);
111 | smoothing_bottom_half *= 2.0;
112 | if (smoothing_bottom_half > 0.0) {
113 | smoothing_bottom_half = 0.0;
114 | }
115 | smoothing_bottom_half *= -1.0;
116 | smoothing_bottom_half = 1.0 - smoothing_bottom_half;
117 | smoothing_bottom_half = (smoothing_bottom_half * 0.9) + 0.1; // 0.0-1.0 input range becomes 0.1-1.0
118 | // Bottom half of knob now has range of 0.1 (fully left) to 1.0 (knob is centered) accesible through this variable (stays 1.0 when in top half)
119 | // Making 0.1 the bottom value prevents the LEDs from experiencing 0% change per frame! ;)
120 |
121 | // These are the final values we'll feed into the two smoothing algorithms soon
122 | smoothing_follower = 0.100 + (smoothing_top_half * 0.300); // 0.0-1.0 input range becomes 0.1 - 0.400
123 | smoothing_exp_average = 1.0 - smoothing_bottom_half; // invert input
124 |
125 | // Process knob speed and update knob structs
126 | knob_photons.value = CONFIG.PHOTONS;
127 | knob_chroma.value = CONFIG.CHROMA;
128 | knob_mood.value = CONFIG.MOOD;
129 |
130 | SQ15x16 speed_threshold = 0.005;
131 |
132 | knob_photons.change_rate = fabs_fixed(knob_photons.value - knob_photons.last_value);
133 | knob_chroma.change_rate = fabs_fixed(knob_chroma.value - knob_chroma.last_value);
134 | knob_mood.change_rate = fabs_fixed(knob_mood.value - knob_mood.last_value);
135 |
136 | if (knob_photons.change_rate > speed_threshold) { knob_photons.last_change = t_now; }
137 | if (knob_chroma.change_rate > speed_threshold) { knob_chroma.last_change = t_now; }
138 | if (knob_mood.change_rate > speed_threshold) { knob_mood.last_change = t_now; }
139 |
140 | uint16_t knob_timeout_ms = 1500;
141 |
142 | uint32_t most_recent_time = 0;
143 | uint8_t most_recent_knob = K_NONE;
144 | if ((t_now - knob_photons.last_change) <= knob_timeout_ms && knob_photons.last_change > most_recent_time) {
145 | most_recent_time = knob_photons.last_change;
146 | most_recent_knob = K_PHOTONS;
147 | }
148 | if ((t_now - knob_chroma.last_change) <= knob_timeout_ms && knob_chroma.last_change > most_recent_time) {
149 | most_recent_time = knob_chroma.last_change;
150 | most_recent_knob = K_CHROMA;
151 | }
152 | if ((t_now - knob_mood.last_change) <= knob_timeout_ms && knob_mood.last_change > most_recent_time) {
153 | most_recent_time = knob_mood.last_change;
154 | most_recent_knob = K_MOOD;
155 | }
156 |
157 | current_knob = most_recent_knob;
158 |
159 | knob_photons.last_value = knob_photons.value;
160 | knob_chroma.last_value = knob_chroma.value;
161 | knob_mood.last_value = knob_mood.value;
162 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/lightshow_modes.h:
--------------------------------------------------------------------------------
1 | void get_smooth_spectrogram() {
2 | static SQ15x16 spectrogram_smooth_last[64];
3 |
4 | for (uint8_t bin = 0; bin < 64; bin++) {
5 | SQ15x16 note_brightness = spectrogram[bin];
6 |
7 | if (spectrogram_smooth[bin] < note_brightness) {
8 | SQ15x16 distance = note_brightness - spectrogram_smooth[bin];
9 | spectrogram_smooth[bin] += distance * SQ15x16(0.75);
10 |
11 | } else if (spectrogram_smooth[bin] > note_brightness) {
12 | SQ15x16 distance = spectrogram_smooth[bin] - note_brightness;
13 | spectrogram_smooth[bin] -= distance * SQ15x16(0.75);
14 | }
15 | }
16 | }
17 |
18 | CRGB calc_chromagram_color() {
19 | CRGB sum_color = CRGB(0, 0, 0);
20 | for (uint8_t i = 0; i < 12; i++) {
21 | float prog = i / 12.0;
22 |
23 | float bright = note_chromagram[i];
24 | for (uint8_t s = 0; s < CONFIG.SQUARE_ITER + 1; s++) {
25 | bright *= bright;
26 | }
27 | bright *= 0.5;
28 |
29 | if (bright > 1.0) {
30 | bright = 1.0;
31 | }
32 |
33 | if (chromatic_mode == true) {
34 | CRGB out_col = CHSV(255 * prog, 255 * CONFIG.SATURATION, 255 * bright);
35 | //out_col.r = scale8(out_col.r, out_col.r);
36 | //out_col.g = scale8(out_col.g, out_col.g);
37 | //out_col.b = scale8(out_col.b, out_col.b);
38 | sum_color += out_col;
39 | } else {
40 | //sum_color += hsv(255 * float(chroma_val) + float(hue_shift), 255 * CONFIG.SATURATION, 255 * bright);
41 | }
42 | }
43 |
44 | if (chromatic_mode == false) {
45 | sum_color = force_saturation(sum_color, 255 * CONFIG.SATURATION);
46 | }
47 |
48 | return sum_color;
49 | }
50 |
51 | void avg_bins(uint8_t low_bin, uint8_t high_bin) {
52 | // TBD
53 | }
54 |
55 | void test_mode() {
56 | static float radians = 0.00;
57 | radians += CONFIG.MOOD;
58 | float position = sin(radians) * 0.5 + 0.5;
59 | set_dot_position(RESERVED_DOTS + 0, position);
60 | clear_leds();
61 | draw_dot(leds_16, RESERVED_DOTS + 0, hsv(chroma_val, CONFIG.SATURATION, CONFIG.PHOTONS * CONFIG.PHOTONS));
62 | }
63 |
64 | // Default mode!
65 | void light_mode_gdft() {
66 | for (SQ15x16 i = 0; i < NUM_FREQS; i += 1) { // 64 freqs
67 | SQ15x16 prog = i / (SQ15x16)NUM_FREQS;
68 | SQ15x16 bin = spectrogram_smooth[i.getInteger()];
69 | if (bin > 1.0) { bin = 1.0; }
70 |
71 | uint8_t extra_iters = 0;
72 | if (chromatic_mode == true) {
73 | extra_iters = 1;
74 | }
75 | for (uint8_t s = 0; s < CONFIG.SQUARE_ITER + extra_iters; s++) {
76 | bin = (bin * bin) * SQ15x16(0.65) + (bin * SQ15x16(0.35));
77 | }
78 |
79 | //bin = apply_contrast_fixed(bin, 0.04);
80 |
81 | //bin *= SQ15x16(1.0 - CONFIG.BACKDROP_BRIGHTNESS);
82 | //bin += SQ15x16(CONFIG.BACKDROP_BRIGHTNESS);
83 |
84 | SQ15x16 led_hue;
85 | if (chromatic_mode == true) {
86 | led_hue = note_colors[i.getInteger() % 12]; // Makes hue completely cycle once per octave
87 | } else {
88 | led_hue = chroma_val + hue_position + ((sqrt(float(bin)) * SQ15x16(0.05)) + (prog * SQ15x16(0.10)) * hue_shifting_mix);
89 | }
90 |
91 | leds_16[i.getInteger()] = hsv(led_hue + bin * SQ15x16(0.050), CONFIG.SATURATION, bin);
92 | }
93 |
94 | shift_leds_up(leds_16, 64); // (led_utilities.h) Move image up one half
95 | mirror_image_downwards(leds_16); // (led_utilities.h) Mirror downwards
96 | }
97 |
98 | /*
99 | void light_mode_gdft_chromagram() {
100 | for (uint16_t i = 0; i < NATIVE_RESOLUTION; i++) {
101 | float prog = i / float(NATIVE_RESOLUTION);
102 |
103 | float bin = interpolate(prog, note_chromagram, 12) * 1.25;
104 | if (bin > 1.0) { bin = 1.0; };
105 |
106 | for (uint8_t s = 0; s < CONFIG.SQUARE_ITER + 1; s++) {
107 | bin = bin * bin;
108 | }
109 |
110 | bin *= 1.0 - CONFIG.BACKDROP_BRIGHTNESS;
111 | bin += CONFIG.BACKDROP_BRIGHTNESS;
112 |
113 | float led_brightness_raw = 254 * bin; // -1 for temporal dithering below
114 | uint16_t led_brightness = led_brightness_raw;
115 | float fract = led_brightness_raw - led_brightness;
116 |
117 | if (CONFIG.TEMPORAL_DITHERING == true) {
118 | if (fract >= dither_table[dither_step]) {
119 | led_brightness += 1;
120 | }
121 | }
122 |
123 | float led_hue;
124 | if (chromatic_mode == true) {
125 | //led_hue = 255 * prog;
126 | } else {
127 | //led_hue = 255 * chroma_val + (i >> 1) + hue_shift;
128 | }
129 |
130 | //leds[i] = CHSV(led_hue + hue_shift, 255 * CONFIG.SATURATION, led_brightness);
131 | }
132 | }
133 | */
134 |
135 | /*
136 | void light_mode_bloom(bool fast_scroll) {
137 | static uint32_t iter = 0;
138 | const float led_share = 1.0 / 12.0;
139 | iter++;
140 |
141 | if (bitRead(iter, 0) == 0) {
142 | CRGB sum_color = calc_chromagram_color();
143 |
144 | //sum_color = force_saturation(sum_color, 255 * CONFIG.SATURATION);
145 |
146 | if (fast_scroll == true) { // Fast mode scrolls two LEDs at a time
147 | for (uint8_t i = 0; i < NATIVE_RESOLUTION - 2; i++) {
148 | leds_fx[(NATIVE_RESOLUTION - 1) - i] = leds_last[(NATIVE_RESOLUTION - 1) - i - 2];
149 | }
150 |
151 | leds_fx[0] = sum_color; // New information goes here
152 | leds_fx[1] = sum_color; // New information goes here
153 |
154 | } else { // Slow mode only scrolls one LED at a time
155 | for (uint8_t i = 0; i < NATIVE_RESOLUTION - 1; i++) {
156 | leds_fx[(NATIVE_RESOLUTION - 1) - i] = leds_last[(NATIVE_RESOLUTION - 1) - i - 1];
157 | }
158 |
159 | leds_fx[0] = sum_color; // New information goes here
160 | }
161 |
162 | load_leds_from_fx();
163 | save_leds_to_last();
164 |
165 | //fadeToBlackBy(leds, 128, 255-255*waveform_peak_scaled);
166 |
167 | distort_logarithmic();
168 | //distort_exponential();
169 |
170 | fade_top_half(CONFIG.MIRROR_ENABLED); // fade at different location depending if mirroring is enabled
171 | //increase_saturation(32);
172 |
173 | save_leds_to_aux();
174 | } else {
175 | load_leds_from_aux();
176 | }
177 | }
178 | */
179 |
180 | void light_mode_vu_dot() {
181 | static SQ15x16 dot_pos_last = 0.0;
182 | static SQ15x16 audio_vu_level_smooth = 0.0;
183 | static SQ15x16 max_level = 0.01;
184 |
185 | SQ15x16 mix_amount = mood_scale(0.10, 0.05);
186 |
187 | audio_vu_level_smooth = (audio_vu_level_average * mix_amount) + (audio_vu_level_smooth * (1.0 - mix_amount));
188 |
189 | if (audio_vu_level_smooth * 1.1 > max_level) {
190 | SQ15x16 distance = (audio_vu_level_smooth * 1.1) - max_level;
191 | max_level += distance *= 0.1;
192 | } else {
193 | max_level *= 0.9999;
194 | if (max_level < 0.0025) {
195 | max_level = 0.0025;
196 | }
197 | }
198 | SQ15x16 multiplier = 1.0 / max_level;
199 |
200 | SQ15x16 dot_pos = (audio_vu_level_smooth * multiplier);
201 |
202 | if (dot_pos > 1.0) {
203 | dot_pos = 1.0;
204 | }
205 |
206 | SQ15x16 mix = mood_scale(0.25, 0.24);
207 | SQ15x16 dot_pos_smooth = (dot_pos * mix) + (dot_pos_last * (1.0-mix));
208 | dot_pos_last = dot_pos_smooth;
209 |
210 | SQ15x16 brightness = sqrt(float(dot_pos_smooth));
211 |
212 | set_dot_position(RESERVED_DOTS + 0, dot_pos_smooth * 0.5 + 0.5);
213 | set_dot_position(RESERVED_DOTS + 1, 0.5 - dot_pos_smooth * 0.5);
214 |
215 | clear_leds();
216 | //fade_grayscale(0.15);
217 |
218 | SQ15x16 hue = chroma_val + hue_position;
219 | CRGB16 color = hsv(hue, CONFIG.SATURATION, brightness);
220 | draw_dot(leds_16, RESERVED_DOTS + 0, color);
221 | draw_dot(leds_16, RESERVED_DOTS + 1, color);
222 | }
223 |
224 | void light_mode_kaleidoscope() {
225 | static float pos_r = 0.0;
226 | static float pos_g = 0.0;
227 | static float pos_b = 0.0;
228 |
229 | static SQ15x16 brightness_low = 0.0;
230 | static SQ15x16 brightness_mid = 0.0;
231 | static SQ15x16 brightness_high = 0.0;
232 |
233 |
234 |
235 |
236 |
237 | SQ15x16 sum_low = 0.0;
238 | SQ15x16 sum_mid = 0.0;
239 | SQ15x16 sum_high = 0.0;
240 |
241 | for (uint8_t i = 0; i < 20; i++) {
242 | SQ15x16 bin = spectrogram_smooth[0 + i];
243 | bin = bin * 0.5 + (bin * bin) * 0.5;
244 | sum_low += bin;
245 | if (bin > brightness_low) {
246 | SQ15x16 dist = fabs_fixed(bin - brightness_low);
247 | brightness_low += dist * 0.1;
248 | }
249 | }
250 | for (uint8_t i = 0; i < 20; i++) {
251 | SQ15x16 bin = spectrogram_smooth[20 + i];
252 | bin = bin * 0.5 + (bin * bin) * 0.5;
253 | sum_mid += bin;
254 | if (bin > brightness_mid) {
255 | SQ15x16 dist = fabs_fixed(bin - brightness_mid);
256 | brightness_mid += dist * 0.1;
257 | }
258 | }
259 | for (uint8_t i = 0; i < 20; i++) {
260 | SQ15x16 bin = spectrogram_smooth[40 + i];
261 | bin = bin * 0.5 + (bin * bin) * 0.5;
262 | sum_high += bin;
263 | if (bin > brightness_high) {
264 | SQ15x16 dist = fabs_fixed(bin - brightness_high);
265 | brightness_high += dist * 0.1;
266 | }
267 | }
268 |
269 | brightness_low *= 0.99;
270 | brightness_mid *= 0.99;
271 | brightness_high *= 0.99;
272 |
273 | SQ15x16 shift_speed = (SQ15x16)100 + ((SQ15x16)500 * (SQ15x16)CONFIG.MOOD);
274 |
275 | SQ15x16 shift_r = (shift_speed * sum_low);
276 | SQ15x16 shift_g = (shift_speed * sum_mid);
277 | SQ15x16 shift_b = (shift_speed * sum_high);
278 |
279 | SQ15x16 speed_limit = (SQ15x16)2000 + (SQ15x16)2000 * (SQ15x16)CONFIG.MOOD;
280 |
281 | pos_r += (float)shift_r;
282 | pos_g += (float)shift_g;
283 | pos_b += (float)shift_b;
284 |
285 |
286 |
287 |
288 |
289 | for (uint8_t i = 0; i < 64; i++) {
290 | uint32_t y_pos_r = pos_r;
291 | uint32_t y_pos_g = pos_g;
292 | uint32_t y_pos_b = pos_b;
293 |
294 | uint32_t i_shifted = i + 18;
295 | uint32_t i_scaled = (i_shifted * i_shifted * i_shifted);
296 |
297 | SQ15x16 r_val = inoise16(i_scaled * 0.5 + y_pos_r) / 65536.0;
298 | SQ15x16 g_val = inoise16(i_scaled * 1.0 + y_pos_g) / 65536.0;
299 | SQ15x16 b_val = inoise16(i_scaled * 1.5 + y_pos_b) / 65536.0;
300 |
301 | if (r_val > 1.0) { r_val = 1.0; };
302 | if (g_val > 1.0) { g_val = 1.0; };
303 | if (b_val > 1.0) { b_val = 1.0; };
304 |
305 | for (uint8_t i = 0; i < CONFIG.SQUARE_ITER + 1; i++) {
306 | r_val *= r_val;
307 | g_val *= g_val;
308 | b_val *= b_val;
309 | }
310 |
311 | r_val = apply_contrast_fixed(r_val, 0.1);
312 | g_val = apply_contrast_fixed(g_val, 0.1);
313 | b_val = apply_contrast_fixed(b_val, 0.1);
314 |
315 | SQ15x16 prog = 1.0;
316 | if (i < 32) {
317 | prog = (i / 31.0);
318 | }
319 | prog *= prog;
320 |
321 | r_val *= prog * brightness_low;
322 | g_val *= prog * brightness_mid;
323 | b_val *= prog * brightness_high;
324 |
325 | CRGB16 col = { r_val, g_val, b_val };
326 | col = desaturate(col, 0.1 + (0.9 - 0.9*CONFIG.SATURATION));
327 |
328 | if (chromatic_mode == false) {
329 | SQ15x16 brightness = 0.0;
330 | if(r_val > brightness){ brightness = r_val; }
331 | if(g_val > brightness){ brightness = g_val; }
332 | if(b_val > brightness){ brightness = b_val; }
333 |
334 | SQ15x16 led_hue = chroma_val + hue_position + ((sqrt(float(brightness)) * SQ15x16(0.05)) + (prog * SQ15x16(0.10)) * hue_shifting_mix);
335 | col = hsv(led_hue, CONFIG.SATURATION, brightness);
336 | }
337 |
338 | leds_16[i] = { col.r, col.g, col.b };
339 | leds_16[NATIVE_RESOLUTION - 1 - i] = leds_16[i];
340 | }
341 | }
342 |
343 | void light_mode_chromagram_gradient() {
344 | for (uint8_t i = 0; i < 64; i++) {
345 | SQ15x16 prog = i / 64.0;
346 | SQ15x16 note_magnitude = interpolate(prog, chromagram_smooth, 12) * 0.9 + 0.1;
347 |
348 | for (uint8_t s = 0; s < CONFIG.SQUARE_ITER; s++) {
349 | note_magnitude = (note_magnitude * note_magnitude) * SQ15x16(0.65) + (note_magnitude * SQ15x16(0.35));
350 | }
351 |
352 | SQ15x16 led_hue;
353 | if (chromatic_mode == true) {
354 | led_hue = interpolate(prog, note_colors, 12);
355 | } else {
356 | led_hue = chroma_val + hue_position + ((sqrt(float(note_magnitude)) * SQ15x16(0.05)) + (prog * SQ15x16(0.10)) * hue_shifting_mix);
357 | }
358 |
359 | CRGB16 col = hsv(led_hue, CONFIG.SATURATION, note_magnitude * note_magnitude);
360 |
361 | leds_16[64 + i] = col;
362 | leds_16[63 - i] = col;
363 | }
364 | }
365 |
366 | void light_mode_chromagram_dots() {
367 | static SQ15x16 chromagram_last[12];
368 |
369 | memset(leds_16, 0, sizeof(CRGB16) * 128);
370 | //dim_display(0.9);
371 |
372 | low_pass_array_fixed(chromagram_smooth, chromagram_last, 12, LED_FPS, float(mood_scale(3.5, 1.5)));
373 | memcpy(chromagram_last, chromagram_smooth, sizeof(float) * 12);
374 |
375 | for (uint8_t i = 0; i < 12; i++) {
376 | SQ15x16 led_hue;
377 | if (chromatic_mode == true) {
378 | led_hue = note_colors[i];
379 | } else {
380 | led_hue = chroma_val + hue_position + (sqrt(float(1.0)) * SQ15x16(0.05));
381 | }
382 |
383 | SQ15x16 magnitude = chromagram_smooth[i] * 1.0;
384 | if (magnitude > 1.0) { magnitude = 1.0; }
385 |
386 | magnitude = magnitude * magnitude;
387 |
388 | CRGB16 col = hsv(led_hue, CONFIG.SATURATION, magnitude);
389 |
390 | set_dot_position(RESERVED_DOTS + i * 2 + 0, magnitude * 0.45 + 0.5);
391 | set_dot_position(RESERVED_DOTS + i * 2 + 1, 0.5 - magnitude * 0.45);
392 |
393 | draw_dot(leds_16, RESERVED_DOTS + i * 2 + 0, col);
394 | draw_dot(leds_16, RESERVED_DOTS + i * 2 + 1, col);
395 | }
396 | }
397 |
398 | void light_mode_bloom() {
399 | // Clear output
400 | memset(leds_16, 0, sizeof(CRGB16) * NATIVE_RESOLUTION);
401 |
402 | draw_sprite(leds_16, leds_16_prev, 128, 128, 0.250 + 1.750 * CONFIG.MOOD, 0.99);
403 |
404 | //-------------------------------------------------------
405 |
406 | /*
407 | SQ15x16 brightness_low = 0.0;
408 | SQ15x16 brightness_mid = 0.0;
409 | SQ15x16 brightness_high = 0.0;
410 |
411 | for (uint8_t i = 0; i < 20; i++) {
412 | SQ15x16 bin = spectrogram_smooth[0 + i];
413 | bin = bin * 0.5 + (bin * bin) * 0.5;
414 | brightness_low += bin;
415 | }
416 | for (uint8_t i = 0; i < 20; i++) {
417 | SQ15x16 bin = spectrogram_smooth[20 + i];
418 | bin = bin * 0.5 + (bin * bin) * 0.5;
419 | brightness_mid += bin;
420 | }
421 | for (uint8_t i = 0; i < 20; i++) {
422 | SQ15x16 bin = spectrogram_smooth[40 + i];
423 | bin = bin * 0.5 + (bin * bin) * 0.5;
424 | brightness_high += bin;
425 | }
426 |
427 | brightness_low /= (SQ15x16)10.0;
428 | brightness_mid /= (SQ15x16)10.0;
429 | brightness_high /= (SQ15x16)10.0;
430 |
431 | if(brightness_low > 1.0){
432 | brightness_low = 1.0;
433 | }
434 | if(brightness_mid > 1.0){
435 | brightness_mid = 1.0;
436 | }
437 | if(brightness_high > 1.0){
438 | brightness_high = 1.0;
439 | }
440 |
441 | for(uint8_t i = 0; i < CONFIG.SQUARE_ITER; i++){
442 | brightness_low *= brightness_low;
443 | brightness_mid *= brightness_mid;
444 | brightness_high *= brightness_high;
445 | }
446 |
447 | CRGB16 col = { brightness_low, brightness_mid, brightness_high };
448 | leds_16[63] = col;
449 | */
450 |
451 | CRGB16 sum_color;
452 | SQ15x16 share = 1 / 6.0;
453 | for (uint8_t i = 0; i < 12; i++) {
454 | float prog = i / 12.0;
455 | SQ15x16 bin = chromagram_smooth[i];
456 | CRGB16 add_color = hsv(prog, CONFIG.SATURATION, bin*bin * share);
457 |
458 | sum_color.r += add_color.r;
459 | sum_color.g += add_color.g;
460 | sum_color.b += add_color.b;
461 | }
462 |
463 | if (sum_color.r > 1.0) { sum_color.r = 1.0; };
464 | if (sum_color.g > 1.0) { sum_color.g = 1.0; };
465 | if (sum_color.b > 1.0) { sum_color.b = 1.0; };
466 |
467 | for (uint8_t i = 0; i < CONFIG.SQUARE_ITER; i++) {
468 | sum_color.r *= sum_color.r;
469 | sum_color.g *= sum_color.g;
470 | sum_color.b *= sum_color.b;
471 | }
472 |
473 | CRGB temp_col = { uint8_t(sum_color.r * 255), uint8_t(sum_color.g * 255), uint8_t(sum_color.b * 255) };
474 | temp_col = force_saturation(temp_col, 255*CONFIG.SATURATION);
475 |
476 | if (chromatic_mode == false) {
477 | SQ15x16 led_hue = chroma_val + hue_position + (sqrt(float(1.0)) * SQ15x16(0.05));
478 | temp_col = force_hue(temp_col, 255*float(led_hue));
479 | }
480 |
481 | leds_16[63] = { temp_col.r / 255.0, temp_col.g / 255.0, temp_col.b / 255.0 };
482 | leds_16[64] = leds_16[63];
483 |
484 | //-------------------------------------------------------
485 |
486 | // Copy last frame to temp
487 | memcpy(leds_16_prev, leds_16, sizeof(CRGB16) * NATIVE_RESOLUTION);
488 |
489 | for(uint8_t i = 0; i < 32; i++){
490 | float prog = i / 31.0;
491 | leds_16[128-1-i].r *= (prog*prog);
492 | leds_16[128-1-i].g *= (prog*prog);
493 | leds_16[128-1-i].b *= (prog*prog);
494 | }
495 |
496 | for (uint8_t i = 0; i < 64; i++) {
497 | leds_16[i] = leds_16[128 - 1 - i];
498 | }
499 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/noise_cal.h:
--------------------------------------------------------------------------------
1 | extern void propagate_noise_reset();
2 |
3 | void start_noise_cal() {
4 | noise_complete = false;
5 | max_waveform_val = 0;
6 | max_waveform_val_raw = 0;
7 | noise_iterations = 0;
8 | dc_offset_sum = 0;
9 | CONFIG.DC_OFFSET = 0;
10 | CONFIG.VU_LEVEL_FLOOR = 0.0;
11 | CONFIG.SWEET_SPOT_MIN_LEVEL = 0;
12 | for (uint8_t i = 0; i < NUM_FREQS; i++) {
13 | noise_samples[i] = 0;
14 | }
15 | for (uint8_t i = 0; i < NATIVE_RESOLUTION; i++) {
16 | ui_mask[i] = 0;
17 | }
18 | USBSerial.println("STARTING NOISE CAL");
19 | }
20 |
21 | void clear_noise_cal() {
22 | propagate_noise_reset();
23 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
24 | noise_samples[i] = 0;
25 | }
26 | save_config();
27 | save_ambient_noise_calibration();
28 | USBSerial.println("NOISE CAL CLEARED");
29 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/p2p.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge P2P NETWORK FUNCTIONS
3 | ----------------------------------------*/
4 |
5 | // Fully documenting the P2P functions is a TODO for now.
6 | // Sorry!
7 |
8 | const uint8_t broadcast_address[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
9 | esp_now_peer_info_t broadcast_peer;
10 | bool flashing_flag = false;
11 |
12 | enum COMMAND_TYPES {
13 | COMMAND_NULL, // 0
14 | COMMAND_SYNC_SETTINGS, // 1
15 | COMMAND_TRIGGER_NOISE_CAL, // 2
16 | COMMAND_CLEAR_NOISE_CAL, // 3
17 | COMMAND_IDENTIFY_MAIN, // 4
18 | NUM_COMMAND_TYPES
19 | };
20 |
21 | struct SB_COMMAND_SYNC_SETTINGS {
22 | char ident[4] = { 'S', 'B', 'C', 0 };
23 | uint8_t command_type = COMMAND_SYNC_SETTINGS;
24 | float PHOTONS_KNOB;
25 | float CHROMA_KNOB;
26 | float MOOD_KNOB;
27 | uint8_t LIGHTSHOW_MODE;
28 | uint8_t MIRROR_ENABLED;
29 | uint8_t CHROMAGRAM_RANGE;
30 | };
31 |
32 | struct SB_COMMAND_TRIGGER_NOISE_CAL {
33 | char ident[4] = { 'S', 'B', 'C', 0 };
34 | uint8_t command_type = COMMAND_TRIGGER_NOISE_CAL;
35 | };
36 |
37 | struct SB_COMMAND_CLEAR_NOISE_CAL {
38 | char ident[4] = { 'S', 'B', 'C', 0 };
39 | uint8_t command_type = COMMAND_CLEAR_NOISE_CAL;
40 | };
41 |
42 | struct SB_COMMAND_IDENTIFY_MAIN {
43 | char ident[4] = { 'S', 'B', 'C', 0 };
44 | uint8_t command_type = COMMAND_IDENTIFY_MAIN;
45 | };
46 |
47 | void print_mac(const uint8_t *mac_addr) {
48 | USBSerial.print(mac_addr[0], HEX);
49 | USBSerial.print(':');
50 | USBSerial.print(mac_addr[1], HEX);
51 | USBSerial.print(':');
52 | USBSerial.print(mac_addr[2], HEX);
53 | USBSerial.print(':');
54 | USBSerial.print(mac_addr[3], HEX);
55 | USBSerial.print(':');
56 | USBSerial.print(mac_addr[4], HEX);
57 | USBSerial.print(':');
58 | USBSerial.print(mac_addr[5], HEX);
59 | }
60 |
61 | void sync_settings(uint32_t t_now) {
62 | SB_COMMAND_SYNC_SETTINGS setting;
63 |
64 | setting.PHOTONS_KNOB = CONFIG.PHOTONS;
65 | setting.CHROMA_KNOB = CONFIG.CHROMA;
66 | setting.MOOD_KNOB = CONFIG.MOOD;
67 | setting.LIGHTSHOW_MODE = CONFIG.LIGHTSHOW_MODE;
68 | setting.MIRROR_ENABLED = CONFIG.MIRROR_ENABLED;
69 | setting.CHROMAGRAM_RANGE = CONFIG.CHROMAGRAM_RANGE;
70 |
71 | const uint8_t *peer_addr = broadcast_peer.peer_addr;
72 | esp_now_send(peer_addr, (uint8_t *)&setting, sizeof(SB_COMMAND_SYNC_SETTINGS));
73 | }
74 |
75 | void identify_main_unit() {
76 | USBSerial.println("[IDENTIFY MAIN UNIT]");
77 | SB_COMMAND_IDENTIFY_MAIN identify;
78 |
79 | const uint8_t *peer_addr = broadcast_peer.peer_addr;
80 | for (uint8_t i = 0; i < 4; i++) {
81 | esp_now_send(peer_addr, (uint8_t *)&identify, sizeof(SB_COMMAND_IDENTIFY_MAIN));
82 | }
83 |
84 | CRGB16 col = {1.0, 0.0, 0.0};
85 | blocking_flash(col); // We aren't main unit, flash red
86 | }
87 |
88 | void propagate_noise_cal() {
89 | if (CONFIG.IS_MAIN_UNIT) {
90 | SB_COMMAND_TRIGGER_NOISE_CAL trigger;
91 | const uint8_t *peer_addr = broadcast_peer.peer_addr;
92 | for (uint8_t i = 0; i < 4; i++) {
93 | esp_now_send(peer_addr, (uint8_t *)&trigger, sizeof(SB_COMMAND_TRIGGER_NOISE_CAL));
94 | }
95 | }
96 | }
97 |
98 | void propagate_noise_reset() {
99 | if (CONFIG.IS_MAIN_UNIT) {
100 | SB_COMMAND_CLEAR_NOISE_CAL clear;
101 | const uint8_t *peer_addr = broadcast_peer.peer_addr;
102 | for (uint8_t i = 0; i < 4; i++) {
103 | esp_now_send(peer_addr, (uint8_t *)&clear, sizeof(SB_COMMAND_CLEAR_NOISE_CAL));
104 | }
105 | }
106 | }
107 |
108 | void on_data_tx(const uint8_t *mac_addr, esp_now_send_status_t status) {
109 | // nothing
110 | }
111 |
112 | void on_data_rx(const uint8_t *mac_addr, const uint8_t *incoming_data, int len) {
113 | //Serial.println("RX PACKET");
114 | main_override = false;
115 | last_rx_time = millis();
116 | char data_type[4];
117 | memcpy(data_type, incoming_data, 4);
118 |
119 | if (strcmp(data_type, "SBC") == 0) {
120 | uint8_t command_type = incoming_data[4];
121 |
122 | if (debug_mode) {
123 | USBSerial.print("RX COMMAND OF TYPE ");
124 | USBSerial.print(command_type);
125 | USBSerial.print(" FROM ");
126 | print_mac(mac_addr);
127 | USBSerial.println();
128 | }
129 |
130 | if (command_type == COMMAND_SYNC_SETTINGS) {
131 | if (CONFIG.IS_MAIN_UNIT == false) {
132 | SB_COMMAND_SYNC_SETTINGS settings;
133 | memcpy(&settings, incoming_data, sizeof(SB_COMMAND_SYNC_SETTINGS));
134 |
135 | CONFIG.PHOTONS = settings.PHOTONS_KNOB;
136 | CONFIG.CHROMA = settings.CHROMA_KNOB;
137 | CONFIG.MOOD = settings.MOOD_KNOB;
138 | CONFIG.LIGHTSHOW_MODE = settings.LIGHTSHOW_MODE;
139 | CONFIG.MIRROR_ENABLED = settings.MIRROR_ENABLED;
140 | CONFIG.CHROMAGRAM_RANGE = settings.CHROMAGRAM_RANGE;
141 | }
142 | } else if (command_type == COMMAND_TRIGGER_NOISE_CAL) {
143 | if (CONFIG.IS_MAIN_UNIT == false) {
144 | if (noise_complete == true) {
145 | noise_complete = false;
146 | start_noise_cal();
147 | }
148 | }
149 | } else if (command_type == COMMAND_CLEAR_NOISE_CAL) {
150 | if (CONFIG.IS_MAIN_UNIT == false) {
151 | if (noise_complete == true) {
152 | clear_noise_cal();
153 | }
154 | }
155 | } else if (command_type == COMMAND_IDENTIFY_MAIN) { // MAIN UNIT ACCEPTS THIS COMMAND FROM OTHERS
156 | if (CONFIG.IS_MAIN_UNIT) {
157 | flashing_flag = true;
158 | }
159 | }
160 | }
161 | else {
162 | if (debug_mode) {
163 | USBSerial.print("UNKNOWN PACKET:");
164 | USBSerial.println(data_type);
165 | }
166 | }
167 | }
168 |
169 | void init_p2p() {
170 | WiFi.mode(WIFI_MODE_STA);
171 |
172 | USBSerial.print("ESP-NOW INIT: ");
173 | USBSerial.println(esp_err_to_name(esp_now_init()));
174 |
175 | esp_now_register_send_cb(on_data_tx);
176 | esp_now_register_recv_cb(on_data_rx);
177 |
178 | memset(&broadcast_peer, 0, sizeof(broadcast_peer));
179 | memcpy(broadcast_peer.peer_addr, broadcast_address, 6);
180 | broadcast_peer.channel = 0; // TODO - avoid broadcast mode to allow for other WIFI channels (Promiscuous only works on channel 0)
181 | broadcast_peer.encrypt = false;
182 |
183 | USBSerial.print("ESP-NOW ADD BROADCAST PEER: ");
184 | USBSerial.println(esp_err_to_name(esp_now_add_peer(&broadcast_peer)));
185 | }
186 |
187 | void run_p2p() {
188 | uint32_t t_now = millis();
189 |
190 | if (t_now - last_rx_time >= 1000) {
191 | main_override = true;
192 | }
193 |
194 | if (CONFIG.IS_MAIN_UNIT) {
195 | sync_settings(t_now);
196 | }
197 |
198 | if (flashing_flag) {
199 | flashing_flag = false;
200 | CRGB16 col = {0.0, 1.0, 0.0};
201 | blocking_flash(col);
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/presets.h:
--------------------------------------------------------------------------------
1 | void set_preset(char* preset_name) {
2 | // Modifies current CONFIG struct based on input preset name
3 |
4 | if (strcmp(preset_name, "default") == 0) {
5 | CONFIG.SQUARE_ITER = 1;
6 | CONFIG.INCANDESCENT_FILTER = 0.80;
7 | CONFIG.INCANDESCENT_MODE = false;
8 | CONFIG.BASE_COAT = true;
9 | CONFIG.BULB_OPACITY = 0.0;
10 | CONFIG.SATURATION = 1.0;
11 | }
12 |
13 | else if (strcmp(preset_name, "tinted_bulbs") == 0) {
14 | CONFIG.SQUARE_ITER = 1;
15 | CONFIG.INCANDESCENT_FILTER = 0.80;
16 | CONFIG.INCANDESCENT_MODE = false;
17 | CONFIG.BASE_COAT = false;
18 | CONFIG.BULB_OPACITY = 1.0;
19 | CONFIG.SATURATION = 1.0;
20 | }
21 |
22 | else if (strcmp(preset_name, "incandescent") == 0) {
23 | CONFIG.SQUARE_ITER = 1;
24 | CONFIG.INCANDESCENT_FILTER = 1.0;
25 | CONFIG.INCANDESCENT_MODE = true;
26 | CONFIG.BASE_COAT = true;
27 | CONFIG.BULB_OPACITY = 0.0;
28 | CONFIG.SATURATION = 1.0;
29 | }
30 |
31 | else if (strcmp(preset_name, "white") == 0) {
32 | CONFIG.SQUARE_ITER = 1;
33 | CONFIG.INCANDESCENT_FILTER = 0;
34 | CONFIG.INCANDESCENT_MODE = false;
35 | CONFIG.BASE_COAT = true;
36 | CONFIG.BULB_OPACITY = 0.0;
37 | CONFIG.SATURATION = 0.0;
38 | }
39 |
40 | else if (strcmp(preset_name, "classic") == 0) {
41 | CONFIG.SQUARE_ITER = 1;
42 | CONFIG.INCANDESCENT_FILTER = 0.0;
43 | CONFIG.INCANDESCENT_MODE = false;
44 | CONFIG.BASE_COAT = false;
45 | CONFIG.BULB_OPACITY = 0.0;
46 | CONFIG.SATURATION = 1.0;
47 | }
48 | }
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/strings.h:
--------------------------------------------------------------------------------
1 | #define PASS "PASS"
2 | #define FAIL "FAIL ###################"
3 |
4 | char notes_chromatic[12] = { 'A','A','B','C','C','D','D','E','F','F','G','G' };
5 | char sharps[12] = { ' ','#',' ',' ','#',' ','#',' ',' ','#',' ','#' };
6 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/system.h:
--------------------------------------------------------------------------------
1 | uint32_t timing_start = 0;
2 | extern void run_sweet_spot();
3 | extern void show_leds();
4 |
5 | void reboot() {
6 | lock_leds();
7 | USBSerial.println("--- ! REBOOTING to apply changes (You may need to restart the Serial Monitor)");
8 | USBSerial.flush();
9 | for(float i = 1.0; i >= 0.0; i-=0.05){
10 | MASTER_BRIGHTNESS = i;
11 | run_sweet_spot();
12 | show_leds();
13 | FastLED.delay(12); // Takes ~250ms total
14 | }
15 | FastLED.setBrightness(0);
16 | FastLED.show();
17 | ESP.restart();
18 | }
19 |
20 | void start_timing(char* func_name) {
21 | USBSerial.print(func_name);
22 | USBSerial.print(": ");
23 | USBSerial.flush();
24 | timing_start = micros();
25 | }
26 |
27 | void end_timing() {
28 | uint32_t timing_end = micros();
29 | uint32_t t_delta = timing_end - timing_start;
30 |
31 | USBSerial.print("DONE IN ");
32 | USBSerial.print(t_delta / 1000.0, 3);
33 | USBSerial.println(" MS");
34 | }
35 |
36 | void check_current_function() {
37 | function_hits[function_id]++;
38 | }
39 |
40 | static void usb_event_callback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
41 | if (event_base == ARDUINO_USB_EVENTS) {
42 | //arduino_usb_event_data_t * data = (arduino_usb_event_data_t*)event_data;
43 | switch (event_id) {
44 | case ARDUINO_USB_STARTED_EVENT:
45 | //Serial0.println("USB PLUGGED");
46 | break;
47 | case ARDUINO_USB_STOPPED_EVENT:
48 | //Serial0.println("USB UNPLUGGED");
49 | break;
50 | case ARDUINO_USB_SUSPEND_EVENT:
51 | //Serial0.printf("USB SUSPENDED: remote_wakeup_en: %u\n", data->suspend.remote_wakeup_en);
52 | break;
53 | case ARDUINO_USB_RESUME_EVENT:
54 | //Serial0.println("USB RESUMED");
55 | break;
56 |
57 | default:
58 | break;
59 | }
60 | } else if (event_base == ARDUINO_FIRMWARE_MSC_EVENTS) {
61 | //arduino_firmware_msc_event_data_t * data = (arduino_firmware_msc_event_data_t*)event_data;
62 | switch (event_id) {
63 | case ARDUINO_FIRMWARE_MSC_START_EVENT:
64 | //Serial0.println("MSC Update Start");
65 | msc_update_started = true;
66 | break;
67 | case ARDUINO_FIRMWARE_MSC_WRITE_EVENT:
68 | //HWSerial.printf("MSC Update Write %u bytes at offset %u\n", data->write.size, data->write.offset);
69 | //Serial0.print(".");
70 | break;
71 | case ARDUINO_FIRMWARE_MSC_END_EVENT:
72 | //Serial0.printf("\nMSC Update End: %u bytes\n", data->end.size);
73 | break;
74 | case ARDUINO_FIRMWARE_MSC_ERROR_EVENT:
75 | //Serial0.printf("MSC Update ERROR! Progress: %u bytes\n", data->error.size);
76 | break;
77 | case ARDUINO_FIRMWARE_MSC_POWER_EVENT:
78 | //Serial0.printf("MSC Update Power: power: %u, start: %u, eject: %u", data->power.power_condition, data->power.start, data->power.load_eject);
79 | break;
80 |
81 | default:
82 | break;
83 | }
84 | }
85 | }
86 |
87 | void enable_usb_update_mode() {
88 | USB.onEvent(usb_event_callback);
89 |
90 | MSC_Update.onEvent(usb_event_callback);
91 | MSC_Update.begin();
92 |
93 | MASTER_BRIGHTNESS = 1.0;
94 |
95 | uint8_t led_index = 0;
96 | uint8_t sweet_index = 0;
97 |
98 | const uint8_t sweet_order[3][3] = {
99 | {1, 0, 0},
100 | {0, 1, 0},
101 | {0, 0, 1}
102 | };
103 |
104 | while (true) {
105 | for (uint8_t i = 0; i < NATIVE_RESOLUTION; i++) {
106 | leds_16[i] = {0, 0, 0};
107 | }
108 |
109 | if (msc_update_started == false) {
110 | leds_16[led_index] = {0, 0, 0.25};
111 | ledcWrite(SWEET_SPOT_LEFT_CHANNEL, sweet_order[sweet_index][0] * 512);
112 | ledcWrite(SWEET_SPOT_CENTER_CHANNEL, sweet_order[sweet_index][1] * 512);
113 | ledcWrite(SWEET_SPOT_RIGHT_CHANNEL, sweet_order[sweet_index][2] * 512);
114 | }
115 | else {
116 | leds_16[NATIVE_RESOLUTION-1-led_index] = {0, 0.25, 0};
117 | ledcWrite(SWEET_SPOT_LEFT_CHANNEL, sweet_order[sweet_index][2] * 4095);
118 | ledcWrite(SWEET_SPOT_CENTER_CHANNEL, sweet_order[sweet_index][1] * 4095);
119 | ledcWrite(SWEET_SPOT_RIGHT_CHANNEL, sweet_order[sweet_index][0] * 4095);
120 | }
121 |
122 |
123 | show_leds();
124 |
125 | if(led_index == 0 || led_index == NATIVE_RESOLUTION/2){
126 | sweet_index++;
127 | if (sweet_index >= 3) {
128 | sweet_index = 0;
129 | }
130 | }
131 |
132 | led_index++;
133 | if (led_index >= NATIVE_RESOLUTION) {
134 | led_index = 0;
135 | }
136 | yield();
137 | }
138 | }
139 |
140 | void init_usb() {
141 | USB.productName("Sensory Bridge"); // Doesn't work, not my fault
142 | USB.manufacturerName("Lixie Labs"); // Doesn't work, not my fault
143 | USB.VID(0x1209); // This works though, god damn I hate USB
144 | USB.PID(0xABED); // Cool, cool cool cool https://pid.codes/1209/ABED/
145 |
146 | USB.begin();
147 | USBSerial.begin();
148 | }
149 |
150 | void init_sweet_spot() {
151 | ledcSetup(SWEET_SPOT_LEFT_CHANNEL, 500, 12);
152 | ledcAttachPin(SWEET_SPOT_LEFT_PIN, SWEET_SPOT_LEFT_CHANNEL);
153 |
154 | ledcSetup(SWEET_SPOT_CENTER_CHANNEL, 500, 12);
155 | ledcAttachPin(SWEET_SPOT_CENTER_PIN, SWEET_SPOT_CENTER_CHANNEL);
156 |
157 | ledcSetup(SWEET_SPOT_RIGHT_CHANNEL, 500, 12);
158 | ledcAttachPin(SWEET_SPOT_RIGHT_PIN, SWEET_SPOT_RIGHT_CHANNEL);
159 | }
160 |
161 | void generate_a_weights() {
162 | start_timing("GENERATING A-WEIGHTS");
163 | for (uint8_t i = 0; i < 13; i++) {
164 | float decibels = a_weight_table[i][1];
165 | float bels = decibels / 10.0;
166 | float ratio = pow(10, bels);
167 | a_weight_table[i][1] = ratio;
168 | }
169 |
170 | for (uint8_t i = 0; i < NUM_FREQS; i++) {
171 | float frequency = notes[i];
172 | uint8_t low_index = 0;
173 | uint8_t high_index = 0;
174 | for (uint8_t x = 0; x < 13; x++) {
175 | float table_freq = a_weight_table[x][0];
176 | if (frequency >= table_freq) {
177 | low_index = x;
178 | high_index = x + 1;
179 | }
180 | }
181 |
182 | float low_freq = a_weight_table[low_index][0];
183 | float high_freq = a_weight_table[high_index][0];
184 |
185 | float freq_position = (frequency - low_freq) / (high_freq - low_freq);
186 |
187 | float interpolated_weight = (a_weight_table[low_index][1] * (1.0 - freq_position)) + (a_weight_table[high_index][1] * (freq_position));
188 |
189 | frequencies[i].a_weighting_ratio = interpolated_weight;
190 | if (frequencies[i].a_weighting_ratio > 1.0) {
191 | frequencies[i].a_weighting_ratio = 1.0;
192 | }
193 | }
194 | end_timing();
195 | }
196 |
197 | void generate_window_lookup() {
198 | start_timing("GENERATING HANN WINDOW LOOKUP TABLE");
199 | for (uint16_t i = 0; i < 2048; i++) {
200 | float ratio = i / 4095.0;
201 | float weighing_factor = 0.54 * (1.0 - cos(TWOPI * ratio));
202 |
203 | window_lookup[i] = 32767 * weighing_factor;
204 | window_lookup[4095 - i] = 32767 * weighing_factor;
205 | }
206 | end_timing();
207 | }
208 |
209 | void precompute_goertzel_constants() {
210 | for (uint16_t i = 0; i < NUM_FREQS; i++) {
211 | int16_t n = i;
212 | frequencies[i].target_freq = notes[n + CONFIG.NOTE_OFFSET];
213 |
214 | float neighbor_left;
215 | float neighbor_right;
216 |
217 | if (i == 0) {
218 | neighbor_left = notes[n + CONFIG.NOTE_OFFSET];
219 | neighbor_right = notes[n + CONFIG.NOTE_OFFSET + 1];
220 | } else if (i == NUM_FREQS - 1) {
221 | neighbor_left = notes[n + CONFIG.NOTE_OFFSET - 1];
222 | neighbor_right = notes[n + CONFIG.NOTE_OFFSET];
223 | } else {
224 | neighbor_left = notes[n + CONFIG.NOTE_OFFSET - 1];
225 | neighbor_right = notes[n + CONFIG.NOTE_OFFSET + 1];
226 | }
227 |
228 | float neighbor_left_distance_hz = fabs(neighbor_left - frequencies[i].target_freq);
229 | float neighbor_right_distance_hz = fabs(neighbor_right - frequencies[i].target_freq);
230 | float max_distance_hz = 0;
231 | if (neighbor_left_distance_hz > max_distance_hz) {
232 | max_distance_hz = neighbor_left_distance_hz;
233 | }
234 | if (neighbor_right_distance_hz > max_distance_hz) {
235 | max_distance_hz = neighbor_right_distance_hz;
236 | }
237 |
238 | frequencies[i].block_size = CONFIG.SAMPLE_RATE / (max_distance_hz * 2.0);
239 |
240 | if(frequencies[i].block_size > 2000){
241 | frequencies[i].block_size = 2000;
242 | }
243 |
244 | frequencies[i].block_size_recip = 1.0 / float(frequencies[i].block_size);
245 |
246 | float k = (int)(0.5 + ((frequencies[i].block_size * frequencies[i].target_freq) / CONFIG.SAMPLE_RATE));
247 | float w = (2.0 * PI * k) / frequencies[i].block_size;
248 | float cosine = cos(w);
249 | float sine = sin(w);
250 | float coeff = 2.0 * cosine;
251 | frequencies[i].coeff_q14 = (1 << 14) * coeff;
252 |
253 | frequencies[i].window_mult = 4096.0 / frequencies[i].block_size;
254 | frequencies[i].zone = (i / float(NUM_FREQS)) * NUM_ZONES;
255 | }
256 | }
257 |
258 | void debug_function_timing(uint32_t t_now) {
259 | static uint32_t last_timing_print = t_now;
260 |
261 | if (t_now - last_timing_print >= 30000) {
262 | USBSerial.println("------------");
263 | for (uint8_t i = 0; i < 16; i++) {
264 | USBSerial.print(i);
265 | USBSerial.print(": ");
266 | USBSerial.println(function_hits[i]);
267 |
268 | function_hits[i] = 0;
269 | }
270 |
271 | last_timing_print = t_now;
272 | }
273 | }
274 |
275 | void set_mode_name(uint16_t index, char* mode_name) {
276 | uint8_t len = strlen(mode_name);
277 | for (uint8_t i = 0; i < len; i++) {
278 | mode_names[32 * index + i] = mode_name[i];
279 | }
280 | }
281 |
282 | void init_system() {
283 | noise_button.pin = NOISE_CAL_PIN;
284 | mode_button.pin = MODE_PIN;
285 |
286 | pinMode(noise_button.pin, INPUT_PULLUP);
287 | pinMode(mode_button.pin, INPUT_PULLUP);
288 |
289 | memcpy(&CONFIG_DEFAULTS, &CONFIG, sizeof(CONFIG)); // Copy defaults values to second CONFIG object
290 |
291 | set_mode_name(0, "GDFT");
292 | set_mode_name(1, "CHROMAGRAM");
293 | set_mode_name(2, "BLOOM");
294 | set_mode_name(3, "BLOOM (FAST)");
295 | set_mode_name(4, "VU");
296 | set_mode_name(5, "VU (DOT)");
297 |
298 | init_serial(SERIAL_BAUD);
299 | init_sweet_spot();
300 |
301 | init_fs();
302 |
303 | // NOISE and MODE held down on boot
304 | if (digitalRead(noise_button.pin) == LOW && digitalRead(mode_button.pin) == LOW) {
305 | restore_defaults();
306 | }
307 |
308 | init_leds();
309 | init_usb();
310 |
311 | // MODE held down on boot
312 | if (digitalRead(mode_button.pin) == LOW) {
313 | enable_usb_update_mode();
314 | }
315 |
316 | init_i2s();
317 | init_p2p();
318 | generate_a_weights();
319 | generate_window_lookup();
320 | precompute_goertzel_constants();
321 |
322 | USBSerial.println("SYSTEM INIT COMPLETE!");
323 |
324 | if (CONFIG.BOOT_ANIMATION == true) {
325 | intro_animation();
326 | }
327 | }
328 |
329 | void log_fps(uint32_t t_now_us) {
330 | static uint32_t t_last = t_now_us;
331 | static float fps_history[10] = {0};
332 | static uint8_t fps_history_index = 0;
333 |
334 | uint32_t frame_delta_us = t_now_us - t_last;
335 | float fps_now = 1000000.0 / float(frame_delta_us);
336 |
337 | fps_history[fps_history_index] = fps_now;
338 |
339 | fps_history_index++;
340 | if (fps_history_index >= 10) {
341 | fps_history_index = 0;
342 | }
343 |
344 | float fps_sum = 0;
345 | for (uint8_t i = 0; i < 10; i++) {
346 | fps_sum += fps_history[i];
347 | }
348 |
349 | SYSTEM_FPS = fps_sum / 10.0;
350 |
351 | if (stream_fps == true) {
352 | USBSerial.print("sbs((fps=");
353 | USBSerial.print(SYSTEM_FPS);
354 | USBSerial.println("))");
355 | }
356 |
357 | t_last = t_now_us;
358 | }
359 |
360 | // This is to prevent overuse of internal flash writes!
361 | // Instead of writing every single setting change to
362 | // LittleFS, we wait until no settings have been altered
363 | // for more than 3 seconds before attempting to update
364 | // the flash with changes. This helps in scenarios where
365 | // you're rapidly cycling through modes for example.
366 | void check_settings(uint32_t t_now) {
367 | if (settings_updated) {
368 | if (t_now >= next_save_time) {
369 | if(debug_mode == true){
370 | USBSerial.println("QUEUED CONFIG SAVE TRIGGERED");
371 | }
372 | save_config();
373 | settings_updated = false;
374 | }
375 | }
376 | }
377 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/user_config.h:
--------------------------------------------------------------------------------
1 | /*----------------------------------------
2 | Sensory Bridge HARDWARE CONFIGURATION
3 | ----------------------------------------*/
4 |
5 | // Every notable setting about hardware moved to the settings.sensorybridge.rocks site for now!
6 | // No more hardcoding values for strip length and such
7 |
8 | /*----------------------------------------
9 | Sensory Bridge SOFTWARE CONFIGURATION
10 | ----------------------------------------*/
11 |
12 | // TODO: CRGBPalette16/lookups in place of all CHSV usage, which defaults
13 | // to a rainbow but can be swapped with several pre-made themes by
14 | // commenting/uncommenting one here or selecting via the UART menu
15 |
--------------------------------------------------------------------------------
/SENSORY_BRIDGE_FIRMWARE/utilities.h:
--------------------------------------------------------------------------------
1 | // Can return a value between two array indices with linear interpolation
2 | SQ15x16 IRAM_ATTR interpolate(SQ15x16 index, SQ15x16* array, uint16_t array_size) {
3 | SQ15x16 index_f = index * (array_size - 1);
4 | uint16_t index_i = (uint16_t)index_f;
5 | SQ15x16 index_f_frac = index_f - index_i;
6 |
7 | SQ15x16 left_val = array[index_i];
8 | SQ15x16 right_val = array[index_i + 1];
9 |
10 | if (index_i + 1 >= array_size) {
11 | right_val = left_val;
12 | }
13 |
14 | return (1 - index_f_frac) * left_val + index_f_frac * right_val;
15 | }
16 |
17 | // Convert and array of 4 bytes to a zero-padded hex string (9 chars to include null terminator)
18 | void bytes_to_hex_string(const byte bytes[4], char hex_string[9]) {
19 | snprintf(hex_string, 9, "%02X%02X%02X%02X", bytes[0], bytes[1], bytes[2], bytes[3]);
20 | }
21 |
22 | void print_chip_id() {
23 | for (int i = 0; i < 17; i += 8) {
24 | chip_id |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
25 | }
26 |
27 | char hex_string[9]; // ... Create a char array to store the hex string
28 | bytes_32 b; // ........... Create a bytes_32 struct to hold the bytes of chip_id_high
29 |
30 | b.long_val = chip_id; // ....................... Assign chip_id_low to the long_val member of the struct
31 | bytes_to_hex_string(b.bytes, hex_string); // ... Convert the bytes of chip_id_low to a zero-padded hex string
32 | USBSerial.print(hex_string); // ................ Print the hex string to the serial port
33 |
34 | USBSerial.println(); // Print a newline character
35 | }
36 |
37 | void blur_array(float* input, int length, int kernel_size) {
38 | int padding = kernel_size / 2;
39 | for (int i = 0; i < length; i++) {
40 | float sum = 0.0f;
41 | for (int j = -padding; j <= padding; j++) {
42 | int k = i + j;
43 | if (k < 0) k = 0;
44 | if (k >= length) k = length - 1;
45 | sum += input[k];
46 | }
47 | input[i] = sum / (float)kernel_size;
48 | }
49 | }
50 |
51 | float low_pass_filter(float new_data, float last_data, uint32_t sample_rate, float cutoff_freq) {
52 | float alpha = 1.0 - expf(-2.0 * PI * cutoff_freq / sample_rate);
53 | float output = (1.0 - alpha) * (last_data) + alpha * new_data;
54 | return output;
55 | }
56 |
57 | void low_pass_array(float* new_frame, float* last_frame, uint16_t length, uint32_t sample_rate, float cutoff_freq){
58 | for(uint16_t i = 0; i < length; i++){
59 | new_frame[i] = low_pass_filter(new_frame[i], last_frame[i], sample_rate, cutoff_freq);
60 | }
61 | }
62 |
63 | SQ15x16 low_pass_filter_fixed(SQ15x16 new_data, SQ15x16 last_data, uint32_t sample_rate, float cutoff_freq) {
64 | SQ15x16 alpha = 1.0 - expf(-2.0 * PI * cutoff_freq / sample_rate);
65 | SQ15x16 output = SQ15x16(1.0 - alpha) * (last_data) + alpha * new_data;
66 | return output;
67 | }
68 |
69 | void low_pass_array_fixed(SQ15x16* new_frame, SQ15x16* last_frame, uint16_t length, uint32_t sample_rate, float cutoff_freq){
70 | for(uint16_t i = 0; i < length; i++){
71 | new_frame[i] = low_pass_filter_fixed(new_frame[i], last_frame[i], sample_rate, cutoff_freq);
72 | }
73 | }
74 |
75 | float random_float(){
76 | return esp_random() / (float)UINT32_MAX;
77 | }
78 |
79 | SQ15x16 mood_scale(SQ15x16 center, SQ15x16 range){
80 | SQ15x16 knob_value_bidirectional = (CONFIG.MOOD - 0.5) * SQ15x16(2.0); // 0.0 - 1.0 range transformed to -1.0 to +1.0
81 | SQ15x16 result = center + range*knob_value_bidirectional;
82 |
83 | return result;
84 | }
85 |
86 | SQ15x16 fabs_fixed(SQ15x16 input){
87 | if(input < SQ15x16(0.0)){
88 | input *= SQ15x16(-1.0);
89 | }
90 |
91 | return input;
92 | }
93 |
94 | SQ15x16 fmin_fixed(SQ15x16 a, SQ15x16 b) {
95 | return (a < b) ? a : b;
96 | }
97 |
98 | SQ15x16 fmax_fixed(SQ15x16 a, SQ15x16 b) {
99 | return (a > b) ? a : b;
100 | }
101 |
102 | SQ15x16 fmod_fixed(SQ15x16 dividend, SQ15x16 divisor) {
103 | SQ15x16 quotient = dividend / divisor;
104 | return dividend - (divisor * floorFixed(quotient));
105 | }
106 |
107 | float clip_float(float input){
108 | return min(1.0f, max(0.0f, input));
109 | }
--------------------------------------------------------------------------------
/extras/OSHW/3D Printing/MINI_MAST_MOUNT.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/OSHW/3D Printing/MINI_MAST_MOUNT.stl
--------------------------------------------------------------------------------
/extras/OSHW/3D Printing/SENSORY_BRIDGE_BASE.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/OSHW/3D Printing/SENSORY_BRIDGE_BASE.stl
--------------------------------------------------------------------------------
/extras/img/0.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/0.jpg
--------------------------------------------------------------------------------
/extras/img/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/1.jpg
--------------------------------------------------------------------------------
/extras/img/10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/10.jpg
--------------------------------------------------------------------------------
/extras/img/11.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/11.jpg
--------------------------------------------------------------------------------
/extras/img/12.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/12.jpg
--------------------------------------------------------------------------------
/extras/img/13.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/13.jpg
--------------------------------------------------------------------------------
/extras/img/14.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/14.jpg
--------------------------------------------------------------------------------
/extras/img/15.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/15.jpg
--------------------------------------------------------------------------------
/extras/img/16.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/16.jpg
--------------------------------------------------------------------------------
/extras/img/17.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/17.png
--------------------------------------------------------------------------------
/extras/img/2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/2.jpg
--------------------------------------------------------------------------------
/extras/img/3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/3.jpg
--------------------------------------------------------------------------------
/extras/img/4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/4.jpg
--------------------------------------------------------------------------------
/extras/img/5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/5.jpg
--------------------------------------------------------------------------------
/extras/img/6.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/6.jpg
--------------------------------------------------------------------------------
/extras/img/7.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/7.jpg
--------------------------------------------------------------------------------
/extras/img/8.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/8.jpg
--------------------------------------------------------------------------------
/extras/img/9.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/9.jpg
--------------------------------------------------------------------------------
/extras/img/app_icon.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/app_icon.jpg
--------------------------------------------------------------------------------
/extras/img/firmware_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/firmware_settings.png
--------------------------------------------------------------------------------
/extras/img/firmware_settings_300.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/firmware_settings_300.png
--------------------------------------------------------------------------------
/extras/img/get_you.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/get_you.jpg
--------------------------------------------------------------------------------
/extras/img/nina.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/nina.jpg
--------------------------------------------------------------------------------
/extras/img/on_the_run.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/on_the_run.jpg
--------------------------------------------------------------------------------
/extras/img/oshw_facts.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/extras/img/plantasia.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/plantasia.jpg
--------------------------------------------------------------------------------
/extras/img/street_by_street.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/street_by_street.jpg
--------------------------------------------------------------------------------
/extras/img/trustful_hands.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/connornishijima/SensoryBridge/5f329261987144242be4c3729f6d344631d3be1e/extras/img/trustful_hands.jpg
--------------------------------------------------------------------------------
/extras/misc/audio_transfer.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Audio Transfer Testing
4 |
5 |
80 |
81 |
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/extras/misc/bpm.h:
--------------------------------------------------------------------------------
1 | void autocorrelate_bpm(){
2 | static float us_per_frame = 1000000.0 / FPS;
3 | static float last_bpm = 0;
4 |
5 | uint32_t t_start = micros();
6 |
7 | float max_corr = 0;
8 | uint16_t offset_frames = 0;
9 | bool falling = true;
10 | float last_corr = 240;
11 |
12 | for(uint16_t offset = 0; offset < 240; offset+=1){
13 | float corr_sum = 0.0;
14 | for(uint16_t index = 0; index < 120; index+=1){
15 | float envelope = fft_vel_sum_history[index] * fft_vel_sum_history[index];
16 | float vel_sum_corr = (1.0 - fabs(fft_vel_sum_history[index] - fft_vel_sum_history[index+offset])) * envelope;
17 | corr_sum += vel_sum_corr;
18 | }
19 |
20 | if(falling == false){
21 | if(corr_sum > max_corr){
22 | max_corr = corr_sum;
23 | offset_frames = offset;
24 | }
25 | }
26 | else{
27 | if(corr_sum > last_corr){
28 | falling = false;
29 | }
30 | last_corr = corr_sum;
31 | }
32 | }
33 |
34 | float offset_us = offset_frames*us_per_frame;
35 | float hz = 1000000.0 / offset_us;
36 | float bpm = hz*60;
37 |
38 | while(bpm < 90.0){
39 | bpm = bpm * 2.0;
40 | }
41 |
42 | while(bpm > 180.0){
43 | bpm = bpm / 2.0;
44 | }
45 |
46 | if(last_bpm == 0){
47 | last_bpm = bpm;
48 | }
49 |
50 | /*
51 | if(fabs((bpm / 2) - last_bpm) <= 5.0){
52 | bpm = last_bpm;
53 | }
54 | else if(fabs((bpm * 2) - last_bpm) <= 5.0){
55 | bpm = last_bpm;
56 | }
57 | else if(fabs((bpm * 1.33) - last_bpm) <= 5.0){
58 | bpm = last_bpm;
59 | }
60 | else if(fabs((bpm * 0.75) - last_bpm) <= 5.0){
61 | //bpm = last_bpm;
62 | }
63 | */
64 |
65 | last_bpm = bpm;
66 |
67 | uint32_t t_end = micros();
68 |
69 | Serial.print("0\t250\t");
70 | Serial.print(FPS);
71 | Serial.print("\t");
72 | Serial.print(t_end-t_start);
73 | Serial.print("\t");
74 | Serial.println(bpm);
75 | tempo_animation_frame_cap_target = (FPS / float(bpm/60.0))*4;
76 | }
77 |
--------------------------------------------------------------------------------
/extras/misc/fft_fixed.h:
--------------------------------------------------------------------------------
1 | #define N_WAVE 256 /* full length of Sinewave[] */
2 | #define LOG2_N_WAVE 8 /* log2(N_WAVE) */
3 |
4 | /*
5 | Since we only use 3/4 of N_WAVE, we define only
6 | this many samples, in order to conserve data space.
7 | */
8 |
9 | const int8_t Sinewave[N_WAVE-N_WAVE/4] = {
10 | 0, 3, 6, 9, 12, 15, 18, 21,
11 | 24, 28, 31, 34, 37, 40, 43, 46,
12 | 48, 51, 54, 57, 60, 63, 65, 68,
13 | 71, 73, 76, 78, 81, 83, 85, 88,
14 | 90, 92, 94, 96, 98, 100, 102, 104,
15 | 106, 108, 109, 111, 112, 114, 115, 117,
16 | 118, 119, 120, 121, 122, 123, 124, 124,
17 | 125, 126, 126, 127, 127, 127, 127, 127,
18 |
19 | 127, 127, 127, 127, 127, 127, 126, 126,
20 | 125, 124, 124, 123, 122, 121, 120, 119,
21 | 118, 117, 115, 114, 112, 111, 109, 108,
22 | 106, 104, 102, 100, 98, 96, 94, 92,
23 | 90, 88, 85, 83, 81, 78, 76, 73,
24 | 71, 68, 65, 63, 60, 57, 54, 51,
25 | 48, 46, 43, 40, 37, 34, 31, 28,
26 | 24, 21, 18, 15, 12, 9, 6, 3,
27 |
28 | 0, -3, -6, -9, -12, -15, -18, -21,
29 | -24, -28, -31, -34, -37, -40, -43, -46,
30 | -48, -51, -54, -57, -60, -63, -65, -68,
31 | -71, -73, -76, -78, -81, -83, -85, -88,
32 | -90, -92, -94, -96, -98, -100, -102, -104,
33 | -106, -108, -109, -111, -112, -114, -115, -117,
34 | -118, -119, -120, -121, -122, -123, -124, -124,
35 | -125, -126, -126, -127, -127, -127, -127, -127,
36 |
37 | /*-127, -127, -127, -127, -127, -127, -126, -126,
38 | -125, -124, -124, -123, -122, -121, -120, -119,
39 | -118, -117, -115, -114, -112, -111, -109, -108,
40 | -106, -104, -102, -100, -98, -96, -94, -92,
41 | -90, -88, -85, -83, -81, -78, -76, -73,
42 | -71, -68, -65, -63, -60, -57, -54, -51,
43 | -48, -46, -43, -40, -37, -34, -31, -28,
44 | -24, -21, -18, -15, -12, -9, -6, -3, */
45 | };
46 |
47 | int8_t FIX_MPY(int8_t a, int8_t b){
48 |
49 | //Serial.println(a);
50 | //Serial.println(b);
51 |
52 |
53 | /* shift right one less bit (i.e. 15-1) */
54 | int16_t c = ((int16_t)a * (int16_t)b) >> 6;
55 | /* last bit shifted out = rounding-bit */
56 | b = c & 0x01;
57 | /* last shift + rounding bit */
58 | a = (c >> 1) + b;
59 |
60 | /*
61 | Serial.println(Sinewave[3]);
62 | Serial.println(c);
63 | Serial.println(a);
64 | while(1);*/
65 |
66 | return a;
67 | }
68 |
69 | /*
70 | fix_fft() - perform forward/inverse fast Fourier transform.
71 | fr[n],fi[n] are real and imaginary arrays, both INPUT AND
72 | RESULT (in-place FFT), with 0 <= n < 2**m; set inverse to
73 | 0 for forward transform (FFT), or 1 for iFFT.
74 | */
75 | int16_t fix_fft(int8_t fr[], int8_t fi[], int16_t m, int16_t inverse)
76 | {
77 | int16_t mr, nn, i, j, l, k, istep, n, scale, shift;
78 | int8_t qr, qi, tr, ti, wr, wi;
79 |
80 | n = 1 << m;
81 |
82 | /* max FFT size = N_WAVE */
83 | if (n > N_WAVE)
84 | return -1;
85 |
86 | mr = 0;
87 | nn = n - 1;
88 | scale = 0;
89 |
90 | /* decimation in time - re-order data */
91 | for (m=1; m<=nn; ++m) {
92 | l = n;
93 | do {
94 | l >>= 1;
95 | } while (mr+l > nn);
96 | mr = (mr & (l-1)) + l;
97 |
98 | if (mr <= m)
99 | continue;
100 | tr = fr[m];
101 | fr[m] = fr[mr];
102 | fr[mr] = tr;
103 | ti = fi[m];
104 | fi[m] = fi[mr];
105 | fi[mr] = ti;
106 | }
107 |
108 | l = 1;
109 | k = LOG2_N_WAVE-1;
110 | while (l < n) {
111 | if (inverse) {
112 | /* variable scaling, depending upon data */
113 | shift = 0;
114 | for (i=0; i 16383 || m > 16383) {
122 | shift = 1;
123 | break;
124 | }
125 | }
126 | if (shift)
127 | ++scale;
128 | } else {
129 | /*
130 | fixed scaling, for proper normalization --
131 | there will be log2(n) passes, so this results
132 | in an overall factor of 1/n, distributed to
133 | maximize arithmetic accuracy.
134 | */
135 | shift = 1;
136 | }
137 | /*
138 | it may not be obvious, but the shift will be
139 | performed on each data point exactly once,
140 | during this pass.
141 | */
142 | istep = l << 1;
143 | for (m=0; m>= 1;
160 | wi >>= 1;
161 | }
162 | for (i=m; i>= 1;
170 | qi >>= 1;
171 | }
172 | fr[j] = qr - tr;
173 | fi[j] = qi - ti;
174 | fr[i] = qr + tr;
175 | fi[i] = qi + ti;
176 | }
177 | }
178 | --k;
179 | l = istep;
180 | }
181 | return scale;
182 | }
183 |
184 | /*
185 | fix_fftr() - forward/inverse FFT on array of real numbers.
186 | Real FFT/iFFT using half-size complex FFT by distributing
187 | even/odd samples into real/imaginary arrays respectively.
188 | In order to save data space (i.e. to avoid two arrays, one
189 | for real, one for imaginary samples), we proceed in the
190 | following two steps: a) samples are rearranged in the real
191 | array so that all even samples are in places 0-(N/2-1) and
192 | all imaginary samples in places (N/2)-(N-1), and b) fix_fft
193 | is called with fr and fi pointing to index 0 and index N/2
194 | respectively in the original array. The above guarantees
195 | that fix_fft "sees" consecutive real samples as alternating
196 | real and imaginary samples in the complex array.
197 | */
198 | int16_t fix_fftr(int8_t f[], int16_t m, int16_t inverse)
199 | {
200 | int16_t i, N = 1<<(m-1), scale = 0;
201 | int8_t tt, *fr=f, *fi=&f[N];
202 |
203 | if (inverse)
204 | scale = fix_fft(fi, fr, m-1, inverse);
205 | for (i=1; i freq), fixed scaling is
9 | performed to prevent arithmetic overflow, and to map a 0dB
10 | sine/cosine wave (i.e. amplitude = 32767) to two -6dB freq
11 | coefficients. The return value is always 0.
12 |
13 | For the inverse FFT (freq -> time), fixed scaling cannot be
14 | done, as two 0dB coefficients would sum to a peak amplitude
15 | of 64K, overflowing the 32k range of the fixed-point integers.
16 | Thus, the fix_fft() routine performs variable scaling, and
17 | returns a value which is the number of bits LEFT by which
18 | the output must be shifted to get the actual amplitude
19 | (i.e. if fix_fft() returns 3, each value of fr[] and fi[]
20 | must be multiplied by 8 (2**3) for proper scaling.
21 | Clearly, this cannot be done within fixed-point short
22 | integers. In practice, if the result is to be used as a
23 | filter, the scale_shift can usually be ignored, as the
24 | result will be approximately correctly normalized as is.
25 |
26 | Written by: Tom Roberts 11/8/89
27 | Made portable: Malcolm Slaney 12/15/94 malcolm@interval.com
28 | Enhanced: Dimitrios P. Bouras 14 Jun 2006 dbouras@ieee.org
29 | */
30 |
31 | #define N_WAVE 1024 /* full length of Sinewave[] */
32 | #define LOG2_N_WAVE 10 /* log2(N_WAVE) */
33 |
34 | /*
35 | Henceforth "short" implies 16-bit word. If this is not
36 | the case in your architecture, please replace "short"
37 | with a type definition which *is* a 16-bit word.
38 | */
39 |
40 | /*
41 | Since we only use 3/4 of N_WAVE, we define only
42 | this many samples, in order to conserve data space.
43 | */
44 | short Sinewave[N_WAVE-N_WAVE/4] = {
45 | 0, 201, 402, 603, 804, 1005, 1206, 1406,
46 | 1607, 1808, 2009, 2209, 2410, 2610, 2811, 3011,
47 | 3211, 3411, 3611, 3811, 4011, 4210, 4409, 4608,
48 | 4807, 5006, 5205, 5403, 5601, 5799, 5997, 6195,
49 | 6392, 6589, 6786, 6982, 7179, 7375, 7571, 7766,
50 | 7961, 8156, 8351, 8545, 8739, 8932, 9126, 9319,
51 | 9511, 9703, 9895, 10087, 10278, 10469, 10659, 10849,
52 | 11038, 11227, 11416, 11604, 11792, 11980, 12166, 12353,
53 | 12539, 12724, 12909, 13094, 13278, 13462, 13645, 13827,
54 | 14009, 14191, 14372, 14552, 14732, 14911, 15090, 15268,
55 | 15446, 15623, 15799, 15975, 16150, 16325, 16499, 16672,
56 | 16845, 17017, 17189, 17360, 17530, 17699, 17868, 18036,
57 | 18204, 18371, 18537, 18702, 18867, 19031, 19194, 19357,
58 | 19519, 19680, 19840, 20000, 20159, 20317, 20474, 20631,
59 | 20787, 20942, 21096, 21249, 21402, 21554, 21705, 21855,
60 | 22004, 22153, 22301, 22448, 22594, 22739, 22883, 23027,
61 | 23169, 23311, 23452, 23592, 23731, 23869, 24006, 24143,
62 | 24278, 24413, 24546, 24679, 24811, 24942, 25072, 25201,
63 | 25329, 25456, 25582, 25707, 25831, 25954, 26077, 26198,
64 | 26318, 26437, 26556, 26673, 26789, 26905, 27019, 27132,
65 | 27244, 27355, 27466, 27575, 27683, 27790, 27896, 28001,
66 | 28105, 28208, 28309, 28410, 28510, 28608, 28706, 28802,
67 | 28897, 28992, 29085, 29177, 29268, 29358, 29446, 29534,
68 | 29621, 29706, 29790, 29873, 29955, 30036, 30116, 30195,
69 | 30272, 30349, 30424, 30498, 30571, 30643, 30713, 30783,
70 | 30851, 30918, 30984, 31049, 31113, 31175, 31236, 31297,
71 | 31356, 31413, 31470, 31525, 31580, 31633, 31684, 31735,
72 | 31785, 31833, 31880, 31926, 31970, 32014, 32056, 32097,
73 | 32137, 32176, 32213, 32249, 32284, 32318, 32350, 32382,
74 | 32412, 32441, 32468, 32495, 32520, 32544, 32567, 32588,
75 | 32609, 32628, 32646, 32662, 32678, 32692, 32705, 32717,
76 | 32727, 32736, 32744, 32751, 32757, 32761, 32764, 32766,
77 | 32767, 32766, 32764, 32761, 32757, 32751, 32744, 32736,
78 | 32727, 32717, 32705, 32692, 32678, 32662, 32646, 32628,
79 | 32609, 32588, 32567, 32544, 32520, 32495, 32468, 32441,
80 | 32412, 32382, 32350, 32318, 32284, 32249, 32213, 32176,
81 | 32137, 32097, 32056, 32014, 31970, 31926, 31880, 31833,
82 | 31785, 31735, 31684, 31633, 31580, 31525, 31470, 31413,
83 | 31356, 31297, 31236, 31175, 31113, 31049, 30984, 30918,
84 | 30851, 30783, 30713, 30643, 30571, 30498, 30424, 30349,
85 | 30272, 30195, 30116, 30036, 29955, 29873, 29790, 29706,
86 | 29621, 29534, 29446, 29358, 29268, 29177, 29085, 28992,
87 | 28897, 28802, 28706, 28608, 28510, 28410, 28309, 28208,
88 | 28105, 28001, 27896, 27790, 27683, 27575, 27466, 27355,
89 | 27244, 27132, 27019, 26905, 26789, 26673, 26556, 26437,
90 | 26318, 26198, 26077, 25954, 25831, 25707, 25582, 25456,
91 | 25329, 25201, 25072, 24942, 24811, 24679, 24546, 24413,
92 | 24278, 24143, 24006, 23869, 23731, 23592, 23452, 23311,
93 | 23169, 23027, 22883, 22739, 22594, 22448, 22301, 22153,
94 | 22004, 21855, 21705, 21554, 21402, 21249, 21096, 20942,
95 | 20787, 20631, 20474, 20317, 20159, 20000, 19840, 19680,
96 | 19519, 19357, 19194, 19031, 18867, 18702, 18537, 18371,
97 | 18204, 18036, 17868, 17699, 17530, 17360, 17189, 17017,
98 | 16845, 16672, 16499, 16325, 16150, 15975, 15799, 15623,
99 | 15446, 15268, 15090, 14911, 14732, 14552, 14372, 14191,
100 | 14009, 13827, 13645, 13462, 13278, 13094, 12909, 12724,
101 | 12539, 12353, 12166, 11980, 11792, 11604, 11416, 11227,
102 | 11038, 10849, 10659, 10469, 10278, 10087, 9895, 9703,
103 | 9511, 9319, 9126, 8932, 8739, 8545, 8351, 8156,
104 | 7961, 7766, 7571, 7375, 7179, 6982, 6786, 6589,
105 | 6392, 6195, 5997, 5799, 5601, 5403, 5205, 5006,
106 | 4807, 4608, 4409, 4210, 4011, 3811, 3611, 3411,
107 | 3211, 3011, 2811, 2610, 2410, 2209, 2009, 1808,
108 | 1607, 1406, 1206, 1005, 804, 603, 402, 201,
109 | 0, -201, -402, -603, -804, -1005, -1206, -1406,
110 | -1607, -1808, -2009, -2209, -2410, -2610, -2811, -3011,
111 | -3211, -3411, -3611, -3811, -4011, -4210, -4409, -4608,
112 | -4807, -5006, -5205, -5403, -5601, -5799, -5997, -6195,
113 | -6392, -6589, -6786, -6982, -7179, -7375, -7571, -7766,
114 | -7961, -8156, -8351, -8545, -8739, -8932, -9126, -9319,
115 | -9511, -9703, -9895, -10087, -10278, -10469, -10659, -10849,
116 | -11038, -11227, -11416, -11604, -11792, -11980, -12166, -12353,
117 | -12539, -12724, -12909, -13094, -13278, -13462, -13645, -13827,
118 | -14009, -14191, -14372, -14552, -14732, -14911, -15090, -15268,
119 | -15446, -15623, -15799, -15975, -16150, -16325, -16499, -16672,
120 | -16845, -17017, -17189, -17360, -17530, -17699, -17868, -18036,
121 | -18204, -18371, -18537, -18702, -18867, -19031, -19194, -19357,
122 | -19519, -19680, -19840, -20000, -20159, -20317, -20474, -20631,
123 | -20787, -20942, -21096, -21249, -21402, -21554, -21705, -21855,
124 | -22004, -22153, -22301, -22448, -22594, -22739, -22883, -23027,
125 | -23169, -23311, -23452, -23592, -23731, -23869, -24006, -24143,
126 | -24278, -24413, -24546, -24679, -24811, -24942, -25072, -25201,
127 | -25329, -25456, -25582, -25707, -25831, -25954, -26077, -26198,
128 | -26318, -26437, -26556, -26673, -26789, -26905, -27019, -27132,
129 | -27244, -27355, -27466, -27575, -27683, -27790, -27896, -28001,
130 | -28105, -28208, -28309, -28410, -28510, -28608, -28706, -28802,
131 | -28897, -28992, -29085, -29177, -29268, -29358, -29446, -29534,
132 | -29621, -29706, -29790, -29873, -29955, -30036, -30116, -30195,
133 | -30272, -30349, -30424, -30498, -30571, -30643, -30713, -30783,
134 | -30851, -30918, -30984, -31049, -31113, -31175, -31236, -31297,
135 | -31356, -31413, -31470, -31525, -31580, -31633, -31684, -31735,
136 | -31785, -31833, -31880, -31926, -31970, -32014, -32056, -32097,
137 | -32137, -32176, -32213, -32249, -32284, -32318, -32350, -32382,
138 | -32412, -32441, -32468, -32495, -32520, -32544, -32567, -32588,
139 | -32609, -32628, -32646, -32662, -32678, -32692, -32705, -32717,
140 | -32727, -32736, -32744, -32751, -32757, -32761, -32764, -32766,
141 | };
142 |
143 | /*
144 | FIX_MPY() - fixed-point multiplication & scaling.
145 | Substitute inline assembly for hardware-specific
146 | optimization suited to a particluar DSP processor.
147 | Scaling ensures that result remains 16-bit.
148 | */
149 | inline short FIX_MPY(short a, short b)
150 | {
151 | /* shift right one less bit (i.e. 15-1) */
152 | int c = ((int)a * (int)b) >> 14;
153 | /* last bit shifted out = rounding-bit */
154 | b = c & 0x01;
155 | /* last shift + rounding bit */
156 | a = (c >> 1) + b;
157 | return a;
158 | }
159 |
160 | /*
161 | fix_fft() - perform forward/inverse fast Fourier transform.
162 | fr[n],fi[n] are real and imaginary arrays, both INPUT AND
163 | RESULT (in-place FFT), with 0 <= n < 2**m; set inverse to
164 | 0 for forward transform (FFT), or 1 for iFFT.
165 | */
166 | int fix_fft(short fr[], short fi[], short m, short inverse)
167 | {
168 | int mr, nn, i, j, l, k, istep, n, scale, shift;
169 | short qr, qi, tr, ti, wr, wi;
170 |
171 | n = 1 << m;
172 |
173 | /* max FFT size = N_WAVE */
174 | if (n > N_WAVE)
175 | return -1;
176 |
177 | mr = 0;
178 | nn = n - 1;
179 | scale = 0;
180 |
181 | /* decimation in time - re-order data */
182 | for (m=1; m<=nn; ++m) {
183 | l = n;
184 | do {
185 | l >>= 1;
186 | } while (mr+l > nn);
187 | mr = (mr & (l-1)) + l;
188 |
189 | if (mr <= m)
190 | continue;
191 | tr = fr[m];
192 | fr[m] = fr[mr];
193 | fr[mr] = tr;
194 | ti = fi[m];
195 | fi[m] = fi[mr];
196 | fi[mr] = ti;
197 | }
198 |
199 | l = 1;
200 | k = LOG2_N_WAVE-1;
201 | while (l < n) {
202 | if (inverse) {
203 | /* variable scaling, depending upon data */
204 | shift = 0;
205 | for (i=0; i 16383 || m > 16383) {
213 | shift = 1;
214 | break;
215 | }
216 | }
217 | if (shift)
218 | ++scale;
219 | } else {
220 | /*
221 | fixed scaling, for proper normalization --
222 | there will be log2(n) passes, so this results
223 | in an overall factor of 1/n, distributed to
224 | maximize arithmetic accuracy.
225 | */
226 | shift = 1;
227 | }
228 | /*
229 | it may not be obvious, but the shift will be
230 | performed on each data point exactly once,
231 | during this pass.
232 | */
233 | istep = l << 1;
234 | for (m=0; m>= 1;
243 | wi >>= 1;
244 | }
245 | for (i=m; i>= 1;
253 | qi >>= 1;
254 | }
255 | fr[j] = qr - tr;
256 | fi[j] = qi - ti;
257 | fr[i] = qr + tr;
258 | fi[i] = qi + ti;
259 | }
260 | }
261 | --k;
262 | l = istep;
263 | }
264 | return scale;
265 | }
266 |
267 | /*
268 | fix_fftr() - forward/inverse FFT on array of real numbers.
269 | Real FFT/iFFT using half-size complex FFT by distributing
270 | even/odd samples into real/imaginary arrays respectively.
271 | In order to save data space (i.e. to avoid two arrays, one
272 | for real, one for imaginary samples), we proceed in the
273 | following two steps: a) samples are rearranged in the real
274 | array so that all even samples are in places 0-(N/2-1) and
275 | all imaginary samples in places (N/2)-(N-1), and b) fix_fft
276 | is called with fr and fi pointing to index 0 and index N/2
277 | respectively in the original array. The above guarantees
278 | that fix_fft "sees" consecutive real samples as alternating
279 | real and imaginary samples in the complex array.
280 | */
281 | int fix_fftr(short f[], int m, int inverse)
282 | {
283 | int i, N = 1<<(m-1), scale = 0;
284 | short tt, *fr=f, *fi=&f[N];
285 |
286 | if (inverse)
287 | scale = fix_fft(fi, fr, m-1, inverse);
288 | for (i=1; i= max_corr_level){
35 | max_corr_level = correlation_sum;
36 | max_corr_bpm = bpm;
37 | }
38 |
39 | if(correlation_sum >= 0.95){
40 | max_corr_level = correlation_sum;
41 | max_corr_bpm = bpm;
42 | break;
43 | }
44 | }
45 |
46 | Serial.println(max_corr_bpm);
47 | }
48 |
49 | void process_onset_pulse(){
50 | static bool onsets_ready = false;
51 |
52 | for(uint8_t i = 0; i < 15; i++){
53 | onset_pulse_history[i] = onset_pulse_history[i+1];
54 | }
55 |
56 | onset_pulse_history[15] = current_frame;
57 |
58 | if(onsets_ready == false){ // make sure 8 pulses have been detected
59 | onsets_ready = true;
60 | for(uint8_t i = 0; i < 16; i++){
61 | if(onset_pulse_history[i] == 0){
62 | onsets_ready = false;
63 | }
64 | }
65 | }
66 |
67 | if(onsets_ready){
68 | calculate_onset_correlation();
69 | }
70 | }
71 |
--------------------------------------------------------------------------------