├── LICENSE
├── README.md
├── beaglebone.gemspec
├── lib
├── beaglebone.rb
└── beaglebone
│ ├── ain.rb
│ ├── beaglebone.rb
│ ├── gpio.rb
│ ├── i2c.rb
│ ├── pwm.rb
│ ├── shiftregister.rb
│ ├── spi.rb
│ └── uart.rb
└── procedural-examples.md
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Beaglebone Ruby Library
2 |
3 | **Table of Contents**
4 | - [Overview](#overview)
5 | - [Installation](#installation)
6 | - [Installing Ruby](#installing-ruby)
7 | - [Installing Beaglebone Gem](#installing-beaglebone-gem)
8 | - [Updating Beaglebone Gem](#updating-beaglebone-gem)
9 | - [Usage](#usage)
10 | - [Ruby in Cloud9](#ruby-in-cloud9)
11 | - [Pin Information](#pin-information)
12 | - [GPIO Pins](#gpio-pins)
13 | - [Analog Pins](#analog-pins)
14 | - [PWM Pins](#pwm-pins)
15 | - [UART Pins](#uart-pins)
16 | - [I2C Pins](#i2c-pins)
17 | - [SPI Pins](#spi-pins)
18 | - [Source Code Reference](#source-code-reference)
19 | - [Examples (Object Oriented)](#examples-object-oriented)
20 | - [GPIO](#gpio)
21 | - [GPIO Writing](#gpio-writing)
22 | - [GPIO Reading](#gpio-reading)
23 | - [LEDs](#leds)
24 | - [Edge Triggers](#edge-triggers)
25 | - [Edge Triggers in the Background](#edge-triggers-in-the-background)
26 | - [Shift Registers](#shift-registers)
27 | - [Analog Inputs](#analog-inputs)
28 | - [Reading](#reading)
29 | - [Waiting for Change](#waiting-for-change)
30 | - [Waiting for Change in the Background](#waiting-for-change-in-the-background)
31 | - [Waiting for Threshold](#waiting-for-threshold)
32 | - [Waiting for Threshold in the Background](#waiting-for-Threshold-in-the-background)
33 | - [PWM](#pwm)
34 | - [UART](#uart)
35 | - [UART Writing](#uart-writing)
36 | - [UART Reading](#uart-reading)
37 | - [UART Reading and Iterating](#uart-reading-and-iterating)
38 | - [UART Reading and Iterating in the Background](#uart-reading-and-iterating-in-the-background)
39 | - [I2C](#i2c)
40 | - [I2C Writing](#i2c-writing)
41 | - [I2C Reading](#i2c-reading)
42 | - [LSM303DLHC Example](#lsm303dlhc-example)
43 | - [SPI](#spi)
44 | - [SPI Data Transfer](#spi-data-transfer)
45 | - [MCP3008 Example](#mcp3008-example)
46 | - [Examples (Procedural)](#examples-procedural)
47 | - [License](#license)
48 |
49 | ## Overview
50 | The purpose of this library is to provide easy access to all of the IO features of the Beaglebone in a highly flexible programming language (Ruby). This gem includes object oriented methods as well as procedural methods, so those familiar with Bonescript, the Adafruit Python library, or Arduino programming will be familiar with the syntax. This was developed and tested on a Beaglebone Black running the official Debian images. The code will need to be executed as root in order to function properly and utilize all of the features of the Beaglebone.
51 |
52 | ## Installation
53 | ### Installing Ruby
54 | Ruby and Rubygems are required to use this gem. To install, simply run the command below. This will install Ruby 1.9.3 which includes Rubygems.
55 |
56 | ```
57 | sudo apt-get install ruby
58 | ```
59 |
60 | ### Installing Beaglebone Gem
61 | Once Ruby is installed installed, install the gem by running the command below.
62 |
63 | ```
64 | sudo gem install beaglebone
65 | ```
66 |
67 | ### Updating Beaglebone Gem
68 | Once the gem is installed, you can update to the latest version by running the command below. New versions may contain bug fixes and new features.
69 |
70 | ```
71 | sudo gem update beaglebone
72 | ```
73 |
74 | ## Usage
75 | To use this gem, require it in the Ruby script. An example follows
76 |
77 | ```ruby
78 | #!/usr/bin/env ruby
79 | require 'beaglebone'
80 | include Beaglebone
81 | ```
82 |
83 | ### Ruby in Cloud9
84 | Cloud9 has native Ruby support. Name your files with the extension .rb to run Ruby in Cloud9
85 |
86 | ## Pin Information
87 | The Beaglebone has two headers of IO pins. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers).
88 |
89 | ### GPIO Pins
90 | The beaglebone has a large number of GPIO pins. These pins function at 3.3v. Do not provide more than 3.3v to any GPIO pin or risk damaging the hardware.
91 |
92 | There are built in _capes_ that have priority over the GPIO pins unless disabled. These are for HDMI and the onboard eMMC. It is documented [here](http://beagleboard.org/Support/bone101#headers-black). It is possible to disable these _capes_ if you are not using them.
93 |
94 | ### Analog Pins
95 | The beaglebone has 7 Analog inputs. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers-analog). These pins function at 1.8v. Do not provide more than 1.8v to any Analog pin or risk damaging the hardware. The header has pins available to provide a 1.8v for analog devices as well as a dedicated analog ground.
96 |
97 | ### PWM Pins
98 | The beaglebone has 8 PWM pins. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers-pwm). These pins function at 3.3v.
99 |
100 | Not all 8 pins may be used at the same time. You may use the following pins.
101 |
102 | - P8_13 or P8_19
103 | - P9_14 or P9_16
104 | - P9_21 or P9_22
105 | - P9_28 and P9_42
106 |
107 | ### UART Pins
108 | The beaglebone has 5 UART devices available. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers-serial). These pins function at 3.3v. Do not provide more than 3.3v to any UART pin or risk damaging the hardware.
109 |
110 | UART3 only has a TX pin available.
111 |
112 | UART5 TX and RX pins are unavailable by default, as the HDMI _cape_ claims those pins unless disabled.
113 |
114 | ### I2C Pins
115 | The beaglebone has 2 I2C devices available. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers-i2c). These pins function at 3.3v. Do not provide more than 3.3v to any I2C pin or risk damaging the hardware.
116 |
117 | ### SPI Pins
118 | The beaglebone has 2 SPI devices available. Documentation on these pins is available [here](http://beagleboard.org/Support/bone101#headers-spi). These pins function at 3.3v. Do not provide more than 3.3v to any SPI pin or risk damaging the hardware.
119 |
120 | ## Source Code Reference
121 | A full Source Code reference is available [here](http://rubydoc.info/gems/beaglebone/1.0.5/frames).
122 |
123 | ## Examples (Object Oriented)
124 | These examples will show the various ways to interact with the Beaglebones IO hardware. They will need to be executed as root in order to function correctly.
125 |
126 | ### GPIO
127 | The GPIO pins on the Beaglebone run at **3.3v**. Do not provide more than 3.3v to any GPIO pin or risk damaging the hardware.
128 |
129 | GPIO pins have two modes, input and output. These modes are represented by the symbols **:IN** and **:OUT**.
130 |
131 | GPIO pins have internal pullup and pulldown resistors. These modes are represented by the symbols **:PULLUP**, **:PULLDOWN**, and **:NONE**.
132 |
133 | GPIO pins have an adjustable slew rate. These modes are represented by the symbols **:FAST** and **:SLOW**
134 |
135 | To initialize the pin **P9_11**, pass the symbol for that pin and the mode to the **GPIOPin** constructor.
136 |
137 | ```ruby
138 | # Initialize pin P9_11 in INPUT mode
139 | # This method takes 4 arguments
140 | # pin: The pin to initialize
141 | # mode: The GPIO mode, :IN or :OUT
142 | # pullmode: (optional) The pull mode, :PULLUP, :PULLDOWN, or :NONE
143 | # slewrate: (optional) The slew rate, :FAST or :SLOW
144 | p9_11 = GPIOPin.new(:P9_11, :IN, :PULLUP, :FAST)
145 |
146 | # Initialize pin P9_12 in OUTPUT mode
147 | p9_12 = GPIOPin.new(:P9_12, :OUT)
148 |
149 | # Change pin P9_12 to INPUT mode
150 | p9_12.set_gpio_mode(:IN)
151 |
152 | # Disable pin P9_12
153 | p9_12.disable_gpio_pin
154 |
155 | # Unassign to prevent re-use
156 | p9_12 = nil
157 | ```
158 |
159 | #### GPIO Writing
160 | To set the state of a GPIO pin, the method **#digital_write** is used. The states that can be set are **:HIGH** to provide 3.3v and **:LOW** to provide ground.
161 |
162 | ```ruby
163 | # Initialize pin P9_12 in OUTPUT mode
164 | p9_12 = GPIOPin.new(:P9_12, :OUT)
165 |
166 | # Provide 3.3v on pin P9_12
167 | p9_12.digital_write(:HIGH)
168 |
169 | # Provide ground on pin P9_12
170 | p9_12.digital_write(:LOW)
171 | ```
172 |
173 | #### GPIO Reading
174 | To read the current state of a GPIO pin, the method **#digital_read** is used. It will return the symbol **:HIGH** or **:LOW** depending on the state of the pin.
175 |
176 | ```ruby
177 | # Initialize pin P9_11 in INPUT mode
178 | p9_11 = GPIOPin.new(:P9_11, :IN)
179 |
180 | # Get the current state of P9_11
181 | state = p9_11.digital_read => :LOW
182 | ```
183 |
184 | #### LEDs
185 | The on-board LEDs are addressable via GPIO output. They are available on pins **:USR0** through **:USR3**.
186 |
187 | This example will blink each LED in order 5 times.
188 |
189 | ```ruby
190 | # Create an led object for each LED
191 | led1 = GPIOPin.new(:USR0, :OUT)
192 | led2 = GPIOPin.new(:USR1, :OUT)
193 | led3 = GPIOPin.new(:USR2, :OUT)
194 | led4 = GPIOPin.new(:USR3, :OUT)
195 |
196 | # Run the following block 5 times
197 | 5.times do
198 | # Iterate over each LED
199 | [led1,led2,led3,led4].each do |led|
200 | # Turn on the LED
201 | led.digital_write(:HIGH)
202 | # Delay 0.25 seconds
203 | sleep 0.25
204 | # Turn off the LED
205 | led.digital_write(:LOW)
206 | end
207 | end
208 | ```
209 |
210 | #### Edge Triggers
211 | The Beaglebone can monitor for changes on a GPIO pin. This is called an edge trigger. Since this is interrupt based on the Beaglebone, waiting for a change does not waste CPU cycles by constantly polling the pin.
212 |
213 | The following trigger types are supported
214 | - Rising: Triggered when the state goes from low to high
215 | - Falling: Triggered when the state goes from high to low
216 | - Both: Triggered at any change in state
217 | - None: Triggering is disabled
218 |
219 | These trigger types are represented by the symbols :RISING, :FALLING, :BOTH, and :NONE
220 |
221 | This example will wait for a rising edge to continue, then output the type of edge trigger that was detected.
222 |
223 | ```ruby
224 | # Initialize pin P9_11 in INPUT mode
225 | p9_11 = GPIOPin.new(:P9_11, :IN)
226 |
227 | # Wait here until a rising edge is detected
228 | edge = p9_11.wait_for_edge(:RISING) => :RISING
229 |
230 | # Output the trigger type detected
231 | puts "Saw a #{edge} edge"
232 | ```
233 |
234 | #### Edge Triggers in the Background
235 | To avoid blocking while waiting for an edge trigger, the method **#run_on_edge** will run a callback when an edge trigger is detected. This method will spawn a new thread and wait for an edge trigger in the background. Only one of these threads may be active per pin.
236 |
237 | This example will detect edge triggers in the background and output information when triggered.
238 |
239 | ```ruby
240 | # Initialize pin P9_11 in INPUT mode
241 | p9_11 = GPIOPin.new(:P9_11, :IN)
242 |
243 | # Define callback to run when an edge trigger is detected
244 | # This method takes 3 arguments.
245 | # pin: The pin that triggered the event
246 | # edge: The event that triggered it
247 | # count: How many times it has been triggered
248 | callback = lambda { |pin,edge,count| puts "[#{count}] #{pin} #{edge}"}
249 |
250 | # Run the callback every time a change in state is detected
251 | # This method has two additional arguments that are optional.
252 | # Timeout: How long to wait for an event before terminating the thread
253 | # Repeats: How many times to run the event
254 | # By default, it will run forever every time the specified trigger is detected
255 | p9_11.run_on_edge(callback, :BOTH)
256 |
257 | # This code will run immediately after the previous call, as it does not block
258 | sleep 10
259 |
260 | # Stop the background thread waiting for an edge trigger after 10 seconds
261 | p9_11.stop_edge_wait
262 |
263 | # This convenience method will run the callback only on the first detected change
264 | p9_11.run_once_on_edge(callback, :BOTH)
265 |
266 | # Change the trigger detection for the specified pin
267 | p9_11.set_gpio_edge(:RISING)
268 | ```
269 |
270 | #### Shift Registers
271 | This library will support writing to shift registers using GPIO pins. Create a **ShiftRegister** object by initializing it with the latch pin, clock pin, and data pin.
272 |
273 | This example will trigger 8 pins of a shift register.
274 |
275 | ```ruby
276 | # P9_11 is connected to the latch pin
277 | # P9_12 is connected to the clock pin
278 | # P9_13 is connected to the data pin
279 |
280 | # Initialize shift register
281 | shiftreg = ShiftRegister.new(:P9_11, :P9_12, :P9_13)
282 |
283 | # Write value to shift register
284 | shiftreg.shift_out(0b11111111)
285 | ```
286 |
287 |
288 | ### Analog Inputs
289 | The Analog pins on the Beaglebone run at **1.8v**. Do not provide more than 1.8v to any analog pin or risk damaging the hardware. The header has pins available to provide a 1.8v for analog devices as well as a dedicated analog ground. Analog pins are only capable of reading input values.
290 |
291 | To initialize the pin **P9_33**, pass the symbol for that pin and the mode to the **AINPin** constructor.
292 |
293 | ```ruby
294 | # Initialize pin P9_33 for Analog Input
295 | p9_33 = AINPin.new(:P9_33)
296 | ```
297 |
298 | #### Reading
299 | To read the value from an analog pin, the method **#read** is used. This will return a value between 0 and 1799.
300 |
301 | ```ruby
302 | # Initialize pin P9_33 for Analog Input
303 | p9_33 = AINPin.new(:P9_33)
304 |
305 | # Read the input value in millivolts.
306 | mv = p9_33.read => 1799
307 | ```
308 |
309 | #### Waiting for Change
310 | To wait for the value of an analog pin to change by a specified voltage, the method **#wait_for_change** is used.
311 |
312 | **#wait_for_change** takes the following arguments.
313 | - mv_change: The amount of change in millivolts required before returning
314 | - interval: How often to poll the value of the pin in seconds
315 | - mv_last: (optional) The initial value to use as a point to detect change
316 |
317 | This method returns an array containing the initial voltage, the last polled voltage, and the number of times the pin was polled.
318 |
319 | ```ruby
320 | # Initialize pin P9_33 for Analog Input
321 | p9_33 = AINPin.new(:P9_33)
322 |
323 | # Wait for 100mv of change on pin P9_33. Poll 10 times a second
324 | mv_start, mv_current, count = p9_33.wait_for_change(100, 0.1)
325 | ```
326 |
327 | #### Waiting for Change in the Background
328 | To avoid blocking while waiting for voltage change, the method **#run_on_change** will run a callback every time the specified change is detected. This method will spawn a new thread and wait for change in the background. The method **#run_once_on_change** is a convenience method to only be triggered once. Only one of these threads may be active per pin.
329 |
330 | This example waits for voltage change in the background and outputs information when change is detected.
331 |
332 | ```ruby
333 | # Initialize pin P9_33 for Analog Input
334 | p9_33 = AINPin.new(:P9_33)
335 |
336 | # Define callback to run when condition is met
337 | # This method takes 4 arguments.
338 | # pin: The pin that triggered the event
339 | # mv_last: The initial voltage used to determine change
340 | # mv: The current voltage on the pin
341 | # count: How many times it has been triggered
342 | callback = lambda { |pin, mv_last, mv, count| puts "[#{count}] #{pin} #{mv_last} -> #{mv}" }
343 |
344 | # Run the callback every time the specified voltage change is detected
345 | # This method has one additional argument that is optional.
346 | # Repeats: How many times to will run the event
347 | # By default, it will run forever every time the specified condition is detected
348 | # Detect 10mv of change polling 10 times a second.
349 | p9_33.run_on_change(callback, 10, 0.1)
350 |
351 | # This code will run immediately after the previous call, as it does not block
352 | sleep 20
353 |
354 | # Stop the background thread after 20 seconds
355 | p9_33.stop_wait
356 | ```
357 |
358 | #### Waiting for Threshold
359 | To wait for the value of an analog pin to cross certain threshold voltages, the method **#wait_for_threshold** is used.
360 |
361 | **#wait_for_threshold** takes the following arguments.
362 | - mv_lower: The lower threshold value in millivolts
363 | - mv_upper: The upper threshold value in millivolts
364 | - mv_reset: The voltage change required to cross out of the lower or upper threshold ranges.
365 | - interval: How often to poll the value of the pin in seconds
366 | - mv_last: (optional) The initial value to use as a point to detect change
367 | - state_last: (optional) The initial state to use as a point to detect change
368 |
369 | Three states are available.
370 | - :LOW: below or equal to mv_lower
371 | - :MID: above mv_lower and below mv_upper
372 | - :HIGH: above or equal to mv_upper
373 |
374 | This method returns an array containing the initial voltage, the last polled voltage, the initial state, the last polled state, and the number of times the pin was polled.
375 |
376 | ```ruby
377 | # Initialize pin P9_33 for Analog Input
378 | p9_33 = AINPin.new(:P9_33)
379 |
380 | # Wait for the voltage on pin P9_33 to go below 200mv or above 1600mv.
381 | # To enter the :MID state from :HIGH or :LOW, it will have to cross the thresholds by at least 100mv.
382 | # Poll 10 times a second
383 | data = p9_33.wait_for_threshold(200, 1600, 100, 0.1) => [ 500, 150, :MID, :LOW, 53 ]
384 |
385 | # Assign variables from array
386 | mv_start, mv_current, state_start, state_current, count = data
387 | ```
388 |
389 | #### Waiting for Threshold in the Background
390 | To avoid blocking while waiting for a voltage threshold to be crossed, the method **#run_on_threshold** will run a callback every time the specified change is detected. This method will spawn a new thread and wait for change in the background. The method **#run_once_on_threshold** is a convenience method to only be triggered once. Only one of these threads may be active per pin.
391 |
392 | This example waits for voltage change in the background and outputs information when the specified threshold is crossed.
393 |
394 | ```ruby
395 | # Initialize pin P9_33 for Analog Input
396 | p9_33 = AINPin.new(:P9_33)
397 |
398 | # Define callback to run when condition is met
399 | # This method takes 6 arguments.
400 | # pin: The pin that triggered the event
401 | # mv_last: The initial voltage used to determine change
402 | # mv: The current voltage on the pin
403 | # state_last: The initial state to use as a point to detect change
404 | # state: The current state of the pin
405 | # count: How many times it has been triggered
406 | callback = lambda { |pin, mv_last, mv, state_last, state, count|
407 | puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
408 | }
409 |
410 | # Run the callback every time the specified voltage threshold is crossed
411 | # This method has one additional argument that is optional.
412 | # Repeats: How many times to will run the event
413 | # By default, it will run forever every time the specified condition is detected
414 | # Wait for the voltage on pin P9_33 to go below 200mv or above 1600mv.
415 | # To enter the :MID state from :HIGH or :LOW, it will have to cross the thresholds by at least 100mv.
416 | # Poll 10 times a second
417 | # Run callback when state changes
418 | p9_33.run_on_threshold(callback, 200, 1600, 100, 0.1)
419 |
420 | # This code will run immediately after the previous call, as it does not block
421 | sleep 20
422 |
423 | # Stop the background thread after 20 seconds
424 | p9_33.stop_wait
425 | ```
426 |
427 | ### PWM
428 | The beaglebone supports PWM (pulse width modulated) output on certain pins. These pins output 3.3v. The output is controlled based on frequency and duty cycle.
429 |
430 | To initialize the pin **P9_14**, pass the symbol for that pin, the duty cycle, and the frequency in Hz to the **PWMPin** constructor.
431 |
432 | This example shows how to control PWM output of a specified pin.
433 |
434 | ```ruby
435 | # Initialize pin P9_14 for PWM output
436 | # This pin will now output a square wave at 10Hz with a 90% duty cycle, non-inverted.
437 | p9_14 = PWMPin.new(:P9_14, 90, 10, :NORMAL)
438 |
439 | # Change frequency to 20Hz. Duty cycle remains 90%
440 | p9_14.set_frequency(20)
441 |
442 | # Change the duty cycle to 50%
443 | p9_14.set_duty_cycle(50)
444 |
445 | # Adjust the frequency by setting the period in nanoseconds.
446 | p9_14.set_period_ns(31250000)
447 |
448 | # Adjust the duty cycle by setting the period in nanoseconds.
449 | p9_14.set_duty_cycle_ns(31250000)
450 |
451 | # Invert the output signal
452 | p9_14.set_polarity(:INVERTED)
453 |
454 | # Stop the output signal
455 | p9_14.stop
456 |
457 | # Resume the output signal
458 | p9_14.run
459 |
460 | # Disable the output signal
461 | p9_14.disable_pwm_pin
462 | ```
463 |
464 | ### UART
465 | The beaglebone has a number of UART devices. These operate in TTL mode at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
466 |
467 | Please note, UART3 does not have an RX pin, and UART5 is only available if the HDMI device tree is not enabled.
468 |
469 | To initialize the UART device **UART1**, pass the symbol for that device and the speed to the **UARTDevice** constructor.
470 |
471 | ```ruby
472 | # Initialize the pins for device UART1 into UART mode.
473 | uart1 = UARTDevice.new(:UART1, 9600)
474 |
475 | # Change the speed of a UART device by calling #set_speed
476 | uart1.set_speed(115200)
477 |
478 | # Disable UART device
479 | uart1.disable
480 | ```
481 |
482 | #### UART Writing
483 | Writing to a UART device is accomplished by calling the **#write** or **#writeln** methods
484 | ```ruby
485 | # Initialize the pins for device UART1 into UART mode.
486 | uart1 = UARTDevice.new(:UART1, 9600)
487 |
488 | # Write data to a UART1
489 | uart1.write("DATA DATA DATA!")
490 |
491 | # Write data to UART1 followed by a line feed
492 | uart1.writeln("A line feed follows")
493 | ```
494 |
495 | #### UART Reading
496 | There are many methods available for reading from UART devices. These are blocking methods and will not return until the requested data is available.
497 |
498 | ```ruby
499 | # Initialize the pins for device UART1 into UART mode.
500 | uart1 = UARTDevice.new(:UART1, 9600)
501 |
502 | # Read one character from UART1
503 | c = uart1.readchar => "X"
504 |
505 | # Read 10 characters from UART1
506 | str = uart1.readchars(10) => "0123456789"
507 |
508 | # Read a line from UART1
509 | line = uart1.readline => "All the text up until the linefeed"
510 | ```
511 |
512 | #### UART Reading and Iterating
513 | Data read from the UART device may be iterated with the following methods. These are blocking methods and will run until the loop is broken.
514 |
515 | ```ruby
516 | # Initialize the pins for device UART1 into UART mode.
517 | uart1 = UARTDevice.new(:UART1, 9600)
518 |
519 | # Run block on every character read from UART1
520 | uart1.each_char { |c| puts c }
521 |
522 | # Run block on every 5 character read from UART1
523 | uart1.each_char(5) { |str| puts str }
524 |
525 | # Run block on each line read from UART1
526 | uart1.each_line { |line| puts line }
527 | ```
528 |
529 | #### UART Reading and Iterating in the Background
530 | Data read from the UART device may be iterated in the background with the following methods. The data read is passed to the specified callback. These method will spawn a new thread and wait for data in the background. Only one of these threads may be active per pin.
531 |
532 | This example shows various methods of reading and processing data read from UART1 in the background.
533 |
534 | ```ruby
535 | # Initialize the pins for device UART1 into UART mode.
536 | uart1 = UARTDevice.new(:UART1, 9600)
537 |
538 | # Define the callback to be run. It takes 3 arguments
539 | # uart: the UART device that triggered the callback
540 | # data: the data read from the UART
541 | # count: how many times this was triggered
542 | callback = lambda { |uart, data, count| puts "[#{uart}:#{count}] #{data}" }
543 |
544 | # Run callback for every character read
545 | uart1.run_on_each_char(callback)
546 |
547 | # Run callback for every 3 characters read
548 | uart1.run_on_each_chars(callback, 3)
549 |
550 | # Run callback for every line read
551 | uart1.run_on_each_line(callback)
552 |
553 | # Run callback once after a character is read
554 | uart1.run_once_on_each_char(callback)
555 |
556 | # Run callback once after 3 characters are read
557 | uart1.run_once_on_each_chars(callback, 3)
558 |
559 | # Run callback once after reading a line
560 | uart1.run_once_on_each_line(callback)
561 |
562 | # Stop the currently running background thread
563 | uart1.stop_read_wait
564 | ```
565 |
566 | ### I2C
567 | The beaglebone has a number of I2C devices. These operate at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
568 |
569 | To initialize the I2C device **I2C2**, pass the symbol for that device to the **I2CDevice** constructor.
570 |
571 | ```ruby
572 | # Initialize I2C device I2C2
573 | i2c = I2CDevice.new(:I2C2)
574 | ```
575 |
576 | #### I2C Writing
577 | To write to an I2C device, the method **#write** is used.
578 |
579 | **#write** takes the following arguments.
580 | - address: address of slave device
581 | - data: data to write
582 |
583 | #### I2C Reading
584 | To read from an I2C device, the method **#read** is used.
585 |
586 | **#read** takes the following arguments.
587 | - address: address of slave device
588 | - bytes: bytes to read
589 | - register: (optional) register to start reading from
590 |
591 | #### LSM303DLHC Example
592 |
593 | This example communicates with an [LSM303DLHC](https://www.adafruit.com/products/1120) Accelerometer/Compass/Thermometer device.
594 |
595 | ```ruby
596 | #!/usr/bin/env ruby
597 | require 'beaglebone'
598 | include Beaglebone
599 |
600 | # Initialize I2C device I2C2
601 | i2c = I2CDevice.new(:I2C2)
602 |
603 | # Put compass into continuous conversation mode
604 | i2c.write(0x1e, [0x02, 0x00].pack("C*"))
605 |
606 | # Enable temperatuer sensor, 15hz register update
607 | i2c.write(0x1e, [0x00, 0b10010000].pack("C*") )
608 |
609 | # Delay for the settings to take effect
610 | sleep(0.1)
611 |
612 | # Read axis data. It is made up of 3 big endian signed shorts starting at register 0x03
613 | raw = i2c.read(0x1e, 6, [0x03].pack("C*"))
614 |
615 | # Coordinates are big endian signed shorts in x,z,y order
616 | x,z,y = raw.unpack("s>*")
617 |
618 | # Calculate angle of degrees from North
619 | degrees = (Math::atan2(y, x) * 180) / Math::PI
620 | degrees += 360 if degrees < 0
621 |
622 | # Read 2 byte big endian signed short from temperature register
623 | raw = i2c.read(0x1e, 2, [0x31].pack("C*"))
624 |
625 | # Temperature is sent big endian, least significant digit last
626 | temp = raw.unpack("s>").first
627 |
628 | # Temperature data is 12 bits, last 4 are unused
629 | temp = temp >> 4
630 |
631 | # Each bit is 8c
632 | temp /= 8
633 |
634 | # Correction factor
635 | temp += 18
636 |
637 | # Convert to f
638 | temp = (temp * 1.8 + 32).to_i
639 |
640 | # Output data
641 | puts "#{Time.now.strftime("%H:%M")} Temperature: #{temp} degrees f Direction: #{degrees.to_i} degrees"
642 |
643 | # Disable I2C device
644 | i2c.disable
645 | ```
646 |
647 | ### SPI
648 | The beaglebone has a number of SPI devices. These operate at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
649 |
650 | To initialize the SPI device **SPI0**, pass the symbol for that device to the **SPIDevice** constructor.
651 |
652 | The optional arguments are available
653 | - mode: SPI mode, :SPI_MODE_0 through :SPI_MODE_3
654 | - speed: Speed of the SPI device
655 | - bpw: Bits per word
656 |
657 | ```ruby
658 | # Initialize SPI device SPI0
659 | spi = SPIDevice.new(:SPI0, :SPI_MODE_0, 1000000, 8)
660 |
661 | # You can change SPI with the methods below.
662 |
663 | # Set mode of SPI0
664 | spi.set_mode(:SPI_MODE_3)
665 |
666 | # Set speed of SPI0
667 | spi.set_speed(100000)
668 |
669 | # Set bits per word of SPI0
670 | spi.set_bpw(10)
671 |
672 | # Disable SPI device
673 | spi.disable
674 | ```
675 |
676 | #### SPI Data Transfer
677 | To transfer data to an SPI device, the method **#xfer** is used.
678 |
679 | **#xfer** takes the following arguments
680 | - tx_data: data to transmit
681 | - readbytes: (optional) number of bytes to read, otherwise it sizeof tx_data is used
682 | - speed: (optional) speed of the transfer
683 | - delay: (optional) delay
684 | - bpw: (optonal) bits per word
685 |
686 | **#xfer** returns the data read from the SPI device.
687 |
688 | #### MCP3008 Example
689 | This example communicates with an [MCP3008](http://www.adafruit.com/products/856) ADC device.
690 |
691 | ```ruby
692 | #!/usr/bin/env ruby
693 | require 'beaglebone'
694 | include Beaglebone
695 |
696 | # Initialize SPI device SPI0
697 | spi = SPIDevice.new(:SPI0)
698 |
699 | # communicate with MCP3008
700 | # byte 1: start bit
701 | # byte 2: single(1)/diff(0),3 bites for channel, null pad
702 | # byte 3: don't care
703 | # Read value from channel 0
704 | raw = spi.xfer([ 0b00000001, 0b10000000, 0].pack("C*"))
705 |
706 | # Split data read into an array of characters
707 | data = raw.unpack("C*")
708 |
709 | # The returned data is stored starting at the last two bits of the second byte
710 | val = ((data[1] & 0b00000011) << 8 ) | data[2]
711 |
712 | # Display the value of channel 0
713 | puts "Value of channel 0: #{val}"
714 |
715 | # Read value from channel 1
716 | raw = spi.xfer([ 0b00000001, 0b10010000, 0].pack("C*"))
717 |
718 | # Split data read into an array of characters
719 | data = raw.unpack("C*")
720 |
721 | # The returned data is stored starting at the last two bits of the second byte
722 | val = ((data[1] & 0b00000011) << 8 ) | data[2]
723 |
724 | # Display the value of channel 1
725 | puts "Value of channel 1: #{val}"
726 |
727 | # Disable SPI device
728 | spi.disable
729 | ```
730 |
731 | ## Examples (Procedural)
732 | This library supports _procedural_ methods as well as _object oriented_ methods. They are virtually identical to the _object oriented_ methods, except the first argument they take is the pin. If a callback is required, it is still passed first, before the pin.
733 |
734 | The procedural versions of the examples are available in the file [procedural-examples.md](procedural-examples.md).
735 |
736 | Instead of constructors, the following methods are used to initialize the pins and devices on the Beaglebone.
737 |
738 | ```ruby
739 | # GPIOPin.new becomes
740 | GPIO.pin_mode(:P9_12, :OUT)
741 |
742 | # To set the state of the pin
743 | GPIO.digital_write(:P9_12, :OUT)
744 |
745 | # Analog pins do not require setup, and can be read at any time
746 | AIN.read(:P9_33)
747 |
748 | # PWMPin.new becomes
749 | PWM.start(:P9_14, 90, 10, :NORMAL)
750 |
751 | # UARTDevice.new becomes
752 | UART.setup(:UART1, 9600)
753 |
754 | # I2CDevice.new becomes
755 | I2C.setup(:I2C2)
756 |
757 | # SPIDevice.new becomes
758 | SPI.setup(:SPI0)
759 | ```
760 |
761 | ## License
762 | Copyright (c) 2014 Rob Mosher. Distributed under the GPL-v3 License. See [LICENSE](LICENSE) for more information.
763 |
--------------------------------------------------------------------------------
/beaglebone.gemspec:
--------------------------------------------------------------------------------
1 | Gem::Specification.new do |s|
2 | s.name = 'beaglebone'
3 | s.version = '1.2.6'
4 | s.date = '2015-03-01'
5 | s.summary = 'Beaglebone IO Gem'
6 | s.description = 'A Full Featured Beaglebone IO Gem'
7 | s.author = 'Rob Mosher'
8 | s.email = 'nyt-rubygems@countercultured.net'
9 | s.files = `git ls-files`.split("\n")
10 | s.homepage = 'https://github.com/notnyt/beaglebone'
11 | s.license = 'GPL-3.0'
12 | end
13 |
--------------------------------------------------------------------------------
/lib/beaglebone.rb:
--------------------------------------------------------------------------------
1 | require 'beaglebone/beaglebone'
2 | require 'beaglebone/spi'
3 | require 'beaglebone/i2c'
4 | require 'beaglebone/uart'
5 | require 'beaglebone/pwm'
6 | require 'beaglebone/ain'
7 | require 'beaglebone/gpio'
8 | require 'beaglebone/shiftregister'
9 |
--------------------------------------------------------------------------------
/lib/beaglebone/ain.rb:
--------------------------------------------------------------------------------
1 | # == ain.rb
2 | # This file contains the Analog Input methods
3 | module Beaglebone #:nodoc:
4 | # == AIN
5 | # procedural methods for Analog Input
6 | # == Summary
7 | # #read is called to get the analog value of a pin.
8 | # More advanced polling methods are also available
9 | module AIN
10 | class << self
11 |
12 | # valid voltage readings in mv
13 | RANGE = (0..1799)
14 |
15 | # Read from an analog pin
16 | #
17 | # @param pin should be a symbol representing the header pin
18 | #
19 | # @return [Integer] value in millivolts
20 | #
21 | # @example
22 | # AIN.read(:P9_33) => 1799
23 | def read(pin)
24 | Beaglebone::check_valid_pin(pin, :analog)
25 |
26 | Beaglebone::set_pin_status(pin, :type, :analog)
27 |
28 | ain_fd = Beaglebone::get_pin_status(pin, :fd_ain)
29 |
30 | unless ain_fd
31 | #ensure dtb is loaded
32 | Beaglebone::device_tree_load(TREES[:ADC][:global])
33 |
34 | #open the AIN analog input file
35 | pininfo = PINS[pin]
36 |
37 | ain_file = Dir.glob("/sys/devices/ocp.*/helper.*/AIN#{pininfo[:analog]}").first
38 | #ain_file = Dir.glob("/sys/bus/iio/devices/iio:device0/in_voltage#{pininfo[:analog]}_raw").first
39 | ain_fd = File.open(ain_file, 'r')
40 |
41 | Beaglebone::set_pin_status(pin, :fd_ain, ain_fd)
42 | end
43 |
44 | ain_fd.rewind
45 | ain_fd.read.strip.to_i
46 | end
47 |
48 | # Runs a callback after voltage changes by specified amount.
49 | # This creates a new thread that runs in the background and polls at specified interval.
50 | #
51 | # @param callback A method to call when the change is detected. This method should take 4 arguments: the pin, the previous voltage, the current voltage, and the counter
52 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
53 | # @param mv_change an integer specifying the required change in mv
54 | # @param interval a number representing the wait time between polling
55 | # @param repeats is optional and specifies the number of times the callback will be run
56 | #
57 | # @example
58 | # This polls every 0.1 seconds and will run after a 10mv change is detected
59 | # callback = lambda { |pin, mv_last, mv, count| puts "[#{count}] #{pin} #{mv_last} -> #{mv}" }
60 | # AIN.run_on_change(callback, :P9_33, 10, 0.1)
61 | def run_on_change(callback, pin, mv_change=10, interval=0.01, repeats=nil)
62 |
63 | raise StandardError, "Already waiting for change on pin: #{pin}" if Beaglebone::get_pin_status(pin, :waiting)
64 | raise StandardError, "Already waiting for thread on pin: #{pin}" if Beaglebone::get_pin_status(pin, :thread)
65 |
66 | thread = Thread.new(callback, pin, mv_change, interval, repeats) do |c, p, mvc, i, r|
67 | begin
68 | count = 0
69 | mvl = nil
70 | loop do
71 |
72 | mvl,mv,itr = wait_for_change(p, mvc, i, mvl)
73 |
74 | c.call(p, mvl, mv, count) if c
75 |
76 | #if there was no delay in the wait_for_change, delay now.
77 | sleep(interval) if itr == 0
78 |
79 | mvl = mv
80 | count += 1
81 | break if r && count >= r
82 | end
83 | rescue => ex
84 | puts ex
85 | puts ex.backtrace
86 | ensure
87 | Beaglebone::delete_pin_status(p, :thread)
88 | Beaglebone::delete_pin_status(p, :waiting)
89 | end
90 | end
91 |
92 | Beaglebone::set_pin_status(pin, :thread, thread)
93 | end
94 |
95 | # Runs a callback once after specified change in voltage detected
96 | # Convenience method for run_on_change
97 | # @see #run_on_change
98 | def run_once_on_change(callback, pin, mv_change=10, interval=0.01)
99 | run_on_change(callback, pin, mv_change, interval, 1)
100 | end
101 |
102 | # Runs a callback after voltage changes beyond a certain threshold.
103 | # This creates a new thread that runs in the background and polls at specified interval.
104 | # When the voltage crosses the specified thresholds the callback is run.
105 | #
106 | # @param callback A method to call when the change is detected. This method should take 6 arguments: the pin, the previous voltage, the current voltage, the previous state, the current state, and the counter
107 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
108 | # @param mv_lower an integer specifying the lower threshold voltage
109 | # @param mv_upper an integer specifying the upper threshold voltage
110 | # @param mv_reset an integer specifying the range in mv required to reset the threshold trigger
111 | # @param interval a number representing the wait time between polling
112 | # @param repeats is optional and specifies the number of times the callback will be run
113 | # @example
114 | # # This polls every 0.01 seconds and will run after a the voltage crosses 400mv or 1200mv.
115 | # Voltage will have to cross a range by at least 5mv to prevent rapidly triggering events
116 | # callback = lambda { |pin, mv_last, mv, state_last, state, count|
117 | # puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
118 | # }
119 | # AIN.run_on_threshold(callback, :P9_33, 400, 1200, 5, 0.01)
120 | def run_on_threshold(callback, pin, mv_lower, mv_upper, mv_reset=10, interval=0.01, repeats=nil)
121 |
122 | raise StandardError, "Already waiting for change on pin: #{pin}" if Beaglebone::get_pin_status(pin, :waiting)
123 | raise StandardError, "Already waiting for thread on pin: #{pin}" if Beaglebone::get_pin_status(pin, :thread)
124 |
125 | thread = Thread.new(callback, pin, mv_lower, mv_upper, mv_reset, interval, repeats) do |c, p, mvl, mvu, mvr, i, r|
126 | begin
127 | count = 0
128 | mv_last = nil
129 | state_last = nil
130 | loop do
131 |
132 | mv_last,mv,state_last,state,itr = wait_for_threshold(p, mvl, mvu, mvr, i, mv_last, state_last)
133 |
134 | c.call(p, mv_last, mv, state_last, state, count) if c
135 |
136 | #if there was no delay in the wait_for_change, delay now.
137 | sleep(interval) if itr == 0
138 |
139 | mv_last = mv
140 | state_last = state
141 | count += 1
142 | break if r && r >= count
143 | end
144 | rescue => ex
145 | puts ex
146 | puts ex.backtrace
147 | ensure
148 | Beaglebone::delete_pin_status(p, :thread)
149 | Beaglebone::delete_pin_status(p, :waiting)
150 | end
151 | end
152 |
153 | Beaglebone::set_pin_status(pin, :thread, thread)
154 | end
155 |
156 | # Runs a callback once after voltage crosses a specified threshold.
157 | # Convenience method for run_on_threshold
158 | # @see #run_on_threshold
159 | def run_once_on_threshold(callback, pin, mv_lower, mv_upper, mv_reset=10, interval=0.01)
160 | run_on_threshold(callback, pin, mv_lower, mv_upper, mv_reset, interval, 1)
161 | end
162 |
163 | # noinspection RubyScope
164 |
165 | # Runs a callback after voltage changes beyond a certain threshold.
166 | # This creates a new thread that runs in the background and polls at specified interval.
167 | # When the voltage crosses the specified thresholds the callback is run.
168 | #
169 | # This method should take 6 arguments:
170 | # the pin, the previous voltage, the current voltage, the previous state, the current state, and the counter
171 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
172 | # @param mv_lower an integer specifying the lower threshold voltage
173 | # @param mv_upper an integer specifying the upper threshold voltage
174 | # @param mv_reset an integer specifying the range in mv required to reset the threshold trigger
175 | # @param interval a number representing the wait time between polling
176 | # @param mv_last is optional and specifies the voltage to use as the initial point to measure change
177 | # @param state_last is optional and specifies the state to use as the initial state to watch change
178 | #
179 | # @example
180 | # # This polls every 0.01 seconds and will run after a the voltage crosses 400mv or 1200mv.
181 | # # Voltage will have to cross a range by at least 5mv to prevent rapidly triggering events
182 | # callback = lambda { |pin, mv_last, mv, state_last, state, count|
183 | # puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
184 | # }
185 | # AIN.run_on_threshold(callback, :P9_33, 400, 1200, 5, 0.01)
186 | def wait_for_threshold(pin, mv_lower, mv_upper, mv_reset=10, interval=0.01, mv_last=nil, state_last=nil)
187 | Beaglebone::check_valid_pin(pin, :analog)
188 | raise ArgumentError, "mv_upper needs to be between 0 and 1800: #{pin} (#{mv_upper})" unless (0..1800).include?(mv_upper)
189 | raise ArgumentError, "mv_lower needs to be between 0 and 1800: #{pin} (#{mv_lower})" unless (0..1800).include?(mv_lower)
190 | raise ArgumentError, "mv_lower needs to be <= mv_upper: #{pin} (#{mv_lower}:#{mv_upper})" unless mv_lower <= mv_upper
191 | raise ArgumentError, "mv_reset needs to be between 0 and 1800: #{pin} (#{mv_reset})" unless (0..1800).include?(mv_reset)
192 |
193 | #ensure we're the only ones waiting for this trigger
194 | if Beaglebone::get_pin_status(pin, :thread) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
195 | raise StandardError, "Already waiting for change on pin: #{pin}"
196 | end
197 |
198 | if Beaglebone::get_pin_status(pin, :waiting) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
199 | raise StandardError, "Already waiting for change on pin: #{pin}"
200 | end
201 |
202 | Beaglebone::set_pin_status(pin, :waiting, true)
203 |
204 | mv_last = read(pin) unless mv_last
205 |
206 | if mv_last >= mv_upper
207 | state_last = :HIGH
208 | elsif mv_last <= mv_lower
209 | state_last = :LOW
210 | else
211 | state_last = :MID
212 | end unless state_last
213 |
214 | state = :UNKNOWN
215 | count = 0
216 | loop do
217 | mv = read(pin)
218 |
219 | if state_last == :LOW
220 | #state remains low unless it crosses into high, or above mv_low + mv_reset
221 | if mv >= mv_upper && mv >= mv_lower + mv_reset
222 | state = :HIGH
223 | elsif mv >= mv_lower + mv_reset
224 | state = :MID
225 | else
226 | state = :LOW
227 | end
228 | elsif state_last == :HIGH
229 | #state remains high unless it crosses into low, or below mv_high - mv_reset
230 | if mv <= mv_lower && mv <= mv_upper - mv_reset
231 | state = :LOW
232 | elsif mv <= mv_upper - mv_reset
233 | state = :MID
234 | else
235 | state = :HIGH
236 | end
237 | elsif state_last == :MID
238 | #state changes from normal by crossing into upper or lower
239 | if mv >= mv_upper
240 | state = :HIGH
241 | elsif mv <= mv_lower
242 | state = :LOW
243 | else
244 | state = :MID
245 | end
246 | end
247 |
248 | #if we've detected a change of state
249 | if state != state_last
250 | Beaglebone::delete_pin_status(pin, :waiting)
251 | return [ mv_last, mv, state_last, state, count ]
252 | end
253 |
254 | sleep interval
255 |
256 | count += 1
257 | end
258 |
259 | Beaglebone::delete_pin_status(pin, :waiting)
260 | [ mv_last, -1, state_last, state_last, count ]
261 |
262 | end
263 |
264 | # Returns when voltage changes by specified amount
265 | #
266 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
267 | # @param mv_change an integer specifying the required change in mv
268 | # @param interval a number representing the wait time between polling
269 | # @param mv_last is optional and specifies the voltage to use as the initial point to measure change
270 | #
271 | # @example
272 | # # This will poll every P9_33 every 0.01 seconds until 10mv of change is detected
273 | # # This method will return the initial reading, final reading, and how many times it polled
274 | # AIN.wait_for_change(:P9_33, 10, 0.01) => [ 1200, 1210, 4]
275 | def wait_for_change(pin, mv_change, interval, mv_last=nil)
276 |
277 | Beaglebone::check_valid_pin(pin, :analog)
278 | raise ArgumentError, "mv_change needs to be between 0 and 1800: #{pin} (#{mv_change})" unless (0..1800).include?(mv_change)
279 |
280 | #ensure we're the only ones waiting for this trigger
281 | if Beaglebone::get_pin_status(pin, :thread) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
282 | raise StandardError, "Already waiting for change on pin: #{pin}"
283 | end
284 |
285 | if Beaglebone::get_pin_status(pin, :waiting) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
286 | raise StandardError, "Already waiting for change on pin: #{pin}"
287 | end
288 |
289 |
290 | Beaglebone::set_pin_status(pin, :waiting, true)
291 | mv_last = read(pin) unless mv_last
292 |
293 | change_max = [mv_last - 0, 1799 - mv_last].max
294 |
295 | mv_change = change_max if mv_change > change_max
296 |
297 | count = 0
298 | loop do
299 | mv = read(pin)
300 |
301 | #if we've detected the change or hit the edge of the range
302 | if (mv - mv_last).abs >= mv_change
303 |
304 | Beaglebone::delete_pin_status(pin, :waiting)
305 | return [ mv_last, mv, count ]
306 | end
307 |
308 | sleep interval
309 |
310 | count += 1
311 | end
312 |
313 | Beaglebone::delete_pin_status(pin, :waiting)
314 | [ mv_last, -1, count ]
315 | end
316 |
317 | # Stops any threads waiting for data on specified pin
318 | #
319 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
320 | def stop_wait(pin)
321 | thread = Beaglebone::get_pin_status(pin, :thread)
322 |
323 | thread.exit if thread
324 | thread.join if thread
325 | end
326 |
327 | # Return an array of AIN pins in use
328 | #
329 | # @return [Array]
330 | #
331 | # @example
332 | # AIN.get_analog_pins => [:P9_33, :P9_34]
333 | def get_analog_pins
334 | Beaglebone.pinstatus.clone.select { |x,y| x if y[:type] == :analog}.keys
335 | end
336 |
337 | # Disable an analog pin
338 | #
339 | # @param pin should be a symbol representing the header pin
340 | def disable_analog_pin(pin)
341 | Beaglebone::check_valid_pin(pin, :analog)
342 | Beaglebone::delete_pin_status(pin)
343 | end
344 |
345 | # Disable all analog pins
346 | def cleanup
347 | #reset all GPIO we've used to IN and unexport them
348 | get_analog_pins.each { |x| disable_analog_pin(x) }
349 | end
350 |
351 | end
352 | end
353 |
354 | # Object Oriented AIN Implementation.
355 | # This treats the pin as an object.
356 | class AINPin
357 | # Initialize a Analog pin
358 | # Return's an AINPin object
359 | #
360 | # @example
361 | # p9_33 = AINPin.new(:P9_33)
362 | def initialize(pin)
363 | @pin = pin
364 | end
365 |
366 | # Read from an analog pin
367 | #
368 | # @return [Integer] value in millivolts
369 | #
370 | # @example
371 | # p9_33 = AINPin.new(:P9_33)
372 | # p9_33.read => 1799
373 | def read
374 | AIN::read(@pin)
375 | end
376 |
377 | # Runs a callback after voltage changes by specified amount.
378 | # This creates a new thread that runs in the background and polls at specified interval.
379 | #
380 | # @param callback A method to call when the change is detected
381 | # This method should take 4 arguments: the pin, the previous voltage, the current voltage, and the counter
382 | # @param mv_change an integer specifying the required change in mv
383 | # @param interval a number representing the wait time between polling
384 | # @param repeats is optional and specifies the number of times the callback will be run
385 | #
386 | # @example
387 | # # This polls every 0.1 seconds and will run after a 10mv change is detected
388 | # callback = lambda { |pin, mv_last, mv, count| puts "[#{count}] #{pin} #{mv_last} -> #{mv}" }
389 | # p9_33 = AINPin.new(:P9_33)
390 | # p9_33.run_on_change(callback, 10, 0.1)
391 | def run_on_change(callback, mv_change=10, interval=0.01, repeats=nil)
392 | AIN::run_on_change(callback, @pin, mv_change, interval, repeats)
393 | end
394 |
395 | # Runs a callback once after specified change in voltage detected
396 | # Convenience method for run_on_change
397 | def run_once_on_change(callback, mv_change=10, interval=0.01)
398 | AIN::run_once_on_change(callback, @pin, mv_change, interval)
399 | end
400 |
401 |
402 | # Runs a callback after voltage changes beyond a certain threshold.
403 | # This creates a new thread that runs in the background and polls at specified interval.
404 | # When the voltage crosses the specified thresholds the callback is run.
405 | #
406 | # @param callback A method to call when the change is detected. This method should take 6 arguments: the pin, the previous voltage, the current voltage, the previous state, the current state, and the counter
407 | # @param mv_lower an integer specifying the lower threshold voltage
408 | # @param mv_upper an integer specifying the upper threshold voltage
409 | # @param mv_reset an integer specifying the range in mv required to reset the threshold trigger
410 | # @param interval a number representing the wait time between polling
411 | # @param repeats is optional and specifies the number of times the callback will be run
412 | #
413 | # @example
414 | # # This polls every 0.01 seconds and will run after a the voltage crosses 400mv or 1200mv.
415 | # # Voltage will have to cross a range by at least 5mv to prevent rapidly triggering events
416 | # callback = lambda { |pin, mv_last, mv, state_last, state, count|
417 | # puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
418 | # }
419 | # p9_33 = AINPin.new(:P9_33)
420 | # p9_33.run_on_threshold(callback, 400, 1200, 5, 0.01)
421 | def run_on_threshold(callback, mv_lower, mv_upper, mv_reset=10, interval=0.01, repeats=nil)
422 | AIN::run_on_threshold(callback, @pin, mv_lower, mv_upper, mv_reset, interval, repeats)
423 | end
424 |
425 |
426 | # Runs a callback once after voltage crosses a specified threshold.
427 | # Convenience method for run_on_threshold
428 | def run_once_on_threshold(callback, mv_lower, mv_upper, mv_reset=10, interval=0.01)
429 | AIN::run_once_on_threshold(callback, @pin, mv_lower, mv_upper, mv_reset, interval)
430 | end
431 |
432 | # Returns when voltage changes by specified amount
433 | # @param mv_lower an integer specifying the lower threshold voltage
434 | # @param mv_upper an integer specifying the upper threshold voltage
435 | # @param mv_reset an integer specifying the range in mv required to reset the threshold trigger
436 | # @param interval a number representing the wait time between polling
437 | # @param mv_last is optional and specifies the voltage to use as the initial point to measure change
438 | # @param state_last is optional and specifies the state to use as the initial state to watch change
439 | #
440 | # @example
441 | # # This polls every 0.01 seconds and will run after a the voltage crosses 400mv or 1200mv.
442 | # # Voltage will have to cross a range by at least 5mv to prevent rapidly triggering events
443 | # callback = lambda { |pin, mv_last, mv, state_last, state, count|
444 | # puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
445 | # }
446 | # p9_33 = AINPin.new(:P9_33)
447 | # p9_33.wait_for_threshold(400, 1200, 5, 0.01)
448 | def wait_for_threshold(mv_lower, mv_upper, mv_reset=10, interval=0.01, mv_last=nil, state_last=nil)
449 | AIN::wait_for_threshold(@pin, mv_lower, mv_upper, mv_reset, interval, mv_last, state_last)
450 | end
451 |
452 | # Returns when voltage changes by specified amount
453 | #
454 | # @param mv_change an integer specifying the required change in mv
455 | # @param interval a number representing the wait time between polling
456 | # @param mv_last is optional and specifies the voltage to use as the initial point to measure change
457 | #
458 | # @example
459 | # # This will poll every P9_33 every 0.01 seconds until 10mv of change is detected
460 | # # This method will return the initial reading, final reading, and how many times it polled
461 | # p9_33 = AINPin.new(:P9_33)
462 | # p9_33.wait_for_change(10, 0.01) => [ 1200, 1210, 4]
463 | def wait_for_change(mv_change, interval, mv_last=nil)
464 | AIN::wait_for_change(@pin, mv_change, interval, mv_last)
465 | end
466 |
467 | # Stops any threads waiting for data on this pin
468 | def stop_wait
469 | AIN::stop_wait(@pin)
470 | end
471 |
472 | # Disable analog pin
473 | def disable_analog_pin
474 | AIN::disable_analog_pin(@pin)
475 | end
476 |
477 | end
478 | end
479 |
--------------------------------------------------------------------------------
/lib/beaglebone/beaglebone.rb:
--------------------------------------------------------------------------------
1 | # This is the main module for this gem. You generally do not want to call these methods directly.
2 | module Beaglebone
3 | # Hash of pins and their uses
4 | PINS = {
5 | :USR0 => { :gpio => 53, :led => 'usr0' },
6 | :USR1 => { :gpio => 54, :led => 'usr1' },
7 | :USR2 => { :gpio => 55, :led => 'usr2' },
8 | :USR3 => { :gpio => 56, :led => 'usr3' },
9 |
10 | :P8_1 => { :dgnd => 'Digital Ground' },
11 | :P8_2 => { :dgnd => 'Digital Ground' },
12 |
13 | :P8_3 => { :gpio => 38, :gpiofunc => 'gpio1_6', :muxoffset => '0x018', :mmc => 'mmc1_dat6' },
14 | :P8_4 => { :gpio => 39, :gpiofunc => 'gpio1_7', :muxoffset => '0x01c', :mmc => 'mmc1_dat7' },
15 | :P8_5 => { :gpio => 34, :gpiofunc => 'gpio1_2', :muxoffset => '0x008', :mmc => 'mmc1_dat2' },
16 | :P8_6 => { :gpio => 35, :gpiofunc => 'gpio1_3', :muxoffset => '0x00c', :mmc => 'mmc1_dat3' },
17 |
18 | :P8_7 => { :gpio => 66, :gpiofunc => 'gpio2_2', :muxoffset => '0x090', :timer => 'timer4' },
19 | :P8_8 => { :gpio => 67, :gpiofunc => 'gpio2_3', :muxoffset => '0x094', :timer => 'timer7' },
20 | :P8_9 => { :gpio => 69, :gpiofunc => 'gpio2_5', :muxoffset => '0x09c', :timer => 'timer5' },
21 | :P8_10 => { :gpio => 68, :gpiofunc => 'gpio2_4', :muxoffset => '0x098', :timer => 'timer6' },
22 |
23 | :P8_11 => { :gpio => 45, :gpiofunc => 'gpio1_13', :muxoffset => '0x034' },
24 | :P8_12 => { :gpio => 44, :gpiofunc => 'gpio1_12', :muxoffset => '0x030' },
25 |
26 | # You can emable PWM as listed below
27 | # P8_13 *OR* P8_19 (EHRPWM2B, EHRPWM2A),
28 | # P9_14 *OR* P9_16 (EHRPWM1A, EHRPWM1B),
29 | # P9_21 *OR* P9_22 (EHRPWM0B, EHRPWM0A).
30 | # there are also ecap pwms on pins P9_28 and P9_42
31 |
32 | :P8_13 => { :gpio => 23, :gpiofunc => 'gpio0_23', :muxoffset => '0x024', :pwm => 'pwm_2b', :pwm_id => 2, :pwm_mux => 4 },
33 |
34 | :P8_14 => { :gpio => 26, :gpiofunc => 'gpio0_26', :muxoffset => '0x028' },
35 | :P8_15 => { :gpio => 47, :gpiofunc => 'gpio1_15', :muxoffset => '0x03c' },
36 | :P8_16 => { :gpio => 46, :gpiofunc => 'gpio1_14', :muxoffset => '0x038' },
37 | :P8_17 => { :gpio => 27, :gpiofunc => 'gpio0_27', :muxoffset => '0x02c' },
38 | :P8_18 => { :gpio => 65, :gpiofunc => 'gpio2_1', :muxoffset => '0x08c' },
39 |
40 | :P8_19 => { :gpio => 22, :gpiofunc => 'gpio0_22', :muxoffset => '0x020', :pwm => 'pwm_2a', :pwm_id => 2, :pwm_mux => 4 },
41 |
42 | # You can only use the mmc pins if booting from SD and disabling mmc
43 | # mmc reset behavior is unclear
44 | # Best option is to not use the MMC1_CLK and MMC1_CMD signals at all and tie them low.
45 | :P8_20 => { :gpio => 63, :gpiofunc => 'gpio1_31', :muxoffset => '0x084', :mmc => 'mmc1_cmd' },
46 | :P8_21 => { :gpio => 62, :gpiofunc => 'gpio1_30', :muxoffset => '0x080', :mmc => 'mmc1_clk' },
47 | :P8_22 => { :gpio => 37, :gpiofunc => 'gpio1_5', :muxoffset => '0x014', :mmc => 'mmc1_dat5' },
48 | :P8_23 => { :gpio => 36, :gpiofunc => 'gpio1_4', :muxoffset => '0x010', :mmc => 'mmc1_dat4' },
49 | :P8_24 => { :gpio => 33, :gpiofunc => 'gpio1_1', :muxoffset => '0x004', :mmc => 'mmc1_dat1' },
50 | :P8_25 => { :gpio => 32, :gpiofunc => 'gpio1_0', :muxoffset => '0x000', :mmc => 'mmc1_dat0' },
51 |
52 | :P8_26 => { :gpio => 61, :gpiofunc => 'gpio1_29', :muxoffset => '0x07c' },
53 | :P8_27 => { :gpio => 86, :gpiofunc => 'gpio2_22', :muxoffset => '0x0e0', :lcd => 'lcd_vsync' },
54 | :P8_28 => { :gpio => 88, :gpiofunc => 'gpio2_24', :muxoffset => '0x0e8', :lcd => 'lcd_pclk' },
55 | :P8_29 => { :gpio => 87, :gpiofunc => 'gpio2_23', :muxoffset => '0x0e4', :lcd => 'lcd_hsync' },
56 | :P8_30 => { :gpio => 89, :gpiofunc => 'gpio2_25', :muxoffset => '0x0ec', :lcd => 'lcd_ac_bias' },
57 | :P8_31 => { :gpio => 10, :gpiofunc => 'gpio0_10', :muxoffset => '0x0d8', :lcd => 'lcd_data14', :uart => 'uart5_ctsn', :uart_id => 5 },
58 | :P8_32 => { :gpio => 11, :gpiofunc => 'gpio0_11', :muxoffset => '0x0dc', :lcd => 'lcd_data15', :uart => 'uart5_rtsn', :uart_id => 5 },
59 | :P8_33 => { :gpio => 9, :gpiofunc => 'gpio0_9', :muxoffset => '0x0d4', :lcd => 'lcd_data13', :uart => 'uart4_rtsn', :uart_id => 4 },
60 | :P8_34 => { :gpio => 81, :gpiofunc => 'gpio2_17', :muxoffset => '0x0cc', :lcd => 'lcd_data11', :pwm => 'pwm_1b', :pwm_id => 1, :pwm_mux => 2, :uart => 'uart3_rtsn', :uart_id => 3 },
61 | :P8_35 => { :gpio => 8, :gpiofunc => 'gpio0_8', :muxoffset => '0x0d0', :lcd => 'lcd_data12', :uart => 'uart4_ctsn' },
62 | :P8_36 => { :gpio => 80, :gpiofunc => 'gpio2_16', :muxoffset => '0x0c8', :lcd => 'lcd_data10', :pwm => 'pwm_1a', :pwm_id => 1, :pwm_mux => 2, :uart => 'uart3_ctsn', :uart_id => 3 },
63 | :P8_37 => { :gpio => 78, :gpiofunc => 'gpio2_14', :muxoffset => '0x0c0', :lcd => 'lcd_data8', :uart => 'uart5_txd', :uart_id => 5 },
64 | :P8_38 => { :gpio => 79, :gpiofunc => 'gpio2_15', :muxoffset => '0x0c4', :lcd => 'lcd_data9', :uart => 'uart5_rxd', :uart_id => 5 },
65 | :P8_39 => { :gpio => 76, :gpiofunc => 'gpio2_12', :muxoffset => '0x0b8', :lcd => 'lcd_data6' },
66 | :P8_40 => { :gpio => 77, :gpiofunc => 'gpio2_13', :muxoffset => '0x0bc', :lcd => 'lcd_data7' },
67 | :P8_41 => { :gpio => 74, :gpiofunc => 'gpio2_10', :muxoffset => '0x0b0', :lcd => 'lcd_data4' },
68 | :P8_42 => { :gpio => 75, :gpiofunc => 'gpio2_11', :muxoffset => '0x0b4', :lcd => 'lcd_data5' },
69 | :P8_43 => { :gpio => 72, :gpiofunc => 'gpio2_8', :muxoffset => '0x0a8', :lcd => 'lcd_data2' },
70 | :P8_44 => { :gpio => 73, :gpiofunc => 'gpio2_9', :muxoffset => '0x0ac', :lcd => 'lcd_data3' },
71 | :P8_45 => { :gpio => 70, :gpiofunc => 'gpio2_6', :muxoffset => '0x0a0', :lcd => 'lcd_data0', :pwm => 'pwm_2a', :pwm_id => 2, :pwm_mux => 3 },
72 | :P8_46 => { :gpio => 71, :gpiofunc => 'gpio2_7', :muxoffset => '0x0a4', :lcd => 'lcd_data1', :pwm => 'pwm_2b', :pwm_id => 2, :pwm_mux => 3 },
73 |
74 | :P9_1 => { :dgnd => 'ground' },
75 | :P9_2 => { :dgnd => 'ground' },
76 | :P9_3 => { :vdd_3v3 => '3.3 volts' },
77 | :P9_4 => { :vdd_3v3 => '3.3 volts' },
78 | :P9_5 => { :vdd_5v => '5 volts' },
79 | :P9_6 => { :vdd_5v => '5 volts' },
80 | :P9_7 => { :sys_5v => '5 volts' },
81 | :P9_8 => { :sys_5v => '5 volts' },
82 | :P9_9 => { :pwr_but => 'power button' },
83 | :P9_10 => { :sys_resetn => 'reset button' },
84 |
85 | :P9_11 => { :gpio => 30, :gpiofunc => 'gpio0_30', :muxoffset => '0x070', :uart => 'uart4_rxd', :uart_id => 4 },
86 | :P9_12 => { :gpio => 60, :gpiofunc => 'gpio1_28', :muxoffset => '0x078' },
87 | :P9_13 => { :gpio => 31, :gpiofunc => 'gpio0_31', :muxoffset => '0x074', :uart => 'uart4_txd', :uart_id => 4 },
88 | :P9_14 => { :gpio => 50, :gpiofunc => 'gpio1_18', :muxoffset => '0x048', :pwm => 'pwm_1a', :pwm_id => 1, :pwm_mux => 6 },
89 | :P9_15 => { :gpio => 48, :gpiofunc => 'gpio1_16', :muxoffset => '0x040' },
90 | :P9_16 => { :gpio => 51, :gpiofunc => 'gpio1_19', :muxoffset => '0x04c', :pwm => 'pwm_1b', :pwm_id => 1, :pwm_mux => 6 },
91 | :P9_17 => { :gpio => 5, :gpiofunc => 'gpio0_5', :muxoffset => '0x15c', :i2c => 'i2c1_scl', :i2c_id => 1, :spi => 'spi0_cs0', :spi_id => 0 },
92 | :P9_18 => { :gpio => 4, :gpiofunc => 'gpio0_4', :muxoffset => '0x158', :i2c => 'i2c1_sda', :i2c_id => 1, :spi => 'spi0_d1', :spi_id => 0 },
93 | :P9_19 => { :i2c => 'i2c2_scl', :i2c_id => 2, :uart => 'uart1_rtsn', :uart_id => 1, :spi => 'spi1_cs1', :spi_id => 1 },
94 | :P9_20 => { :i2c => 'i2c2_sda', :i2c_id => 2, :uart => 'uart1_ctsn', :uart_id => 1, :spi => 'spi1_cs0', :spi_id => 1 },
95 | :P9_21 => { :gpio => 3, :gpiofunc => 'gpio0_3', :muxoffset => '0x154', :pwm => 'pwm_0b', :pwm_id => 0, :pwm_mux => 3, :i2c => 'i2c2_scl', :i2c_id => 2, :uart => 'uart2_txd', :uart_id => 2, :spi => 'spi0_d0', :spi_id => 0 },
96 | :P9_22 => { :gpio => 2, :gpiofunc => 'gpio0_2', :muxoffset => '0x150', :pwm => 'pwm_0a', :pwm_id => 0, :pwm_mux => 3, :i2c => 'i2c2_sda', :i2c_id => 2, :uart => 'uart2_rxd', :uart_id => 2, :spi => 'spi0_sclk', :spi_id => 0 },
97 | :P9_23 => { :gpio => 49, :gpiofunc => 'gpio1_17', :muxoffset => '0x044' },
98 | :P9_24 => { :gpio => 15, :gpiofunc => 'gpio0_15', :muxoffset => '0x184', :i2c => 'i2c1_scl', :i2c_id => 1, :uart => 'uart1_txd', :uart_id => 1 },
99 | :P9_25 => { :gpio => 117, :gpiofunc => 'gpio3_21', :muxoffset => '0x1ac', :mcasp => 'mcasp0_ahclkx' },
100 | :P9_26 => { :gpio => 14, :gpiofunc => 'gpio0_14', :muxoffset => '0x180', :i2c => 'i2c1_sda', :i2c_id => 2, :uart => 'uart1_rxd', :uart_id => 1 },
101 | :P9_27 => { :gpio => 115, :gpiofunc => 'gpio3_19', :muxoffset => '0x1a4' },
102 | :P9_28 => { :gpio => 113, :gpiofunc => 'gpio3_17', :muxoffset => '0x19c', :pwm => 'ecappwm2', :pwm_id => 3, :pwm_mux => 4, :ecap => 2, :spi => 'spi1_cs0', :spi_id => 1, :mcasp => 'mcasp0_ahclkr' },
103 | :P9_29 => { :gpio => 111, :gpiofunc => 'gpio3_15', :muxoffset => '0x194', :pwm => 'pwm_0b', :pwm_id => 0, :pwm_mux => 1, :spi => 'spi1_d0', :spi_id => 1, :mcasp => 'mcasp0_fsx' },
104 | :P9_30 => { :gpio => 112, :gpiofunc => 'gpio3_16', :muxoffset => '0x198', :spi => 'spi1_d1', :spi_id => 1 },
105 | :P9_31 => { :gpio => 110, :gpiofunc => 'gpio3_14', :muxoffset => '0x190', :pwm => 'pwm_0a', :pwm_id => 0, :pwm_mux => 1, :spi => 'spi1_sclk', :spi_id => 1, :mcasp => 'mcasp0_aclkx' },
106 |
107 | :P9_32 => { :vdd_adc => 'analog output 1.8v' },
108 | :P9_33 => { :analog => 4 },
109 | :P9_34 => { :gnda_adc => 'analog ground' },
110 | :P9_35 => { :analog => 6 },
111 | :P9_36 => { :analog => 5 },
112 | :P9_37 => { :analog => 2 },
113 | :P9_38 => { :analog => 3 },
114 | :P9_39 => { :analog => 0 },
115 | :P9_40 => { :analog => 1 },
116 |
117 | :P9_41 => { :gpio => 20, :gpiofunc => 'gpio0_20', :muxoffset => '0x1b4' },
118 | :P9_42 => { :gpio => 7, :gpiofunc => 'gpio0_7', :muxoffset => '0x164', :pwm => 'ecappwm0', :pwm_id => 4, :pwm_mux => 0, :ecap => 0, :uart => 'uart3_txd', :uart_id => 3, :spi => 'spi1_sclk', :spi_id => 1 },
119 | :P9_43 => { :dgnd => 'ground' },
120 | :P9_44 => { :dgnd => 'ground' },
121 | :P9_45 => { :dgnd => 'ground' },
122 | :P9_46 => { :dgnd => 'ground' },
123 | }.freeze
124 |
125 | # Generic device trees
126 | TREES = {
127 | :GPIO => { :global => nil, :pin => 'GPIO_' },
128 | :UART => { :global => nil, :pin => 'BB-UART' },
129 | :ADC => { :global => 'BB-ADC', :pin => nil },
130 | :PWM => { :global => 'am33xx_pwm', :pin => 'bone_pwm_' },
131 | }.freeze
132 |
133 | # UART device hash
134 | UARTS = {
135 | :UART1 => { :id => 1, :rx => :P9_26, :tx => :P9_24, :dev => '/dev/ttyO1' },
136 | :UART2 => { :id => 2, :rx => :P9_22, :tx => :P9_21, :dev => '/dev/ttyO2' },
137 | :UART3 => { :id => 3, :rx => nil, :tx => :P9_42, :dev => '/dev/ttyO3' },
138 | :UART4 => { :id => 4, :rx => :P9_11, :tx => :P9_13, :dev => '/dev/ttyO4' },
139 | :UART5 => { :id => 5, :rx => :P8_38, :tx => :P8_37, :dev => '/dev/ttyO5' },
140 | }.freeze
141 |
142 | # I2C device hash
143 | I2CS = {
144 | :I2C0 => { :id => 0, :dev => '/dev/i2c-0' },
145 | :I2C1 => { :id => 2, :dev => '/dev/i2c-2', :scl => :P9_17, :sda => :P9_18, :devicetree => 'BB-I2C1' },
146 | :I2C2 => { :id => 1, :dev => '/dev/i2c-1', :scl => :P9_19, :sda => :P9_20 },
147 | #alternate pins for i2c1
148 | :I2C1A => { :id => 2, :dev => '/dev/i2c-2', :scl => :P9_24, :sda => :P9_26, :devicetree => 'BB-I2C1A1' },
149 | }.freeze
150 |
151 | # SPI device hash
152 | SPIS = {
153 | :counter => 1,
154 | :SPI0 => { :id => 0, :dev => '/dev/spidev', :devicetree => 'BB-SPIDEV0',
155 | :cs0 => :P9_17, :sclk => :P9_22, :d0 => :P9_21, :d1 => :P9_18,
156 | :pins => [ :P9_17, :P9_18, :P9_21, :P9_22 ] },
157 |
158 | :SPI1 => { :id => 1, :dev => '/dev/spidev', :devicetree => 'BB-SPIDEV1',
159 | :cs0 => :P9_28, :sclk => :P9_31, :d0 => :P9_29, :d1 => :P9_30,
160 | :pins => [ :P9_28, :P9_29, :P9_30, :P9_31 ] },
161 |
162 | #alternate pins for SPI2
163 | :SPI1A => { :id => 1, :dev => '/dev/spidev', :devicetree => 'BB-SPIDEV1A1',
164 | :cs0 => :P9_20, :sclk => :P9_42, :d0 => :P9_29, :d1 => :P9_30,
165 | :pins => [ :P9_20, :P9_29, :P9_30, :P9_42 ] },
166 |
167 | }
168 |
169 | @pinstatus = {}
170 | @pinmutex = Mutex.new
171 | @loaded_dtbs = []
172 |
173 | class << self
174 | attr_accessor :pinstatus, :pinmutex, :loaded_dtbs
175 |
176 | # @private
177 | # get hash entry for pin
178 | def get_pin_status(pin, key = nil)
179 | pinmutex.synchronize do
180 | if key
181 | pinstatus[pin] ? pinstatus[pin][key] : nil
182 | else
183 | pinstatus[pin]
184 | end
185 | end
186 | end
187 |
188 | # @private
189 | # set hash entry for pin
190 | def set_pin_status(pin, key, value)
191 | pinmutex.synchronize do
192 | pinstatus[pin] ||= {}
193 | pinstatus[pin][key] = value
194 | end
195 | end
196 |
197 | # @private
198 | # delete pin's hash entry
199 | def delete_pin_status(pin, key = nil)
200 | pinmutex.synchronize do
201 | if key.nil?
202 | pinstatus.delete(pin)
203 | else
204 | pinstatus[pin].delete(key) if pinstatus[pin]
205 | end
206 | end
207 | end
208 |
209 | # disable pin
210 | def disable_pin(pin)
211 | status = get_pin_status(pin)
212 |
213 | if status
214 | case status[:type]
215 | when :gpio
216 | Beaglebone::GPIO.disable_gpio_pin(pin)
217 | when :pwm
218 | Beaglebone::PWM.disable_pwm_pin(pin)
219 | else
220 | #we can't disable any other pin types at this time
221 | raise StandardError, "Cannot disable pin: #{pin} in #{status[:type]} mode"
222 | end
223 | end
224 | end
225 |
226 | # check if a pin of given type is valid
227 | def check_valid_pin(pin, type = nil)
228 | #check to see if pin exists
229 | raise ArgumentError, "No such PIN: #{pin.to_s}" unless PINS[pin]
230 |
231 | if type
232 | raise StandardError, "Pin does not support #{type}: #{pin.to_s}" unless PINS[pin][type]
233 | end
234 | end
235 |
236 | # return capemgr directory
237 | def get_capemgr_dir
238 | Dir.glob([ '/sys/devices/bone_capemgr.*', '/sys/devices/platform/bone_capemgr' ]).first
239 | end
240 |
241 | # check if device tree is loaded
242 | def device_tree_loaded?(name)
243 | !!File.open("#{get_capemgr_dir}/slots").read.match(/,#{name}$/)
244 | end
245 |
246 | # load a device tree
247 | def device_tree_load(name, delay=0.25)
248 | return true if loaded_dtbs.include?(name)
249 |
250 | if device_tree_loaded?(name)
251 | loaded_dtbs << name
252 | return true
253 | end
254 |
255 | File.open("#{get_capemgr_dir}/slots", 'w') { |f| f.write(name) }
256 | sleep delay
257 | raise StandardError, "Unable to load device tree: #{name}" unless device_tree_loaded?(name)
258 | true
259 | end
260 |
261 | # unload a device tree, return false if not loaded, return true if it unloads
262 | def device_tree_unload(name)
263 | return false unless device_tree_loaded?(name)
264 |
265 | dtb_id = File.open("#{get_capemgr_dir}/slots", 'r').read.scan(/^ ?(\d+): .*?,#{name}/).flatten.first
266 |
267 | File.open("#{get_capemgr_dir}/slots", 'w') { |f| f.write("-#{dtb_id}") }
268 |
269 | raise StandardError, "Unable to unload device tree: #{name}" if device_tree_loaded?(name)
270 |
271 | true
272 | end
273 |
274 | # cleanup all the things
275 | def cleanup
276 | Beaglebone::AIN.cleanup
277 | Beaglebone::PWM.cleanup
278 | Beaglebone::GPIO.cleanup
279 | Beaglebone::UART.cleanup
280 | Beaglebone::I2C.cleanup
281 | Beaglebone::SPI.cleanup
282 | end
283 | end
284 | end
285 |
286 |
--------------------------------------------------------------------------------
/lib/beaglebone/gpio.rb:
--------------------------------------------------------------------------------
1 | # == gpio.rb
2 | # This file contains the GPIO methods
3 |
4 | module Beaglebone #:nodoc:
5 | # == GPIO
6 | # procedural methods for GPIO control
7 | # == Summary
8 | # #pin_mode is called to initialize a pin.
9 | # Further basic functionality is available with #digital_read and #digital_write
10 | module GPIO
11 | class << self
12 | # GPIO modes
13 | MODES = [ :IN, :OUT ]
14 | # GPIO states
15 | STATES = { :HIGH => 1, :LOW => 0 }
16 | # Edge trigger options
17 | EDGES = [ :NONE, :RISING, :FALLING, :BOTH ]
18 | # Slew rates
19 | SLEWRATES = [ :SLOW, :FAST ]
20 | # pull modes
21 | PULLMODES = [ :PULLUP, :PULLDOWN, :NONE ]
22 |
23 | # dts template for GPIO pin
24 | GPIOTEMPLATE = '/*
25 | * This is a template-generated file
26 | */
27 |
28 | /dts-v1/;
29 | /plugin/;
30 |
31 | /{
32 | compatible = "ti,beaglebone", "ti,beaglebone-black";
33 | part_number = "BS_PINMODE_!PIN_KEY!_!DATA!";
34 |
35 | exclusive-use =
36 | "!PIN_DOT_KEY!",
37 | "!PIN_FUNCTION!";
38 |
39 | fragment@0 {
40 | target = <&am33xx_pinmux>;
41 | __overlay__ {
42 | bs_pinmode_!PIN_KEY!_!DATA!: pinmux_bs_pinmode_!PIN_KEY!_!DATA! {
43 | pinctrl-single,pins = ;
44 | };
45 | };
46 | };
47 |
48 | fragment@1 {
49 | target = <&ocp>;
50 | __overlay__ {
51 | bs_pinmode_!PIN_KEY!_!DATA!_pinmux {
52 | compatible = "bone-pinmux-helper";
53 | status = "okay";
54 | pinctrl-names = "default";
55 | pinctrl-0 = <&bs_pinmode_!PIN_KEY!_!DATA!>;
56 | };
57 | };
58 | };
59 | };
60 | '
61 | # Initialize a GPIO pin
62 | #
63 | # @param pin should be a symbol representing the header pin
64 | # @param mode should specify the mode of the pin, either :IN or :OUT
65 | # @param pullmode (optional) should specify the pull mode, :PULLUP, :PULLDOWN, or :NONE
66 | # @param slewrate (optional) should specify the slew rate, :FAST or :SLOW
67 | # @example
68 | # GPIO.pin_mode(:P9_12, :OUT)
69 | # GPIO.pin_mode(:P9_11, :IN, :PULLUP, :FAST)
70 | def pin_mode(pin, mode, pullmode = nil, slewrate = nil)
71 |
72 | #make sure a valid mode was passed
73 | check_valid_mode(mode)
74 |
75 | #make sure a valid pin was passed and that it supports GPIO
76 | Beaglebone::check_valid_pin(pin, :gpio)
77 |
78 | #get info from PINS hash
79 | pininfo = PINS[pin]
80 |
81 | #if pin is enabled for something else, disable it
82 | if Beaglebone::get_pin_status(pin) && Beaglebone::get_pin_status(pin, :type) != :gpio
83 | Beaglebone::disable_pin(pin)
84 | end
85 |
86 | pullmode = pullmode || :PULLUP
87 | slewrate = slewrate || :FAST
88 |
89 | raise ArgumentError, "Invalid Slew Rate (#{slewrate}) specified on: #{pin}" unless SLEWRATES.include?(slewrate)
90 | raise ArgumentError, "Invalid Pull Mode (#{pullmode}) specified on: #{pin}" unless PULLMODES.include?(pullmode)
91 |
92 | if mode == :IN and pullmode != :PULLUP and ( pininfo[:mmc] or pin == :P9_15 )
93 | raise ArgumentError, "Invalid Pull mode specified for pin: #{pin} (#{pullmode})"
94 | end
95 |
96 | #export pin unless its an on board LED, if it isn't already exported
97 | if pininfo[:led]
98 | raise StandardError, "LEDs only support OUT mode: #{pin.to_s}" unless mode == :OUT
99 | File.open("#{gpio_directory(pin)}/trigger", 'w') { |f| f.write('gpio') }
100 | else
101 | # if pin is not an onboard LED
102 |
103 | # create device tree overlay for this pin, do not force rebuild
104 | pin_data = create_device_tree(pin, mode, pullmode, slewrate, false)
105 |
106 | # unload previous dtb if loaded
107 | begin
108 | Beaglebone::device_tree_unload("#{TREES[:GPIO][:pin]}#{pin}_.*")
109 | rescue
110 | #
111 | end
112 |
113 | # load device tree overlay
114 | Beaglebone::device_tree_load("#{TREES[:GPIO][:pin]}#{pin}_0x#{pin_data.to_s(16)}")
115 |
116 | # export gpio pin
117 | begin
118 | File.open('/sys/class/gpio/export', 'w') { |f| f.write pininfo[:gpio] }
119 | rescue
120 | #
121 | end
122 |
123 | #check to see if pin is GPIO enabled in /sys/class/gpio/
124 | raise StandardError, "GPIO was unable to initalize pin: #{pin.to_s}" unless enabled?(pin)
125 |
126 | end unless Beaglebone::get_pin_status(pin, :type) == :gpio
127 |
128 | #set pin mode
129 | unless pininfo[:led]
130 | set_gpio_mode(pin, mode)
131 | dir = read_gpio_direction(pin)
132 | raise StandardError, "GPIO was unable to set mode: #{pin.to_s} to #{mode.to_s} (#{dir})" if mode != dir
133 | end
134 |
135 | Beaglebone::set_pin_status(pin, :mode, mode)
136 | end
137 |
138 | # Sets a pin's output state
139 | #
140 | # @param pin should be a symbol representing the header pin
141 | # @param state should be a symbol representin the state, :HIGH or :LOW
142 | #
143 | # @example
144 | # GPIO.digital_write(:P9_12, :HIGH)
145 | # GPIO.digital_write(:P9_12, :LOW)
146 | def digital_write(pin, state)
147 | check_valid_state(state)
148 | check_gpio_enabled(pin)
149 |
150 | raise StandardError, "PIN not in GPIO OUT mode: #{pin}" unless get_gpio_mode(pin) == :OUT
151 |
152 | fd = get_value_fd(pin)
153 | fd.write STATES[state.to_sym].to_s
154 | fd.flush
155 | Beaglebone::set_pin_status(pin, :state, state)
156 | end
157 |
158 | # Reads a pin's input state and return that value
159 | #
160 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
161 | #
162 | # @return [Symbol] :HIGH or :LOW
163 | #
164 | # @example
165 | # GPIO.digital_read(:P9_11) => :HIGH
166 | def digital_read(pin)
167 | check_gpio_enabled(pin)
168 |
169 | raise StandardError, "PIN not in GPIO IN mode: #{pin}" unless get_gpio_mode(pin) == :IN
170 |
171 | fd = get_value_fd(pin)
172 | fd.rewind
173 | value = fd.read.to_s.strip
174 | state = STATES.key(value.to_i)
175 |
176 | Beaglebone::set_pin_status(pin, :state, state)
177 | end
178 |
179 | # Runs a callback on an edge trigger event.
180 | # This creates a new thread that runs in the background
181 | #
182 | # @param callback A method to call when the edge trigger is detected. This method should take 3 arguments, the pin, the edge, and the counter
183 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
184 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
185 | # @param timeout is optional and specifies a time window to wait
186 | # @param repeats is optional and specifies the number of times the callback will be run
187 | #
188 | # @example
189 | # GPIO.run_on_edge(lambda { |pin,edge,count| puts "[#{count}] #{pin} -- #{edge}" }, :P9_11, :RISING)
190 | def run_on_edge(callback, pin, edge, timeout = nil, repeats=nil)
191 |
192 | raise StandardError, "Already waiting for trigger on pin: #{pin}" if Beaglebone::get_pin_status(pin, :trigger)
193 | raise StandardError, "Already waiting for trigger on pin: #{pin}" if Beaglebone::get_pin_status(pin, :thread)
194 |
195 | thread = Thread.new(callback, pin, edge, timeout, repeats) do |c, p, e, t, r|
196 | begin
197 | count = 0
198 | loop do
199 |
200 | state = wait_for_edge(p, e, t, false)
201 |
202 | c.call(p, state, count) if c
203 | count += 1
204 | break if r && count >= r
205 | end
206 | rescue => ex
207 | puts ex
208 | puts ex.backtrace
209 | ensure
210 | cleanup_edge_trigger(p)
211 | end
212 | end
213 |
214 | Beaglebone::set_pin_status(pin, :thread, thread)
215 | end
216 |
217 | # Runs a callback one time on an edge trigger event.
218 | # This is a convenience method for run_on_edge
219 | # @see #run_on_edge
220 | def run_once_on_edge(callback, pin, edge, timeout = nil)
221 | run_on_edge(callback, pin, edge, timeout, 1)
222 | end
223 |
224 | # Stops any threads waiting for data on specified pin
225 | #
226 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
227 | def stop_edge_wait(pin)
228 | thread = Beaglebone::get_pin_status(pin, :thread)
229 |
230 | thread.exit if thread
231 | thread.join if thread
232 | end
233 |
234 | # Wait for an edge trigger.
235 | # Returns the type that triggered the event, e.g. :RISING, :FALLING, :BOTH
236 | #
237 | # @returns [Symbol] :RISING, :FALLING, or :BOTH
238 | #
239 | # @param pin should be a symbol representing the header pin, i.e. :P9_11
240 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
241 | # @param timeout is optional and specifies a time window to wait
242 | # @param disable is optional. If set, edge trigger detection is cleared on return
243 | #
244 | # @example
245 | # wait_for_edge(:P9_11, :RISING, 30) => :RISING
246 | def wait_for_edge(pin, edge, timeout = nil, disable=true)
247 | check_valid_edge(edge)
248 | raise ArgumentError, "Cannot wait for edge trigger NONE: #{pin}" if edge.to_sym == :NONE
249 |
250 | check_gpio_enabled(pin)
251 | raise StandardError, "PIN not in GPIO IN mode: #{pin}" unless get_gpio_mode(pin) == :IN
252 |
253 | #ensure we're the only ones waiting for this trigger
254 | if Beaglebone::get_pin_status(pin, :thread) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
255 | raise StandardError, "Already waiting for trigger on pin: #{pin}"
256 | end
257 |
258 | if Beaglebone::get_pin_status(pin, :trigger) && Beaglebone::get_pin_status(pin, :thread) != Thread.current
259 | raise StandardError, "Already waiting for trigger on pin: #{pin}"
260 | end
261 |
262 | set_gpio_edge(pin, edge)
263 |
264 | fd = get_value_fd(pin)
265 | fd.read
266 |
267 | #select will return fd into the error set "es" if it recieves an interrupt
268 | _, _, es = IO.select(nil, nil, [fd], timeout)
269 |
270 | set_gpio_edge(pin, :NONE) if disable
271 |
272 | es ? digital_read(pin) : nil
273 |
274 | end
275 |
276 | # Resets all the GPIO pins that we have used and unexport them
277 | def cleanup
278 | get_gpio_pins.each { |x| disable_gpio_pin(x) }
279 | end
280 |
281 | # Returns true if specified pin is enabled in GPIO mode, else false
282 | def enabled?(pin)
283 |
284 | return true if Beaglebone::get_pin_status(pin, :type) == :gpio
285 |
286 | return false unless valid?(pin)
287 | if Dir.exists?(gpio_directory(pin))
288 |
289 | Beaglebone::set_pin_status(pin, :type, :gpio)
290 | return true
291 | end
292 |
293 | false
294 | end
295 |
296 | # Sends data to a shift register
297 | #
298 | # @param latch_pin should be a symbol representing the header pin, i.e. :P9_12
299 | # @param clock_pin should be a symbol representing the header pin, i.e. :P9_13
300 | # @param data_pin should be a symbol representing the header pin, i.e. :P9_14
301 | # @param data Integer value to write to the shift register
302 | # @param lsb optional, send least significant bit first if set
303 | #
304 | # @example
305 | # GPIO.shift_out(:P9_11, :P9_12, :P9_13, 255)
306 | def shift_out(latch_pin, clock_pin, data_pin, data, lsb=nil)
307 | raise ArgumentError, "data must be > 0 (#{data})" if data < 0
308 | digital_write(latch_pin, :LOW)
309 |
310 | binary = data.to_s(2)
311 | pad = 8 - ( binary.size % 8 )
312 | binary = ( '0' * pad ) + binary if pad.between?(1,7)
313 |
314 | binary.reverse! if lsb
315 |
316 | binary.each_char do |bit|
317 | digital_write(clock_pin, :LOW)
318 | digital_write(data_pin, bit == '0' ? :LOW : :HIGH)
319 | digital_write(clock_pin, :HIGH)
320 | end
321 | digital_write(latch_pin, :HIGH)
322 |
323 | data
324 | end
325 |
326 | # Returns last known state from +pin+, reads state if unknown
327 | # @returns [Symbol] :HIGH or :LOW
328 | def get_gpio_state(pin)
329 | check_gpio_enabled(pin)
330 |
331 | state = Beaglebone::get_pin_status(pin, :state)
332 | return state if state
333 |
334 | digital_read(pin)
335 | end
336 |
337 | # Returns mode from +pin+, reads mode if unknown
338 | # @returns [Symbol] :IN or :OUT
339 | def get_gpio_mode(pin)
340 | check_gpio_enabled(pin)
341 |
342 | mode = Beaglebone::get_pin_status(pin, :mode)
343 | return mode if mode
344 |
345 | read_gpio_direction(pin)
346 | end
347 |
348 | # Set GPIO mode on an initialized pin
349 | #
350 | # @param pin should be a symbol representing the header pin
351 | # @param mode should specify the mode of the pin, either :IN or :OUT
352 | #
353 | # @example
354 | # GPIO.set_gpio_mode(:P9_12, :OUT)
355 | # GPIO.set_gpio_mode(:P9_11, :IN)
356 | def set_gpio_mode(pin, mode)
357 | Beaglebone::check_valid_pin(pin, :gpio)
358 | check_valid_mode(mode)
359 | check_gpio_enabled(pin)
360 |
361 | File.open("#{gpio_directory(pin)}/direction", 'w') { |f| f.write mode.to_s.downcase }
362 | Beaglebone::set_pin_status(pin, :mode, mode)
363 | end
364 |
365 | # Set GPIO edge trigger type on an initialized pin
366 | #
367 | # @param pin should be a symbol representing the header pin
368 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
369 | # @param force is optional, if set will set the mode even if already set
370 | #
371 | # @example
372 | # GPIO.set_gpio_edge(:P9_11, :RISING)
373 | def set_gpio_edge(pin, edge, force=nil)
374 | check_valid_edge(edge)
375 | Beaglebone::check_valid_pin(pin, :gpio)
376 |
377 | raise StandardError, "PIN not in GPIO IN mode: #{pin}" unless get_gpio_mode(pin) == :IN
378 |
379 | return if get_gpio_edge(pin) == edge && !force
380 |
381 | File.open("#{gpio_directory(pin)}/edge", 'w') { |f| f.write edge.to_s.downcase }
382 | testedge = read_gpio_edge(pin)
383 | if testedge != edge.to_s.downcase
384 | Beaglebone::delete_pin_status(pin, :trigger)
385 | raise StandardError, "GPIO was unable to set edge: #{pin.to_s} to #{edge.to_s}"
386 | end
387 |
388 | if edge.to_sym == :NONE
389 | Beaglebone::delete_pin_status(pin, :trigger)
390 | else
391 | Beaglebone::set_pin_status(pin, :trigger, edge.to_sym)
392 | end
393 |
394 | end
395 |
396 | # Returns the GPIO edge trigger type on an initialized pin
397 | # @return [Symbol] :NONE, :RISING, :FALLING, or :BOTH
398 | def get_gpio_edge(pin)
399 | check_gpio_enabled(pin)
400 |
401 | edge = Beaglebone::get_pin_status(pin, :trigger)
402 | return edge if edge
403 |
404 | read_gpio_edge(pin)
405 | end
406 |
407 | # Return an array of GPIO pins in use
408 | #
409 | # @return [Array]
410 | #
411 | # @example
412 | # GPIO.get_gpio_pins => [:P9_12, :P9_13]
413 | def get_gpio_pins
414 | Beaglebone.pinstatus.clone.select { |x,y| x if y[:type] == :gpio && !PINS[x][:led] }.keys
415 | end
416 |
417 | # Disable a GPIO pin
418 | #
419 | # @param pin should be a symbol representing the header pin
420 | def disable_gpio_pin(pin)
421 |
422 | Beaglebone::check_valid_pin(pin, :gpio)
423 |
424 | pininfo = PINS[pin]
425 |
426 | close_value_fd(pin)
427 |
428 | #close any running threads
429 | stop_edge_wait(pin)
430 |
431 | #write to unexport to disable gpio
432 | begin
433 | File.open('/sys/class/gpio/unexport', 'w') { |f| f.write(pininfo[:gpio]) }
434 | rescue
435 | #
436 | end
437 |
438 | #unload device tree
439 | Beaglebone::device_tree_unload("#{TREES[:GPIO][:pin]}#{pin}_.*") unless pininfo[:led]
440 |
441 | #remove status from hash so following enabled? call checks actual system
442 | Beaglebone::delete_pin_status(pin)
443 |
444 | #check to see if pin is GPIO enabled in /sys/class/gpio/
445 | raise StandardError, "GPIO was unable to uninitalize pin: #{pin.to_s}" if enabled?(pin)
446 |
447 | end
448 |
449 | private
450 |
451 | #ensure edge type is valid
452 | def check_valid_edge(edge)
453 | raise ArgumentError, "No such edge: #{edge.to_s}" unless EDGES.include?(edge)
454 | end
455 |
456 | #read gpio edge file
457 | def read_gpio_edge(pin)
458 | check_gpio_enabled(pin)
459 | File.open("#{gpio_directory(pin)}/edge", 'r').read.to_s.strip
460 | end
461 |
462 | #check if pin is valid to use as gpio pin
463 | def valid?(pin)
464 | #check to see if pin exists
465 | return false unless PINS[pin]
466 | return false unless PINS[pin][:gpio]
467 |
468 | true
469 | end
470 |
471 | #set edge trigger to none
472 | def cleanup_edge_trigger(pin)
473 | if Beaglebone::get_pin_status(pin, :thread) == Thread.current
474 | set_gpio_edge(pin, :NONE)
475 | Beaglebone::delete_pin_status(pin, :thread)
476 | end
477 | end
478 |
479 | #convenience method for getting gpio dir in /sys
480 | def gpio_directory(pin)
481 | raise StandardError, 'Invalid Pin' unless valid?(pin)
482 | #led's are in a special place
483 | if PINS[pin][:led]
484 | "/sys/class/leds/beaglebone:green:#{pin.to_s.downcase}"
485 | else
486 | #normal gpio pins
487 | "/sys/class/gpio/gpio#{PINS[pin][:gpio]}"
488 | end
489 | end
490 |
491 | #read gpio direction file
492 | def read_gpio_direction(pin)
493 | check_gpio_enabled(pin)
494 |
495 | Beaglebone::set_pin_status(pin, :mode, File.open("#{gpio_directory(pin)}/direction", 'r').read.to_s.strip.to_sym.upcase)
496 | end
497 |
498 | #return the open value fd, or open if needed
499 | def get_value_fd(pin)
500 | check_gpio_enabled(pin)
501 |
502 | fd = Beaglebone::get_pin_status(pin, :fd_value)
503 | return fd if fd
504 |
505 | pininfo = PINS[pin]
506 |
507 | #leds aren't normal gpio pins, we can toggle them on and off however.
508 | if pininfo[:led]
509 | fd = File.open("#{gpio_directory(pin)}/brightness", 'w+')
510 | else
511 | fd = File.open("#{gpio_directory(pin)}/value", 'w+')
512 | end
513 |
514 | Beaglebone::set_pin_status(pin, :fd_value, fd)
515 | end
516 |
517 | #close value fd if open
518 | def close_value_fd(pin)
519 | fd = Beaglebone::get_pin_status(pin, :fd_value)
520 | fd.close if fd
521 | Beaglebone::delete_pin_status(pin, :fd_value)
522 | end
523 |
524 | #ensure state is valid
525 | def check_valid_state(state)
526 | #check to see if mode is valid
527 | state = state.to_sym
528 | raise ArgumentError, "No such state: #{state.to_s}" unless STATES.include?(state)
529 | end
530 |
531 | #ensure mode is valid
532 | def check_valid_mode(mode)
533 | #check to see if mode is valid
534 | mode = mode.to_sym
535 | raise ArgumentError, "No such mode: #{mode.to_s}" unless MODES.include?(mode)
536 | end
537 |
538 | #ensure gpio pin is enabled
539 | def check_gpio_enabled(pin)
540 | Beaglebone::check_valid_pin(pin, :gpio)
541 | raise StandardError, "PIN not GPIO enabled: #{pin}" unless enabled?(pin)
542 | end
543 |
544 | def create_device_tree(pin, mode, pullmode, slewrate, force = false)
545 | #get info from PINS hash
546 | pininfo = PINS[pin]
547 |
548 | #generate data value for dts
549 | #Bit 15 PIN USAGE is an indicator and should be a 1 if the pin is used or 0 if it is unused.
550 | # Bits 14-7 RESERVED is not to be used and left as 0.
551 | # Bit 6 SLEW CONTROL 0=Fast 1=Slow
552 | # Bit 5 RX Enabled 0=Disabled 1=Enabled
553 | # Bit 4 PU/PD 0=Pulldown 1=Pullup.
554 | # Bit 3 PULLUP/DN 0=Pullup/pulldown enabled 1= Pullup/pulldown disabled
555 | # Bit 2-0 MUX MODE SELECT Mode 0-7. (refer to TRM)
556 | pin_data = 0
557 | pin_data |= 0b1000000 if slewrate == :SLOW
558 | pin_data |= 0b100000 if mode == :IN
559 | case pullmode
560 | when :PULLUP
561 | pin_data |= 0b10000
562 | when :NONE
563 | pin_data |= 0b1000
564 | else
565 | # default is pulldown enabled
566 | end
567 | #set mux mode, 7 is gpio
568 | pin_data |= 7
569 |
570 | dts = GPIOTEMPLATE.clone
571 |
572 | dts.gsub!('!PIN_KEY!', pin.to_s)
573 | dts.gsub!('!PIN_DOT_KEY!', pin.to_s.gsub('_', '.'))
574 | dts.gsub!('!PIN_FUNCTION!', pininfo[:gpiofunc])
575 | dts.gsub!('!PIN_OFFSET!', pininfo[:muxoffset])
576 | dts.gsub!('!DATA!', "0x#{pin_data.to_s(16)}")
577 |
578 | filename = "/lib/firmware/#{TREES[:GPIO][:pin]}#{pin}_0x#{pin_data.to_s(16)}-00A0"
579 | dts_fn = "#{filename}.dts"
580 | dtb_fn = "#{filename}.dtbo"
581 |
582 | # if we've already built this file, we don't need to do it again
583 | return pin_data if File.exists?(dtb_fn) && !force
584 |
585 | dts_file = File.open(dts_fn, 'w')
586 | dts_file.write(dts)
587 | dts_file.close
588 |
589 | system("dtc -O dtb -o #{dtb_fn} -b 0 -@ #{dts_fn}")
590 |
591 | pin_data
592 | end
593 | end
594 | end
595 |
596 | # Object Oriented GPIO Implementation.
597 | # This treats the pin as an object.
598 | class GPIOPin
599 |
600 | # Initialize a GPIO pin
601 | # Return's a GPIOPin object, setting the pin mode on initialization
602 | #
603 | # @param mode should specify the mode of the pin, either :IN or :OUT
604 | # @param pullmode (optional) should specify the pull mode, :PULLUP, :PULLDOWN, or :NONE
605 | # @param slewrate (optional) should specify the slew rate, :FAST or :SLOW
606 | #
607 | # @return [GPIOPin]
608 | #
609 | # @example
610 | # p9_12 = GPIOPin.new(:P9_12, :OUT)
611 | # p9_11 = GPIOPin.new(:P9_11, :IN)
612 | def initialize(pin, mode, pullmode = nil, slewrate = nil)
613 | @pin = pin
614 |
615 | GPIO::pin_mode(@pin, mode, pullmode, slewrate)
616 | end
617 |
618 | # Sets a pin's output state
619 | #
620 | # @param state should be a symbol representin the state, :HIGH or :LOW
621 | #
622 | # @example
623 | # p9_12 = GPIOPin.new(:P9_12, :OUT)
624 | # p9_12.digital_write(:HIGH)
625 | # p9_12.digital_write(:LOW)
626 | def digital_write(state)
627 | GPIO::digital_write(@pin, state)
628 | end
629 |
630 | # Reads a pin's input state and return that value
631 | #
632 | # @return [Symbol] :HIGH or :LOW
633 | #
634 | # @example
635 | # p9_11 = GPIOPin.new(:P9_12, :OUT)
636 | # p9_11.digital_read => :HIGH
637 | def digital_read
638 | GPIO::digital_read(@pin)
639 | end
640 |
641 | # Runs a callback on an edge trigger event.
642 | # This creates a new thread that runs in the background
643 | #
644 | # @param callback A method to call when the edge trigger is detected. This method should take 3 arguments, the pin, the edge, and the counter
645 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
646 | # @param timeout is optional and specifies a time window to wait
647 | # @param repeats is optional and specifies the number of times the callback will be run
648 | #
649 | # @example
650 | # p9_11 = GPIOPin.new(:P9_11, :IN)
651 | # p9_11.run_on_edge(lambda { |pin,edge,count| puts "[#{count}] #{pin} -- #{edge}" }, :P9_11, :RISING) def run_on_edge(callback, edge, timeout=nil, repeats=nil)
652 | def run_on_edge(callback, edge, timeout=nil, repeats=nil)
653 | GPIO::run_on_edge(callback, @pin, edge, timeout, repeats)
654 | end
655 |
656 | # Runs a callback one time on an edge trigger event.
657 | # this is a convenience method for run_on_edge
658 | # @see #run_on_edge
659 | def run_once_on_edge(callback, edge, timeout=nil)
660 | GPIO::run_once_on_edge(callback, @pin, edge, timeout)
661 | end
662 |
663 | # Stops any threads waiting for data on this pin
664 | #
665 | def stop_edge_wait
666 | GPIO::stop_edge_wait(@pin)
667 | end
668 |
669 | # Wait for an edge trigger.
670 | # Returns the type that triggered the event, e.g. :RISING, :FALLING, :BOTH
671 | #
672 | # @return [Symbol] :RISING, :FALLING, or :BOTH
673 | #
674 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
675 | # @param timeout is optional and specifies a time window to wait
676 | #
677 | # @example
678 | # p9_11 = GPIOPin.new(:P9_11, :IN)
679 | # p9_11.wait_for_edge(:RISING, 30) => :RISING
680 | def wait_for_edge(edge, timeout=nil)
681 | GPIO::wait_for_edge(@pin, edge, timeout)
682 | end
683 |
684 | # Returns last known state from +pin+, reads state if unknown
685 | # @return [Symbol] :HIGH or :LOW
686 | def get_gpio_state
687 | GPIO::get_gpio_state(@pin)
688 | end
689 |
690 | # Returns mode from pin, reads mode if unknown
691 | # @return [Symbol] :IN or :OUT
692 | def get_gpio_mode
693 | GPIO::get_gpio_mode(@pin)
694 | end
695 |
696 | # Returns the GPIO edge trigger type
697 | # @return [Symbol] :NONE, :RISING, :FALLING, or :BOTH
698 | def get_gpio_edge
699 | GPIO::get_gpio_edge(@pin)
700 | end
701 |
702 |
703 | # Set GPIO mode on an initialized pin
704 | #
705 | # @param mode should specify the mode of the pin, either :IN or :OUT
706 | #
707 | # @example
708 | # p9_12.set_gpio_mode(:OUT)
709 | # p9_11.set_gpio_mode(:IN)
710 | def set_gpio_mode(mode)
711 | GPIO::set_gpio_mode(@pin, mode)
712 | end
713 |
714 | # Set GPIO edge trigger type
715 | #
716 | # @param edge should be a symbol representing the trigger type, e.g. :RISING, :FALLING, :BOTH
717 | # @param force is optional, if set will set the mode even if already set
718 | #
719 | # @example
720 | # p9_11.set_gpio_edge(:RISING)
721 | def set_gpio_edge(edge, force=nil)
722 | GPIO::set_gpio_edge(@pin, edge, force)
723 | end
724 |
725 | # Disable GPIO pin
726 | def disable_gpio_pin
727 | GPIO::disable_gpio_pin(@pin)
728 | end
729 |
730 | end
731 | end
732 |
--------------------------------------------------------------------------------
/lib/beaglebone/i2c.rb:
--------------------------------------------------------------------------------
1 | # == i2c.rb
2 | # This file contains I2C methods
3 | module Beaglebone #:nodoc:
4 | # == I2C
5 | # Procedural methods for I2C control
6 | # == Summary
7 | # #setup is called to initialize an I2C device
8 | module I2C
9 |
10 | I2C_SLAVE = 0x0703
11 |
12 | @i2cstatus = {}
13 | @i2cmutex = Mutex.new
14 |
15 | class << self
16 | attr_accessor :i2cstatus, :i2cmutex
17 |
18 | # Initialize an I2C device
19 | #
20 | # @param i2c should be a symbol representing the I2C device
21 | #
22 | # @example
23 | # I2C.setup(:I2C2)
24 | def setup(i2c)
25 | check_i2c_valid(i2c)
26 |
27 | #make sure i2c not already enabled
28 | return if get_i2c_status(i2c)
29 |
30 | i2cinfo = I2CS[i2c]
31 |
32 | #ensure dtb is loaded
33 | Beaglebone::device_tree_load("#{i2cinfo[:devicetree]}") if i2cinfo[:devicetree]
34 |
35 | #open the i2c device
36 | i2c_fd = File.open(i2cinfo[:dev], 'r+')
37 |
38 | Beaglebone::set_pin_status(i2cinfo[:scl], :i2c, i2cinfo[:id])
39 | Beaglebone::set_pin_status(i2cinfo[:scl], :type, :i2c)
40 | Beaglebone::set_pin_status(i2cinfo[:scl], :fd_i2c, i2c_fd)
41 |
42 | Beaglebone::set_pin_status(i2cinfo[:sda], :i2c, i2cinfo[:id])
43 | Beaglebone::set_pin_status(i2cinfo[:sda], :type, :i2c)
44 | Beaglebone::set_pin_status(i2cinfo[:sda], :fd_i2c, i2c_fd)
45 |
46 | set_i2c_status(i2c, :fd_i2c, i2c_fd)
47 | set_i2c_status(i2c, :mutex, Mutex.new)
48 | end
49 |
50 | # Write data to an I2C device
51 | #
52 | # @param i2c should be a symbol representing the I2C device
53 | # @param address the address of the slave device
54 | # @param data the data to write
55 | #
56 | # @return Integer the number of bytes written
57 | #
58 | # @example
59 | # I2C.write(:I2C2, 0x1e, [0x00, 0b10010000].pack("C*") )
60 | def write(i2c, address, data)
61 | check_i2c_enabled(i2c)
62 |
63 | lock_i2c(i2c) do
64 | i2c_fd = get_i2c_status(i2c, :fd_i2c)
65 |
66 | #set the slave address to communicate with
67 | i2c_fd.ioctl(I2C_SLAVE, address)
68 |
69 | i2c_fd.syswrite(data)
70 | end
71 | end
72 |
73 | # Read data from an I2C device
74 | #
75 | # @param i2c should be a symbol representing the I2C device
76 | # @param address the address of the slave device
77 | # @param bytes bytes to read
78 | # @param register optional register to read from
79 | #
80 | # @example
81 | # # read 3 big endian signed shorts starting at register 0x03
82 | # data = I2C.read(:I2C2, 0x1e, 6, [0x03].pack("C*"))
83 | # x,z,y = raw.unpack("s>*")
84 | def read(i2c, address, bytes=1, register=nil)
85 | check_i2c_enabled(i2c)
86 |
87 | data = ''
88 | lock_i2c(i2c) do
89 | i2c_fd = get_i2c_status(i2c, :fd_i2c)
90 |
91 | #set the slave address to communicate with
92 | i2c_fd.ioctl(I2C_SLAVE, address)
93 |
94 | i2c_fd.syswrite(register) if register
95 |
96 | data = i2c_fd.sysread(bytes)
97 | end
98 |
99 | data
100 | end
101 |
102 | # Return the file descriptor to the open I2C device
103 | #
104 | # @param i2c should be a symbol representing the I2C device
105 | def file(i2c)
106 | check_i2c_enabled(i2c)
107 | get_i2c_status(i2c, :fd_i2c)
108 | end
109 |
110 | # Disable the specified I2C device.
111 | #
112 | # @note device trees cannot be unloaded at this time without kernel panic.
113 | #
114 | # @param i2c should be a symbol representing the I2C device
115 | def disable(i2c)
116 | check_i2c_valid(i2c)
117 | check_i2c_enabled(i2c)
118 |
119 | disable_i2c_pin(I2CS[i2c][:sda]) if I2CS[i2c][:sda]
120 | disable_i2c_pin(I2CS[i2c][:scl]) if I2CS[i2c][:scl]
121 |
122 | delete_i2c_status(i2c)
123 |
124 | #removing i2c tree causes a crash... can't really disable.
125 | #Beaglebone::device_tree_unload("#{I2CS[i2c][:devicetree]}") if I2CS[i2c][:devicetree]
126 |
127 | end
128 |
129 | # Disable all active I2C interfaces
130 | def cleanup
131 | #reset all i2cs we've used and unload the device tree
132 | i2cstatus.clone.keys.each { |i2c| disable(i2c)}
133 | end
134 |
135 | private
136 |
137 | # disable i2c pin
138 | def disable_i2c_pin(pin)
139 | Beaglebone::check_valid_pin(pin, :i2c)
140 |
141 | Beaglebone::delete_pin_status(pin)
142 | end
143 |
144 | # ensure valid i2c device
145 | def check_i2c_valid(i2c)
146 | raise ArgumentError, "Invalid i2c Specified #{i2c.to_s}" unless I2CS[i2c] && I2CS[i2c][:sda]
147 | i2cinfo = I2CS[i2c.to_sym]
148 |
149 | unless i2cinfo[:scl] && [nil,:i2c].include?(Beaglebone::get_pin_status(i2cinfo[:scl], :type))
150 | raise StandardError, "SCL Pin for #{i2c.to_s} in use"
151 | end
152 |
153 | unless i2cinfo[:sda] && [nil,:i2c].include?(Beaglebone::get_pin_status(i2cinfo[:sda], :type))
154 | raise StandardError, "SDA Pin for #{i2c.to_s} in use"
155 | end
156 |
157 | end
158 |
159 | # ensure i2c device is enabled
160 | def check_i2c_enabled(i2c)
161 | raise ArgumentError, "i2c not enabled #{i2c.to_s}" unless get_i2c_status(i2c)
162 | end
163 |
164 | # lock i2c device
165 | def lock_i2c(i2c)
166 | check_i2c_enabled(i2c)
167 | mutex = get_i2c_status(i2c, :mutex)
168 |
169 | mutex.synchronize do
170 | yield
171 | end
172 | end
173 |
174 | # i2c hash getter
175 | def get_i2c_status(i2c, key = nil)
176 | i2cmutex.synchronize do
177 | if key
178 | i2cstatus[i2c] ? i2cstatus[i2c][key] : nil
179 | else
180 | i2cstatus[i2c]
181 | end
182 | end
183 | end
184 |
185 | # i2c hash setter
186 | def set_i2c_status(i2c, key, value)
187 | i2cmutex.synchronize do
188 | i2cstatus[i2c] ||= {}
189 | i2cstatus[i2c][key] = value
190 | end
191 | end
192 |
193 | # i2c hash delete
194 | def delete_i2c_status(i2c, key = nil)
195 | i2cmutex.synchronize do
196 | if key.nil?
197 | i2cstatus.delete(i2c)
198 | else
199 | i2cstatus[i2c].delete(key) if i2cstatus[i2c]
200 | end
201 | end
202 | end
203 |
204 | end
205 | end
206 |
207 | # Object Oriented I2C Implementation.
208 | # This treats the I2C device as an object.
209 | class I2CDevice
210 | # Initialize an I2C device. Returns an I2CDevice object
211 | #
212 | # @param i2c should be a symbol representing the I2C device
213 | #
214 | # @example
215 | # i2c = I2CDevice.new(:I2C2)
216 | def initialize(i2c)
217 | @i2c = i2c
218 | I2C::setup(@i2c)
219 | end
220 |
221 | # Write data to an I2C device
222 | #
223 | # @param address the address of the slave device
224 | # @param data the data to write
225 | #
226 | # @return Integer the number of bytes written
227 | #
228 | # @example
229 | # i2c.write(0x1e, [0x00, 0b10010000].pack("C*") )
230 | def write(address, data)
231 | I2C::write(@i2c, address, data)
232 | end
233 |
234 | # Read data from an I2C device
235 | #
236 | # @param address the address of the slave device
237 | # @param bytes bytes to read
238 | # @param register optional register to read from
239 | #
240 | # @example
241 | # # read 3 big endian signed shorts starting at register 0x03
242 | # data = i2c.read(0x1e, 6, [0x03].pack("C*"))
243 | # x,z,y = raw.unpack("s>*")
244 | def read(address, bytes=1, register=nil)
245 | I2C::read(@i2c, address, bytes, register)
246 | end
247 |
248 | # Disable the specified I2C device.
249 | #
250 | # @note device trees cannot be unloaded at this time without kernel panic.
251 | def disable
252 | I2C::disable(@i2c)
253 | end
254 |
255 | # Return the file descriptor to the open I2C device
256 | def file
257 | I2C::file(@i2c)
258 | end
259 | end
260 | end
261 |
--------------------------------------------------------------------------------
/lib/beaglebone/pwm.rb:
--------------------------------------------------------------------------------
1 | # == pwm.rb
2 | # This file contains the PWM control methods
3 | module Beaglebone #:nodoc:
4 | # == PWM
5 | # procedural methods for PWM control
6 | # == Summary
7 | # #start is called to enable a PWM pin
8 | module PWM
9 |
10 | # Polarity hash
11 | POLARITIES = { :NORMAL => 0, :INVERTED => 1 }
12 |
13 | class << self
14 |
15 | # Initialize a PWM pin
16 | #
17 | # @param pin should be a symbol representing the header pin
18 | # @param duty should specify the duty cycle
19 | # @param frequency should specify cycles per second
20 | # @param polarity optional, should specify the polarity, :NORMAL or :INVERTED
21 | # @param run optional, if false, pin will be configured but will not run
22 | #
23 | # @example
24 | # PWM.start(:P9_14, 90, 10, :NORMAL)
25 | def start(pin, duty=nil, frequency=nil, polarity=nil, run=true)
26 | #make sure the pwm controller dtb is loaded
27 | Beaglebone::device_tree_load(TREES[:PWM][:global])
28 |
29 | Beaglebone::check_valid_pin(pin, :pwm)
30 |
31 | #if pin is enabled for something else, disable it
32 | if Beaglebone::get_pin_status(pin) && Beaglebone::get_pin_status(pin, :type) != :pwm
33 | Beaglebone::disable_pin(pin)
34 | end
35 |
36 | #load device tree for pin if not already loaded
37 | unless Beaglebone::get_pin_status(pin, :type) == :pwm
38 | Beaglebone::device_tree_load("#{TREES[:PWM][:pin]}#{pin}", 0.5)
39 | Beaglebone::set_pin_status(pin, :type, :pwm)
40 | end
41 |
42 | duty_fd = File.open("#{pwm_directory(pin)}/duty", 'r+')
43 | period_fd = File.open("#{pwm_directory(pin)}/period", 'r+')
44 | polarity_fd = File.open("#{pwm_directory(pin)}/polarity", 'r+')
45 | run_fd = File.open("#{pwm_directory(pin)}/run", 'r+')
46 |
47 | Beaglebone::set_pin_status(pin, :fd_duty, duty_fd)
48 | Beaglebone::set_pin_status(pin, :fd_period, period_fd)
49 | Beaglebone::set_pin_status(pin, :fd_polarity, polarity_fd)
50 | Beaglebone::set_pin_status(pin, :fd_run, run_fd)
51 |
52 | read_period_value(pin)
53 | read_duty_value(pin)
54 | read_polarity_value(pin)
55 |
56 | run_fd.write('0')
57 | run_fd.flush
58 |
59 | set_polarity(pin, polarity) if polarity
60 | set_frequency(pin, frequency) if frequency
61 | set_duty_cycle(pin, duty) if duty
62 |
63 | if run
64 | run_fd.write('1')
65 | run_fd.flush
66 | end
67 |
68 | raise StandardError, "Could not start PWM: #{pin}" unless read_run_value(pin) == 1
69 | true
70 | end
71 |
72 | # Returns true if specified pin is enabled in PWM mode, else false
73 | def enabled?(pin)
74 | return true if Beaglebone::get_pin_status(pin, :type) == :pwm
75 |
76 | return false unless valid?(pin)
77 | if Dir.exists?(pwm_directory(pin))
78 |
79 | start(pin, nil, nil, nil, false)
80 | return true
81 | end
82 | false
83 | end
84 |
85 | # Stop PWM output on specified pin
86 | #
87 | # @param pin should be a symbol representing the header pin
88 | def stop(pin)
89 | Beaglebone::check_valid_pin(pin, :pwm)
90 |
91 | return false unless enabled?(pin)
92 |
93 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless Beaglebone::get_pin_status(pin, :type) == :pwm
94 |
95 | run_fd = Beaglebone::get_pin_status(pin, :fd_run)
96 |
97 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless run_fd
98 |
99 | run_fd.write('0')
100 | run_fd.flush
101 |
102 | raise StandardError, "Could not stop PWM: #{pin}" unless read_run_value(pin) == 0
103 | true
104 | end
105 |
106 | # Start PWM output on specified pin. Pin must have been previously started
107 | #
108 | # @param pin should be a symbol representing the header pin
109 | def run(pin)
110 | Beaglebone::check_valid_pin(pin, :pwm)
111 |
112 | return false unless enabled?(pin)
113 |
114 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless Beaglebone::get_pin_status(pin, :type) == :pwm
115 |
116 | run_fd = Beaglebone::get_pin_status(pin, :fd_run)
117 |
118 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless run_fd
119 |
120 | run_fd.write('1')
121 | run_fd.flush
122 |
123 | raise StandardError, "Could not start PWM: #{pin}" unless read_run_value(pin) == 1
124 | true
125 |
126 | end
127 |
128 | # Set polarity on specified pin
129 | #
130 | # @param pin should be a symbol representing the header pin
131 | # @param polarity should specify the polarity, :NORMAL or :INVERTED
132 | # @example
133 | # PWM.set_polarity(:P9_14, :INVERTED)
134 | def set_polarity(pin, polarity)
135 | check_valid_polarity(polarity)
136 | check_pwm_enabled(pin)
137 |
138 | polarity_fd = Beaglebone::get_pin_status(pin, :fd_polarity)
139 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless polarity_fd
140 |
141 | polarity_fd.write(POLARITIES[polarity.to_sym].to_s)
142 | polarity_fd.flush
143 |
144 | raise StandardError, "Could not set polarity: #{pin}" unless read_polarity_value(pin) == POLARITIES[polarity.to_sym]
145 |
146 | end
147 |
148 | # Set duty cycle of specified pin in percentage
149 | #
150 | # @param pin should be a symbol representing the header pin
151 | # @param duty should specify the duty cycle in percentage
152 | # @example
153 | # PWM.set_duty_cycle(:P9_14, 25)
154 | def set_duty_cycle(pin, duty, newperiod=nil)
155 |
156 | raise ArgumentError, "Duty cycle must be >= 0 and <= 100, #{duty} invalid" if duty < 0 || duty > 100
157 | check_pwm_enabled(pin)
158 |
159 |
160 | fd = Beaglebone::get_pin_status(pin, :fd_duty)
161 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
162 |
163 | period = newperiod || Beaglebone::get_pin_status(pin, :period)
164 |
165 | value = ((duty * period) / 100.0).round
166 |
167 | fd.write(value.to_s)
168 | fd.flush
169 |
170 | raise StandardError, "Could not set duty cycle: #{pin} (#{value})" unless read_duty_value(pin) == value
171 |
172 | Beaglebone::set_pin_status(pin, :duty_pct, duty)
173 | value
174 |
175 | end
176 |
177 |
178 | # Set duty cycle of specified pin in nanoseconds
179 | #
180 | # @param pin should be a symbol representing the header pin
181 | # @param duty should specify the duty cycle in nanoseconds
182 | # @example
183 | # PWM.set_duty_cycle_ns(:P9_14, 2500000)
184 | def set_duty_cycle_ns(pin, duty)
185 |
186 | check_pwm_enabled(pin)
187 |
188 | fd = Beaglebone::get_pin_status(pin, :fd_duty)
189 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
190 |
191 | period = Beaglebone::get_pin_status(pin, :period)
192 |
193 | duty = duty.to_i
194 |
195 | if duty < 0 || duty > period
196 | raise ArgumentError, "Duty cycle ns must be >= 0 and <= #{period} (current period), #{duty} invalid"
197 | end
198 |
199 | value = duty
200 |
201 | fd.write(value.to_s)
202 | fd.flush
203 |
204 | #since we're setting the duty_ns, we want to update the duty_pct value as well here.
205 | raise StandardError, "Could not set duty cycle: #{pin} (#{value})" unless read_duty_value(pin, true) == value
206 |
207 | value
208 | end
209 |
210 | # Set frequency of specified pin in cycles per second
211 | #
212 | # @param pin should be a symbol representing the header pin
213 | # @param frequency should specify the frequency in cycles per second
214 | # @example
215 | # PWM.set_frequency(:P9_14, 100)
216 | def set_frequency(pin, frequency)
217 | frequency = frequency.to_i
218 | raise ArgumentError, "Frequency must be > 0 and <= 1000000000, #{frequency} invalid" if frequency < 1 || frequency > 1000000000
219 | check_pwm_enabled(pin)
220 |
221 | fd = Beaglebone::get_pin_status(pin, :fd_period)
222 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
223 |
224 | duty_ns = Beaglebone::get_pin_status(pin, :duty)
225 | duty_pct = Beaglebone::get_pin_status(pin, :duty_pct)
226 |
227 | value = (1000000000 / frequency).round
228 |
229 | #we can't set the frequency lower than the previous duty cycle
230 | #adjust if necessary
231 | if duty_ns > value
232 | set_duty_cycle(pin, Beaglebone::get_pin_status(pin, :duty_pct), value)
233 | end
234 |
235 | fd.write(value.to_s)
236 | fd.flush
237 |
238 | raise StandardError, "Could not set frequency: #{pin} (#{value})" unless read_period_value(pin) == value
239 |
240 | #adjust the duty cycle if we haven't already
241 | if duty_ns <= value
242 | set_duty_cycle(pin, duty_pct, value)
243 | end
244 |
245 | value
246 | end
247 |
248 | # Set frequency of specified pin based on period duration
249 | #
250 | # @param pin should be a symbol representing the header pin
251 | # @param period should specify the length of a cycle in nanoseconds
252 | #
253 | # @example
254 | # PWM.set_frequency_ns(:P9_14, 100000000)
255 | def set_period_ns(pin, period)
256 | period = period.to_i
257 | raise ArgumentError, "period must be > 0 and <= 1000000000, #{period} invalid" if period < 1 || period > 1000000000
258 | check_pwm_enabled(pin)
259 |
260 | fd = Beaglebone::get_pin_status(pin, :fd_period)
261 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
262 |
263 | duty_ns = Beaglebone::get_pin_status(pin, :duty)
264 | value = period.to_i
265 |
266 | #we can't set the frequency lower than the previous duty cycle
267 | #adjust if necessary
268 | if duty_ns > value
269 | set_duty_cycle(pin, Beaglebone::get_pin_status(pin, :duty_pct), value)
270 | end
271 |
272 | fd.write(value.to_s)
273 | fd.flush
274 |
275 | raise StandardError, "Could not set period: #{pin} (#{value})" unless read_period_value(pin) == value
276 |
277 | #adjust the duty cycle if we haven't already
278 | if duty_ns <= value
279 | set_duty_cycle(pin, Beaglebone::get_pin_status(pin, :duty_pct), value)
280 | end
281 |
282 | value
283 | end
284 |
285 | #reset all PWM pins we've used to IN and unexport them
286 | def cleanup
287 | get_pwm_pins.each { |x| disable_pwm_pin(x) }
288 | end
289 |
290 | # Return an array of PWM pins in use
291 | #
292 | # @return [Array]
293 | #
294 | # @example
295 | # PWM.get_pwm_pins => [:P9_13, :P9_14]
296 | def get_pwm_pins
297 | Beaglebone.pinstatus.clone.select { |x,y| x if y[:type] == :pwm}.keys
298 | end
299 |
300 | # Disable a PWM pin
301 | #
302 | # @param pin should be a symbol representing the header pin
303 | def disable_pwm_pin(pin)
304 | Beaglebone::check_valid_pin(pin, :pwm)
305 | Beaglebone::delete_pin_status(pin) if Beaglebone::device_tree_unload("#{TREES[:PWM][:pin]}#{pin}")
306 | end
307 |
308 | private
309 |
310 | #ensure pin is valid pwm pin
311 | def valid?(pin)
312 | #check to see if pin exists
313 | pin = pin.to_sym
314 |
315 | return false unless PINS[pin]
316 | return false unless PINS[pin][:pwm]
317 |
318 | true
319 | end
320 |
321 | #ensure pin is pwm enabled
322 | def check_pwm_enabled(pin)
323 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless enabled?(pin)
324 | end
325 |
326 | #read run file
327 | def read_run_value(pin)
328 | check_pwm_enabled(pin)
329 |
330 | fd = Beaglebone::get_pin_status(pin, :fd_run)
331 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
332 |
333 | fd.rewind
334 | fd.read.strip.to_i
335 | end
336 |
337 | #read polarity file
338 | def read_polarity_value(pin)
339 | check_pwm_enabled(pin)
340 |
341 | fd = Beaglebone::get_pin_status(pin, :fd_polarity)
342 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
343 |
344 | fd.rewind
345 | value = fd.read.strip.to_i
346 |
347 | Beaglebone::set_pin_status(pin, :polarity, value)
348 |
349 | end
350 |
351 | #read duty file
352 | def read_duty_value(pin, setpct=false)
353 | check_pwm_enabled(pin)
354 |
355 | fd = Beaglebone::get_pin_status(pin, :fd_duty)
356 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
357 |
358 | fd.rewind
359 | value = fd.read.strip.to_i
360 |
361 | Beaglebone::set_pin_status(pin, :duty, value)
362 | # only set duty_pct if it is unset or if we are forcing it.
363 | if setpct || Beaglebone::get_pin_status(pin, :duty_pct).nil?
364 | duty_pct = ((value * 100.0) / Beaglebone::get_pin_status(pin, :period)).round
365 | Beaglebone::set_pin_status(pin, :duty_pct, duty_pct)
366 | end
367 |
368 | value
369 | end
370 |
371 | #read period file
372 | def read_period_value(pin)
373 | check_pwm_enabled(pin)
374 |
375 | fd = Beaglebone::get_pin_status(pin, :fd_period)
376 | raise StandardError, "Pin is not PWM enabled: #{pin}" unless fd
377 |
378 | fd.rewind
379 | value = fd.read.strip.to_i
380 |
381 | Beaglebone::set_pin_status(pin, :period, value)
382 |
383 | value
384 | end
385 |
386 | #return sysfs directory for pwm control
387 | def pwm_directory(pin)
388 | raise StandardError, 'Invalid Pin' unless valid?(pin)
389 | Dir.glob("/sys/devices/ocp.*/pwm_test_#{pin}.*").first
390 | end
391 |
392 | #ensure polarity is valid
393 | def check_valid_polarity(polarity)
394 | #check to see if mode is valid
395 | polarity = polarity.to_sym
396 | raise ArgumentError, "No such polarity: #{polarity.to_s}" unless POLARITIES.include?(polarity)
397 | end
398 |
399 | end
400 | end
401 |
402 | # Object Oriented PWM Implementation.
403 | # This treats the pin as an object.
404 | class PWMPin
405 |
406 | # Initialize a PWM pin
407 | #
408 | #
409 | # @param duty should specify the duty cycle
410 | # @param frequency should specify cycles per second
411 | # @param polarity optional, should specify the polarity, :NORMAL or :INVERTED
412 | # @param run optional, if false, pin will be configured but will not run
413 | #
414 | # @example
415 | # p9_14 = PWMPin.new(:P9_14, 90, 10, :NORMAL)
416 | def initialize(pin, duty=nil, frequency=nil, polarity=nil, run=true)
417 | @pin = pin
418 | PWM::start(@pin, duty, frequency, polarity, run)
419 | end
420 |
421 | # Stop PWM output on pin
422 | def stop
423 | PWM::stop(@pin)
424 | end
425 |
426 | # Start PWM output on pin. Pin must have been previously started
427 | def run
428 | PWM::run(@pin)
429 | end
430 |
431 | # Set polarity on pin
432 | #
433 | # @param polarity should specify the polarity, :NORMAL or :INVERTED
434 | # @example
435 | # p9_14.set_polarity(:INVERTED)
436 | def set_polarity(polarity)
437 | PWM::set_polarity(@pin, polarity)
438 | end
439 |
440 | # Set duty cycle of pin in percentage
441 | #
442 | #
443 | # @param duty should specify the duty cycle in percentage
444 | # @example
445 | # p9_14.set_duty_cycle(25)
446 | def set_duty_cycle(duty, newperiod=nil)
447 | PWM::set_duty_cycle(@pin, duty, newperiod)
448 | end
449 |
450 | # Set duty cycle of pin in nanoseconds
451 | #
452 | # @param duty should specify the duty cycle in nanoseconds
453 | # @example
454 | # p9_14.set_duty_cycle_ns(2500000)
455 | def set_duty_cycle_ns(duty)
456 | PWM::set_duty_cycle_ns(@pin, duty)
457 | end
458 |
459 | # Set frequency of pin in cycles per second
460 | #
461 | # @param frequency should specify the frequency in cycles per second
462 | # @example
463 | # p9_14.set_frequency(100)
464 | def set_frequency(frequency)
465 | PWM::set_frequency(@pin, frequency)
466 | end
467 |
468 | # Set frequency of pin based on period duration
469 | #
470 | # @param period should specify the length of a cycle in nanoseconds
471 | # @example
472 | # p9_14.set_frequency_ns(100000000)
473 | def set_period_ns(period)
474 | PWM::set_period_ns(@pin, period)
475 | end
476 |
477 | # Disable PWM pin
478 | def disable_pwm_pin
479 | PWM::disable_pwm_pin(@pin)
480 | end
481 | end
482 |
483 | end
484 |
--------------------------------------------------------------------------------
/lib/beaglebone/shiftregister.rb:
--------------------------------------------------------------------------------
1 | # == shiftregister.rb
2 | # This file contains the shiftregister control methods
3 | module Beaglebone #:nodoc:
4 | class ShiftRegister
5 |
6 | # Create a shiftregister object based on 3 GPIO pins
7 | #
8 | # @param latch_pin should be a symbol representing the header pin, i.e. :P9_12
9 | # @param clock_pin should be a symbol representing the header pin, i.e. :P9_13
10 | # @param data_pin should be a symbol representing the header pin, i.e. :P9_14
11 | # @param lsb optional, send least significant bit first if set
12 | #
13 | # @example
14 | # shiftregister = ShiftRegister.new(:P9_11, :P9_12, :P9_13)
15 | def initialize(latch_pin, clock_pin, data_pin, lsb=nil)
16 |
17 | @latch_pin = latch_pin
18 | @clock_pin = clock_pin
19 | @data_pin = data_pin
20 | @lsb = lsb
21 |
22 | GPIO::pin_mode(@latch_pin, :OUT)
23 | GPIO::pin_mode(@clock_pin, :OUT)
24 | GPIO::pin_mode(@data_pin, :OUT)
25 | end
26 |
27 | # Send data to shift register
28 | #
29 | # @param data Integer value to write to the shift register
30 | # @param lsb optional, send least significant bit first if set
31 | #
32 | # @example
33 | # shiftregister = ShiftRegister.new(:P9_11, :P9_12, :P9_13)
34 | # shiftregister.shift_out(255)
35 | def shift_out(data, lsb=nil)
36 | GPIO::shift_out(@latch_pin, @clock_pin, @data_pin, data, lsb || @lsb)
37 | end
38 |
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/lib/beaglebone/spi.rb:
--------------------------------------------------------------------------------
1 | # == spi.rb
2 | # This file contains SPI methods
3 | module Beaglebone #:nodoc:
4 | # == SPI
5 | # Procedural methods for SPI control
6 | # == Summary
7 | # #setup is called to initialize an SPI device
8 | module SPI
9 | #some ioctl defines
10 | IOC_NONE = 0
11 | IOC_WRITE = 1
12 | IOC_READ = 2
13 |
14 | IOC_NRBITS = 8
15 | IOC_TYPEBITS = 8
16 | IOC_SIZEBITS = 14
17 | IOC_DIRBITS = 2
18 |
19 | IOC_NRSHIFT = 0
20 | IOC_TYPESHIFT = IOC_NRSHIFT+IOC_NRBITS
21 | IOC_SIZESHIFT = IOC_TYPESHIFT+IOC_TYPEBITS
22 | IOC_DIRSHIFT = IOC_SIZESHIFT+IOC_SIZEBITS
23 |
24 | #spi defines
25 | SPI_CPHA = 0x01
26 | SPI_CPOL = 0x02
27 |
28 | SPI_MODE_0 = (0|0)
29 | SPI_MODE_1 = (0|SPI_CPHA)
30 | SPI_MODE_2 = (SPI_CPOL|0)
31 | SPI_MODE_3 = (SPI_CPOL|SPI_CPHA)
32 |
33 | SPI_MODES = {
34 | :SPI_MODE_0 => SPI_MODE_0,
35 | :SPI_MODE_1 => SPI_MODE_1,
36 | :SPI_MODE_2 => SPI_MODE_2,
37 | :SPI_MODE_3 => SPI_MODE_3,
38 | }
39 |
40 | SPI_CS_HIGH = 0x04
41 | SPI_LSB_FIRST = 0x08
42 | SPI_3WIRE = 0x10
43 | SPI_LOOP = 0x20
44 | SPI_NO_CS = 0x40
45 | SPI_READY = 0x80
46 |
47 | SPI_IOC_MAGIC = 'k'.ord
48 |
49 | SPI_IOC_RD_MODE = 2147576577 #ior(SPI_IOC_MAGIC, 1, 1)
50 | SPI_IOC_WR_MODE = 1073834753 #iow(SPI_IOC_MAGIC, 1, 1)
51 |
52 | SPI_IOC_RD_LSB_FIRST = 2147576578 #ior(SPI_IOC_MAGIC, 2, 1)
53 | SPI_IOC_WR_LSB_FIRST = 1073834754 #iow(SPI_IOC_MAGIC, 2, 1)
54 |
55 | SPI_IOC_RD_BITS_PER_WORD = 2147576579 #ior(SPI_IOC_MAGIC, 3, 1)
56 | SPI_IOC_WR_BITS_PER_WORD = 1073834755 #iow(SPI_IOC_MAGIC, 3, 1)
57 |
58 | SPI_IOC_RD_MAX_SPEED_HZ = 2147773188 #ior(SPI_IOC_MAGIC, 4, 4)
59 | SPI_IOC_WR_MAX_SPEED_HZ = 1074031364 #iow(SPI_IOC_MAGIC, 4, 4)
60 |
61 | SPI_IOC_MESSAGE_1 = 1075866368
62 |
63 | SPI_IOC_TRANSFER_STRUCT_SIZE = 32
64 |
65 | @spistatus = {}
66 | @spimutex = Mutex.new
67 |
68 | class << self
69 |
70 | attr_accessor :spistatus, :spimutex
71 |
72 | # Initialize an SPI device
73 | #
74 | # @param spi should be a symbol representing the SPI device
75 | # @param mode optional, default 0, specifies the SPI mode :SPI_MODE_0 through 3
76 | # @param speed optional, specifies the SPI communication speed
77 | # @param bpw optional, specifies the bits per word
78 | #
79 | # @example
80 | # SPI.setup(:SPI0, SPI_MODE_0)
81 | def setup(spi, mode=nil, speed=1000000, bpw=8)
82 | check_spi_valid(spi)
83 |
84 | #make sure spi not already enabled
85 | return if get_spi_status(spi)
86 |
87 | mode = mode || SPI_MODE_0
88 |
89 | spiinfo = SPIS[spi]
90 |
91 | #ensure dtb is loaded
92 | Beaglebone::device_tree_load("#{spiinfo[:devicetree]}") if spiinfo[:devicetree]
93 |
94 | #open the spi device.
95 | spi_fd = File.open("#{spiinfo[:dev]}#{SPIS[:counter]}.0", 'r+')
96 |
97 | set_spi_status(spi, :fd_spi, spi_fd)
98 | set_spi_status(spi, :mutex, Mutex.new)
99 |
100 | set_mode(spi, mode)
101 | set_bpw(spi, bpw)
102 | set_speed(spi, speed)
103 |
104 | SPIS[:counter] += 1
105 |
106 | spiinfo[:pins].each do |pin|
107 | Beaglebone::set_pin_status(pin, :spi, spiinfo[:id])
108 | Beaglebone::set_pin_status(pin, :type, :spi)
109 | Beaglebone::set_pin_status(pin, :fd_spi, spi_fd)
110 | end
111 |
112 | end
113 |
114 | # Transfer data to and from the SPI device
115 | #
116 | # @return String data read from SPI device
117 | #
118 | # @param spi should be a symbol representing the SPI device
119 | # @param tx_data data to transmit
120 | # @param readbytes bytes to read, otherwise it sizeof tx_data is used
121 | # @param speed optional, speed to xfer at
122 | # @param delay optional delay
123 | # @param bpw optional bits per word
124 | #
125 | # @example
126 | # # communicate with MCP3008
127 | # # byte 1: start bit
128 | # # byte 2: single(1)/diff(0),3 bites for channel, null pad
129 | # # byte 3: don't care
130 | # SPI.setup(:SPI0, SPI_MODE_0)
131 | # raw = SPI.xfer(:SPI0, [ 0b00000001, 0b10000000, 0].pack("C*"))
132 | # data = raw.unpack("C*")
133 | # val = ((data[1] & 0b00000011) << 8 ) | data[2]
134 | def xfer(spi, tx_data, readbytes=0, speed=nil, delay=nil, bpw=nil)
135 | check_spi_enabled(spi)
136 |
137 | speed = speed || get_spi_status(spi, :speed)
138 | delay = delay || 0
139 | bpw = bpw || get_spi_status(spi, :bpw)
140 |
141 | if tx_data.size > readbytes
142 | readbytes = tx_data.size
143 | end
144 |
145 | rx_data = ' ' * readbytes
146 |
147 | lock_spi(spi) do
148 | spi_fd = get_spi_status(spi, :fd_spi)
149 |
150 | ### SPI IOC transfer structure
151 | # __u64 tx_buf;
152 | # __u64 rx_buf;
153 | #
154 | # __u32 len;
155 | # __u32 speed_hz;
156 | #
157 | # __u16 delay_usecs;
158 | # __u8 bits_per_word;
159 | # __u8 cs_change;
160 | # __u32 pad;
161 | ###
162 |
163 | msg = [ tx_data, 0,
164 | rx_data, 0,
165 | readbytes,
166 | speed,
167 | delay,
168 | bpw,
169 | 0,
170 | 0].pack('pLpLLLSCCL')
171 |
172 | #ioctl call to begin data transfer
173 | spi_fd.ioctl(SPI_IOC_MESSAGE_1, msg)
174 | #speedup with defined int
175 | #spi_fd.ioctl(spi_ioc_message(1), msg)
176 |
177 | end
178 | rx_data
179 | end
180 |
181 | # Return the file descriptor to the open SPI device
182 | #
183 | # @param spi should be a symbol representing the SPI device
184 | def file(spi)
185 | check_spi_enabled(spi)
186 | get_spi_status(spi, :fd_spi)
187 | end
188 |
189 | # Set the communication speed of the specified SPI device
190 | #
191 | # @param spi should be a symbol representing the SPI device
192 | # @param speed communication speed
193 | def set_speed(spi, speed)
194 | speed = speed.to_i
195 | raise ArgumentError, "Speed (#{speed.to_s}) must be a positive integer" unless speed > 0
196 |
197 | check_spi_enabled(spi)
198 | spi_fd = get_spi_status(spi, :fd_spi)
199 |
200 | spi_fd.ioctl(SPI_IOC_WR_MAX_SPEED_HZ, [speed].pack('L'))
201 |
202 | # deal with old versions of ruby that can't handle large number IOCTL
203 | # https://bugs.ruby-lang.org/issues/6127
204 | begin
205 | spi_fd.ioctl(SPI_IOC_RD_MAX_SPEED_HZ, [speed].pack('L'))
206 | rescue
207 | puts 'Warning, old Ruby detected, cannot set SPI max read speed'
208 | end
209 |
210 | set_spi_status(spi, :speed, speed)
211 | end
212 |
213 | # Set the communication speed of the specified SPI device
214 | #
215 | # @param spi should be a symbol representing the SPI device
216 | # @param mode should be a valid SPI mode, e.g. :SPI_MODE_0 through 3
217 | def set_mode(spi, mode)
218 | check_spi_enabled(spi)
219 |
220 | #if mode is a symbol, translate it to the appropriate value
221 | mode = SPI_MODES[mode] if mode.class == Symbol && SPI_MODES[mode]
222 |
223 | raise ArgumentError, "Mode (#{mode.to_s}) is unknown" unless SPI_MODES.values.include?(mode)
224 | spi_fd = get_spi_status(spi, :fd_spi)
225 |
226 | # deal with old versions of ruby that can't handle large number IOCTL
227 | # https://bugs.ruby-lang.org/issues/6127
228 | begin
229 | spi_fd.ioctl(SPI_IOC_WR_MODE, [mode].pack('C'))
230 | spi_fd.ioctl(SPI_IOC_RD_MODE, [mode].pack('C'))
231 | rescue
232 | puts 'Warning, old Ruby detected, cannot set SPI mode'
233 | end
234 |
235 | end
236 |
237 | # Set the bits per word of the specified SPI device
238 | #
239 | # @param spi should be a symbol representing the SPI device
240 | # @param bpw should specify the bits per word
241 | def set_bpw(spi, bpw)
242 | bpw = bpw.to_i
243 | raise ArgumentError, "BPW (#{bpw.to_s}) must be a positive integer" unless bpw > 0
244 |
245 | check_spi_enabled(spi)
246 | spi_fd = get_spi_status(spi, :fd_spi)
247 |
248 | spi_fd.ioctl(SPI_IOC_WR_BITS_PER_WORD, [bpw].pack('C'))
249 |
250 | # deal with old versions of ruby that can't handle large number IOCTL
251 | # https://bugs.ruby-lang.org/issues/6127
252 | begin
253 | spi_fd.ioctl(SPI_IOC_RD_BITS_PER_WORD, [bpw].pack('C'))
254 | rescue
255 | puts 'Warning, old Ruby detected, cannot set SPI read bits per word'
256 | end
257 |
258 | set_spi_status(spi, :bpw, bpw)
259 | end
260 |
261 | # Disable the specified SPI device
262 | #
263 | # @note device trees cannot be unloaded at this time without kernel panic.
264 | #
265 | # @param spi should be a symbol representing the SPI device
266 | def disable(spi)
267 | check_spi_valid(spi)
268 | check_spi_enabled(spi)
269 |
270 | SPIS[spi][:pins].each do |pin|
271 | disable_spi_pin(pin)
272 | end
273 |
274 | delete_spi_status(spi)
275 |
276 | #removing spi tree causes a crash... can't really disable.
277 | #Beaglebone::device_tree_unload("#{SPIS[spi][:devicetree]}") if SPIS[spi][:devicetree]
278 |
279 | end
280 |
281 | # Disable all active SPI devices
282 | def cleanup
283 | #reset all spis we've used and unload the device tree
284 | spistatus.clone.keys.each { |spi| disable(spi)}
285 | end
286 |
287 | private
288 |
289 | #ensure spi is valid
290 | def check_spi_valid(spi)
291 | raise ArgumentError, "Invalid spi Specified #{spi.to_s}" unless SPIS[spi] && SPIS[spi][:sclk]
292 | spiinfo = SPIS[spi.to_sym]
293 |
294 | unless spiinfo[:sclk] && [nil,:spi].include?(Beaglebone::get_pin_status(spiinfo[:sclk], :type))
295 | raise StandardError, "SCLK Pin for #{spi.to_s} in use"
296 | end
297 |
298 | unless spiinfo[:d0] && [nil,:spi].include?(Beaglebone::get_pin_status(spiinfo[:d0], :type))
299 | raise StandardError, "D0 Pin for #{spi.to_s} in use"
300 | end
301 |
302 | unless spiinfo[:d1] && [nil,:spi].include?(Beaglebone::get_pin_status(spiinfo[:d1], :type))
303 | raise StandardError, "D1 Pin for #{spi.to_s} in use"
304 | end
305 |
306 | unless spiinfo[:cs0] && [nil,:spi].include?(Beaglebone::get_pin_status(spiinfo[:cs0], :type))
307 | raise StandardError, "CS0 Pin for #{spi.to_s} in use"
308 | end
309 | end
310 |
311 | # lock spi
312 | def lock_spi(spi)
313 | check_spi_enabled(spi)
314 | mutex = get_spi_status(spi, :mutex)
315 |
316 | mutex.synchronize do
317 | yield
318 | end
319 | end
320 |
321 | # ensure spi is enabled
322 | def check_spi_enabled(spi)
323 | raise ArgumentError, "spi not enabled #{spi.to_s}" unless get_spi_status(spi)
324 | end
325 |
326 | # disable spi pin
327 | def disable_spi_pin(pin)
328 | Beaglebone::check_valid_pin(pin, :spi)
329 |
330 | Beaglebone::delete_pin_status(pin)
331 | end
332 |
333 | #ports of ioctl definitions
334 | def ioc(dir,type,nr,size)
335 | (((dir) << IOC_DIRSHIFT) |
336 | ((type) << IOC_TYPESHIFT) |
337 | ((nr) << IOC_NRSHIFT) |
338 | ((size) << IOC_SIZESHIFT))
339 | end
340 |
341 | def ior(type,nr,size)
342 | ioc(IOC_READ,(type),(nr),size)
343 | end
344 |
345 | def iow(type,nr,size)
346 | ioc(IOC_WRITE,(type),(nr),size)
347 | end
348 |
349 | def spi_msgsize(n)
350 | n*SPI_IOC_TRANSFER_STRUCT_SIZE < 1<;
40 | __overlay__ {
41 | bb_uart3_pins: pinmux_bb_uart3_pins {
42 | pinctrl-single,pins = <
43 | 0x164 0x01
44 | >;
45 | };
46 | };
47 | };
48 |
49 | fragment@1 {
50 | target = <&uart4>; /* really uart3 */
51 | __overlay__ {
52 | status = "okay";
53 | pinctrl-names = "default";
54 | pinctrl-0 = <&bb_uart3_pins>;
55 | };
56 | };
57 | };
58 | '
59 |
60 | # Initialize a UART device
61 | #
62 | # @param uart should be a symbol representing the UART device
63 | # @param speed should be an integer thats a valid speed. @see SPEEDS
64 | #
65 | # @example
66 | # UART.setup(:UART1, 9600)
67 | def setup(uart, speed=9600)
68 | check_uart_valid(uart)
69 | check_speed_valid(speed)
70 |
71 | #make sure uart not already enabled
72 | return if get_uart_status(uart)
73 |
74 | uartinfo = UARTS[uart]
75 |
76 | #ensure we have a dtb to load
77 | create_device_tree(uart)
78 |
79 | #ensure dtb is loaded
80 | Beaglebone::device_tree_load("#{TREES[:UART][:pin]}#{uartinfo[:id]}")
81 |
82 | #open the uart device
83 | uart_fd = File.open(uartinfo[:dev], 'r+')
84 |
85 | if uartinfo[:tx]
86 | Beaglebone::set_pin_status(uartinfo[:tx], :uart, uartinfo[:id])
87 | Beaglebone::set_pin_status(uartinfo[:tx], :type, :uart)
88 | Beaglebone::set_pin_status(uartinfo[:tx], :fd_uart, uart_fd)
89 | end
90 |
91 | if uartinfo[:rx]
92 | Beaglebone::set_pin_status(uartinfo[:rx], :uart, uartinfo[:id])
93 | Beaglebone::set_pin_status(uartinfo[:tx], :type, :uart)
94 | Beaglebone::set_pin_status(uartinfo[:rx], :fd_uart, uart_fd)
95 | end
96 |
97 | system("stty -F #{uartinfo[:dev]} raw")
98 | system("stty -F #{uartinfo[:dev]} #{speed}")
99 |
100 | set_uart_status(uart, :fd_uart, uart_fd)
101 | end
102 |
103 | # Set the speed of the UART
104 | #
105 | # @param speed should be an integer thats a valid speed. @see SPEEDS
106 | #
107 | # @example
108 | # UART.set_speed(:UART1, 9600)
109 | def set_speed(uart, speed)
110 | check_uart_valid(uart)
111 | check_speed_valid(speed)
112 |
113 | uartinfo = UARTS[uart]
114 | system("stty -F #{uartinfo[:dev]} #{speed}")
115 | end
116 |
117 | # Write data to a UART device
118 | #
119 | # @param uart should be a symbol representing the UART device
120 | # @param data the data to write
121 | #
122 | # @return Integer the number of bytes written
123 | #
124 | # @example
125 | # UART.write(:UART1, "1234") => 4
126 | def write(uart, data)
127 | check_uart_enabled(uart)
128 |
129 | pin_tx = UARTS[uart][:tx]
130 |
131 | Beaglebone::check_valid_pin(pin_tx, :uart)
132 |
133 | fd = Beaglebone::get_pin_status(pin_tx, :fd_uart)
134 |
135 | ret = fd.write(data)
136 | fd.flush
137 |
138 | ret
139 | end
140 |
141 | # Write a line data to a UART device.
142 | # This is a convenience method using #write
143 | # @see #write
144 | #
145 | # @param uart should be a symbol representing the UART device
146 | # @param data the data to write
147 | #
148 | # @return Integer the number of bytes written
149 | #
150 | # @example
151 | # UART.writeln(:UART1, "1234") => 5
152 | def writeln(uart, data)
153 | write(uart, data + "\n")
154 | end
155 |
156 | # Read one character from a UART device
157 | #
158 | # @param uart should be a symbol representing the UART device
159 | #
160 | # @return String the character read from the UART device
161 | #
162 | # @example
163 | # UART.readchars(:UART1) => "x"
164 | def readchar(uart)
165 | readchars(uart, 1)
166 | end
167 |
168 | # Read characters from a UART device
169 | #
170 | # @param uart should be a symbol representing the UART device
171 | # @param bytes number of bytes to read
172 | #
173 | # @return String the characters read from the UART device
174 | #
175 | # @example
176 | # UART.readchars(:UART1, 2) => "xx"
177 | def readchars(uart, bytes)
178 | check_uart_enabled(uart)
179 | ensure_read_lock(uart)
180 |
181 | buffer = ''
182 |
183 | pin_rx = UARTS[uart][:rx]
184 |
185 | Beaglebone::check_valid_pin(pin_rx, :uart)
186 |
187 | fd = Beaglebone::get_pin_status(pin_rx, :fd_uart)
188 |
189 | set_uart_status(uart, :waiting, true)
190 |
191 | while bytes > 0 do
192 | buffer << fd.readchar
193 | bytes -= 1
194 | end
195 | set_uart_status(uart, :waiting, false)
196 |
197 | buffer
198 | end
199 |
200 | # Read a line from a UART device
201 | #
202 | # @param uart should be a symbol representing the UART device
203 | #
204 | # @return String the line read from the UART device
205 | #
206 | # @example
207 | # UART.readline(:UART1) => "A line of text"
208 | def readline(uart)
209 | check_uart_enabled(uart)
210 | ensure_read_lock(uart)
211 |
212 | pin_rx = UARTS[uart][:rx]
213 |
214 | Beaglebone::check_valid_pin(pin_rx, :uart)
215 |
216 | fd = Beaglebone::get_pin_status(pin_rx, :fd_uart)
217 |
218 | set_uart_status(uart, :waiting, true)
219 |
220 | data = fd.readline.chop
221 |
222 | set_uart_status(uart, :waiting, false)
223 |
224 | data
225 | end
226 |
227 | # Read a character from a UART device and pass it to the specified block
228 | #
229 | # @param uart should be a symbol representing the UART device
230 | #
231 | # @example
232 | # UART.each_char(:UART1) { |x| puts "read: #{x}" }
233 | def each_char(uart)
234 | loop do
235 | data = readchars(uart, 1)
236 | yield data
237 | end
238 |
239 | end
240 |
241 | # Read characters from a UART device and pass them to the specified block
242 | #
243 | # @param uart should be a symbol representing the UART device
244 | # @param chars should be the number of chars to read
245 | #
246 | # @example
247 | # UART.each_chars(:UART1, 2) { |x| puts "read: #{x}" }
248 | def each_chars(uart, chars)
249 | loop do
250 | data = readchars(uart, chars)
251 | yield data
252 | end
253 | end
254 |
255 |
256 | # Read lines from a UART device and pass them to the specified block
257 | #
258 | # @param uart should be a symbol representing the UART device
259 | #
260 | # @example
261 | # UART.each_line(:UART1) { |x| puts "read: #{x}" }
262 | def each_line(uart)
263 | loop do
264 | data = readline(uart)
265 | yield data
266 | end
267 | end
268 |
269 | # Runs a callback after receiving a line of data from a UART device
270 | # This creates a new thread that runs in the background
271 | #
272 | # @param callback A method to call when the data is received. This method should take 3 arguments, the UART, the line read, and the counter
273 | # @param uart should be a symbol representing the UART device
274 | # @param repeats is optional and specifies the number of times the callback will be run
275 | #
276 | # @example
277 | # callback = lambda { |uart, line, count| puts "[#{uart}:#{count}] #{line} "}
278 | # UART.run_on_each_line(callback, :UART1)
279 | def run_on_each_line(callback, uart, repeats=nil)
280 | check_uart_enabled(uart)
281 |
282 | raise StandardError, "Already waiting for data on uart: #{uart}" if get_uart_status(uart, :waiting)
283 | raise StandardError, "Already waiting for data on uart: #{uart}" if get_uart_status(uart, :thread)
284 |
285 | thread = Thread.new(callback, uart, repeats) do |c, u, r|
286 | begin
287 | count = 0
288 | each_line(u) do |line|
289 |
290 | c.call(u, line, count) if c
291 |
292 | count += 1
293 | break if r && count >= r
294 | end
295 | rescue => ex
296 | puts ex
297 | puts ex.backtrace
298 | ensure
299 | delete_uart_status(u, :thread)
300 | set_uart_status(uart, :waiting, false)
301 | end
302 | end
303 | set_uart_status(uart, :thread, thread)
304 | end
305 |
306 | # Convenience method for run_on_each_line with repeats set to 1
307 | # @see #run_on_each_line
308 | def run_once_on_each_line(callback, uart)
309 | run_on_each_line(callback, uart, 1)
310 | end
311 |
312 | # Runs a callback after receiving data from a UART device
313 | # This creates a new thread that runs in the background
314 | #
315 | # @param callback A method to call when the data is received. This method should take 3 arguments, the UART, the line read, and the counter
316 | # @param uart should be a symbol representing the UART device
317 | # @param chars should be the number of chars to read
318 | # @param repeats is optional and specifies the number of times the callback will be run
319 | #
320 | # @example
321 | # callback = lambda { |uart, data, count| puts "[#{uart}:#{count}] #{data} "}
322 | # UART.run_on_each_chars(callback, :UART1, 2)
323 | def run_on_each_chars(callback, uart, chars=1, repeats=nil)
324 | check_uart_enabled(uart)
325 |
326 | raise StandardError, "Already waiting for data on uart: #{uart}" if get_uart_status(uart, :waiting)
327 | raise StandardError, "Already waiting for data on uart: #{uart}" if get_uart_status(uart, :thread)
328 |
329 | thread = Thread.new(callback, uart, chars, repeats) do |c, u, ch, r|
330 | begin
331 | count = 0
332 | each_chars(u, ch) do |line|
333 |
334 | c.call(u, line, count) if c
335 |
336 | count += 1
337 | break if r && count >= r
338 | end
339 | rescue => ex
340 | puts ex
341 | puts ex.backtrace
342 | ensure
343 | delete_uart_status(u, :thread)
344 | set_uart_status(uart, :waiting, false)
345 | end
346 | end
347 | set_uart_status(uart, :thread, thread)
348 | end
349 |
350 | # Convenience method for run_on_each_chars with chars and repeats set to 1
351 | # @see #run_on_each_chars
352 | def run_once_on_each_char(callback, uart)
353 | run_once_on_each_chars(callback, uart, 1)
354 | end
355 |
356 | # Convenience method for run_on_each_chars with chars and repeats set to 1
357 | # @see #run_on_each_chars
358 | def run_once_on_each_chars(callback, uart, chars=1)
359 | run_on_each_chars(callback, uart, chars, 1)
360 | end
361 |
362 | # Convenience method for run_on_each_chars with chars set to 1
363 | # @see #run_on_each_chars
364 | def run_on_each_char(callback, uart, repeats=nil)
365 | run_on_each_chars(callback, uart, 1, repeats)
366 | end
367 |
368 | # Disable a UART device.
369 | #
370 | # @note device trees cannot be unloaded at this time without kernel panic.
371 | #
372 | # @param uart should be a symbol representing the UART device
373 | #
374 | # @example
375 | # UART.disable(:UART1)
376 | def disable(uart)
377 | check_uart_valid(uart)
378 | check_uart_enabled(uart)
379 |
380 | stop_read_wait(uart)
381 |
382 | disable_uart_pin(UARTS[uart][:rx]) if UARTS[uart][:rx]
383 | disable_uart_pin(UARTS[uart][:tx]) if UARTS[uart][:tx]
384 |
385 | delete_uart_status(uart)
386 | end
387 |
388 | # Stops any threads waiting for data on the specified UART
389 | def stop_read_wait(uart)
390 | thread = get_uart_status(uart, :thread)
391 |
392 | thread.exit if thread
393 | thread.join if thread
394 | end
395 |
396 | # Disable all UART devices
397 | def cleanup
398 | #reset all UARTs we've used and unload the device tree
399 | uartstatus.clone.keys.each { |uart| disable(uart)}
400 | end
401 |
402 | private
403 |
404 | # return hash data for specified UART
405 | def get_uart_status(uart, key = nil)
406 | uartmutex.synchronize do
407 | if key
408 | uartstatus[uart] ? uartstatus[uart][key] : nil
409 | else
410 | uartstatus[uart]
411 | end
412 | end
413 | end
414 |
415 | # set hash data for specified UART
416 | def set_uart_status(uart, key, value)
417 | uartmutex.synchronize do
418 | uartstatus[uart] ||= {}
419 | uartstatus[uart][key] = value
420 | end
421 | end
422 |
423 | # remove hash data for specified UART
424 | def delete_uart_status(uart, key = nil)
425 | uartmutex.synchronize do
426 | if key.nil?
427 | uartstatus.delete(uart)
428 | else
429 | uartstatus[uart].delete(key) if uartstatus[uart]
430 | end
431 | end
432 | end
433 |
434 | # ensure UART is valid
435 | def check_uart_valid(uart)
436 | raise ArgumentError, "Invalid UART Specified #{uart.to_s}" unless UARTS[uart]
437 | uartinfo = UARTS[uart.to_sym]
438 |
439 | if uartinfo[:tx]
440 | unless [nil,:uart].include?(Beaglebone::get_pin_status(uartinfo[:tx], :type))
441 | raise StandardError, "TX Pin for #{uart.to_s} in use"
442 | end
443 | end
444 |
445 | if uartinfo[:rx]
446 | unless [nil,:uart].include?(Beaglebone::get_pin_status(uartinfo[:rx], :type))
447 | raise StandardError, "RX Pin for #{uart.to_s} in use"
448 | end
449 | end
450 |
451 | end
452 |
453 | # ensure UART is enabled
454 | def check_uart_enabled(uart)
455 | raise ArgumentError, "UART not enabled #{uart.to_s}" unless get_uart_status(uart)
456 | end
457 |
458 | # ensure we have a read lock for the UART
459 | def ensure_read_lock(uart)
460 | #ensure we're the only ones reading
461 | if get_uart_status(uart, :thread) && get_uart_status(uart, :thread) != Thread.current
462 | raise StandardError, "Already waiting for data on uart: #{uart}"
463 | end
464 |
465 | if get_uart_status(uart, :waiting) && get_uart_status(uart, :thread) != Thread.current
466 | raise StandardError, "Already waiting for data on uart: #{uart}"
467 | end
468 | end
469 |
470 | # check to make sure the specified speed is valid
471 | def check_speed_valid(speed)
472 | raise ArgumentError, "Invalid speed specified: #{speed}" unless SPEEDS.include?(speed)
473 | end
474 |
475 | # disable a uart pin
476 | def disable_uart_pin(pin)
477 | Beaglebone::check_valid_pin(pin, :uart)
478 |
479 | id = Beaglebone::get_pin_status(pin, :uart)
480 |
481 | Beaglebone::delete_pin_status(pin)
482 |
483 | #removing uart tree causes a crash... can't really disable.
484 | return if true
485 |
486 | Beaglebone::device_tree_unload("#{TREES[:UART][:pin]}#{id}")
487 |
488 | end
489 |
490 | def create_device_tree(uart, force = false)
491 | uartinfo = UARTS[uart]
492 |
493 | #ensure valid uart, and a template to create this exists
494 | return unless uartinfo
495 |
496 | uartnum = uartinfo[:id]
497 |
498 | return unless uartnum && UARTTEMPLATE[uartnum]
499 |
500 | dts = UARTTEMPLATE[uartinfo[:id]].clone
501 |
502 | filename = "/lib/firmware/#{TREES[:UART][:pin]}#{uartnum}-00A0"
503 | dts_fn = "#{filename}.dts"
504 | dtb_fn = "#{filename}.dtbo"
505 |
506 | # if we've already built this file, we don't need to do it again
507 | return if File.exists?(dtb_fn) && !force
508 |
509 | dts_file = File.open(dts_fn, 'w')
510 | dts_file.write(dts)
511 | dts_file.close
512 |
513 | system("dtc -O dtb -o #{dtb_fn} -b 0 -@ #{dts_fn}")
514 |
515 | end
516 |
517 | end
518 | end
519 |
520 | # Object Oriented UART Implementation.
521 | # This treats the UART device as an object.
522 | class UARTDevice
523 | # Initialize a UART device. Returns a UARTDevice object
524 | #
525 | # @param uart should be a symbol representing the UART device
526 | # @param speed should be an integer thats a valid speed. @see SPEEDS
527 | #
528 | # @example
529 | # uart1 = UARTDevice.new(:UART1, 9600)
530 | def initialize(uart, speed=9600)
531 | @uart = uart
532 | UART::setup(@uart, speed)
533 | end
534 |
535 | # Set the speed of the UART
536 | #
537 | # @param speed should be an integer thats a valid speed. @see SPEEDS
538 | #
539 | # @example
540 | # uart1.set_speed(9600)
541 | def set_speed(speed)
542 | UART::set_speed(@uart, speed)
543 | end
544 |
545 | # Write data to a UART device
546 | #
547 | # @param data the data to write
548 | #
549 | # @return Integer the number of bytes written
550 | #
551 | # @example
552 | # uart1.write("1234") => 4
553 | def write(data)
554 | UART::write(@uart, data)
555 | end
556 |
557 | # Write a line data to a UART device.
558 | # This is a convenience method using #write
559 | # @see #write
560 | #
561 | # @param data the data to write
562 | #
563 | # @return Integer the number of bytes written
564 | #
565 | # @example
566 | # uart1.writeln("1234") => 5
567 | def writeln(data)
568 | UART::writeln(@uart, data)
569 | end
570 |
571 | # Read one character from a UART device
572 | #
573 | # @return String the character read from the UART device
574 | #
575 | # @example
576 | # uart1.readchars => "x"
577 | def readchar
578 | UART::readchar(@uart)
579 | end
580 |
581 | # Read characters from a UART device
582 | #
583 | # @param bytes number of bytes to read
584 | #
585 | # @return String the characters read from the UART device
586 | #
587 | # @example
588 | # uart1.readchars(2) => "xx"
589 | def readchars(bytes)
590 | UART::readchars(@uart, bytes)
591 | end
592 |
593 | # Read a line from a UART device
594 | #
595 | # @return String the line read from the UART device
596 | #
597 | # @example
598 | # uart1.readline => "A line of text"
599 | def readline
600 | UART::readline(@uart)
601 | end
602 |
603 | # Read a character from a UART device and pass it to the specified block
604 | #
605 | # @example
606 | # uart1.each_char { |x| puts "read: #{x}" }
607 | def each_char(&block)
608 | UART::each_char(@uart, &block)
609 | end
610 |
611 | # Read characters from a UART device and pass them to the specified block
612 | #
613 | # @param chars should be the number of chars to read
614 | #
615 | # @example
616 | # uart1.each_chars(2) { |x| puts "read: #{x}" }
617 | def each_chars(chars, &block)
618 | UART::each_chars(@uart, chars, &block)
619 | end
620 |
621 | # Read lines from a UART device and pass them to the specified block
622 | #
623 | # @example
624 | # uart1.each_line { |x| puts "read: #{x}" }
625 | def each_line(&block)
626 | UART::each_line(@uart, &block)
627 | end
628 |
629 | # Runs a callback after receiving a line of data from a UART device
630 | # This creates a new thread that runs in the background
631 | #
632 | # @param callback A method to call when the data is received. This method should take 3 arguments, the UART, the line read, and the counter
633 | # @param repeats is optional and specifies the number of times the callback will be run
634 | #
635 | # @example
636 | # callback = lambda { |uart, line, count| puts "[#{uart}:#{count}] #{line} "}
637 | # uart1.run_on_each_line(callback)
638 | def run_on_each_line(callback, repeats=nil)
639 | UART::run_on_each_line(callback, @uart, repeats)
640 | end
641 |
642 | # Convenience method for run_on_each_line with repeats set to 1
643 | # @see #run_on_each_line
644 | def run_once_on_each_line(callback)
645 | UART::run_once_on_each_line(callback, @uart)
646 | end
647 |
648 | # Runs a callback after receiving data from a UART device
649 | # This creates a new thread that runs in the background
650 | #
651 | # @param callback A method to call when the data is received. This method should take 3 arguments, the UART, the line read, and the counter
652 | # @param chars should be the number of chars to read
653 | # @param repeats is optional and specifies the number of times the callback will be run
654 | #
655 | # @example
656 | # callback = lambda { |uart, data, count| puts "[#{uart}:#{count}] #{data} "}
657 | # uart1.run_on_each_chars(callback, 2)
658 | def run_on_each_chars(callback, chars=1, repeats=nil)
659 | UART::run_on_each_chars(callback, @uart, chars, repeats)
660 | end
661 |
662 | # Convenience method for run_on_each_chars with chars and repeats set to 1
663 | # @see #run_on_each_chars
664 | def run_once_on_each_char(callback)
665 | UART::run_once_on_each_char(callback, @uart)
666 | end
667 |
668 | # Convenience method for run_on_each_chars with chars and repeats set to 1
669 | # @see #run_on_each_chars
670 | def run_once_on_each_chars(callback, chars=1)
671 | UART::run_once_on_each_chars(callback, @uart, chars)
672 | end
673 |
674 | # Convenience method for run_on_each_chars with chars set to 1
675 | # @see #run_on_each_chars
676 | def run_on_each_char(callback, repeats=nil)
677 | UART::run_on_each_char(callback, @uart, repeats)
678 | end
679 |
680 | # Stops any threads waiting for data on the specified UART
681 | def stop_read_wait
682 | UART::stop_read_wait(@uart)
683 | end
684 |
685 | # Disable a UART device.
686 | #
687 | # @note device trees cannot be unloaded at this time without kernel panic.
688 | def disable
689 | UART::disable(@uart)
690 | end
691 |
692 | end
693 | end
694 |
--------------------------------------------------------------------------------
/procedural-examples.md:
--------------------------------------------------------------------------------
1 | **Table of Contents**
2 | - [Examples (Procedural)](#examples-procedural)
3 | - [GPIO](#gpio)
4 | - [GPIO Writing](#gpio-writing)
5 | - [GPIO Reading](#gpio-reading)
6 | - [LEDs](#leds)
7 | - [Edge Triggers](#edge-triggers)
8 | - [Edge Triggers in the Background](#edge-triggers-in-the-background)
9 | - [Shift Registers](#shift-registers)
10 | - [Analog Inputs](#analog-inputs)
11 | - [Reading](#reading)
12 | - [Waiting for Change](#waiting-for-change)
13 | - [Waiting for Change in the Background](#waiting-for-change-in-the-background)
14 | - [Waiting for Threshold](#waiting-for-threshold)
15 | - [Waiting for Threshold in the Background](#waiting-for-Threshold-in-the-background)
16 | - [PWM](#pwm)
17 | - [UART](#uart)
18 | - [UART Writing](#uart-writing)
19 | - [UART Reading](#uart-reading)
20 | - [UART Reading and Iterating](#uart-reading-and-iterating)
21 | - [UART Reading and Iterating in the Background](#uart-reading-and-iterating-in-the-background)
22 | - [I2C](#i2c)
23 | - [I2C Writing](#i2c-writing)
24 | - [I2C Reading](#i2c-reading)
25 | - [LSM303DLHC Example](#lsm303dlhc-example)
26 | - [SPI](#spi)
27 | - [SPI Data Transfer](#spi-data-transfer)
28 | - [MCP3008 Example](#mcp3008-example)
29 |
30 | ## Examples (Procedural)
31 | These examples will show the various ways to interact with the Beaglebones IO hardware. They will need to be executed as root in order to function correctly.
32 |
33 | ### GPIO
34 | The GPIO pins on the Beaglebone run at **3.3v**. Do not provide more than 3.3v to any GPIO pin or risk damaging the hardware.
35 |
36 | GPIO pins have two modes, input and output. These modes are represented by the symbols **:IN** and **:OUT**.
37 |
38 | GPIO pins have internal pullup and pulldown resistors. These modes are represented by the symbols **:PULLUP**, **:PULLDOWN**, and **:NONE**.
39 |
40 | GPIO pins have an adjustable slew rate. These modes are represented by the symbols **:FAST** and **:SLOW**
41 | To initialize the pin **P9_11**, pass the symbol for that pin and the mode to the **GPIO.pin_mode** method.
42 |
43 | ```ruby
44 | # Initialize pin P9_11 in INPUT mode
45 | # This method takes 4 arguments
46 | # pin: The pin to initialize
47 | # mode: The GPIO mode, :IN or :OUT
48 | # pullmode: (optional) The pull mode, :PULLUP, :PULLDOWN, or :NONE
49 | # slewrate: (optional) The slew rate, :FAST or :SLOW
50 | GPIO.pin_mode(:P9_11, :IN, :PULLUP, :FAST)
51 |
52 | # Initialize pin P9_12 in OUTPUT mode
53 | GPIO.pin_mode(:P9_12, :OUT)
54 |
55 | # Change pin P9_12 to INPUT mode
56 | GPIO.set_gpio_mode(:P9_12, :IN)
57 |
58 | # Disable pin P9_12
59 | GPIO.disable_gpio_pin(:P9_12)
60 | ```
61 |
62 | #### GPIO Writing
63 | To set the state of a GPIO pin, the method **GPIO.digital_write** is used. The states that can be set are **:HIGH** to provide 3.3v and **:LOW** to provide ground.
64 |
65 | ```ruby
66 | # Initialize pin P9_12 in OUTPUT mode
67 | GPIO.pin_mode(:P9_12, :OUT)
68 |
69 | # Provide 3.3v on pin P9_12
70 | GPIO.digital_write(:P9_12, :HIGH)
71 |
72 | # Provide ground on pin P9_12
73 | GPIO.digital_write(:P9_12, :LOW)
74 | ```
75 |
76 | #### GPIO Reading
77 | To read the current state of a GPIO pin, the method **GPIO.digital_read** is used. It will return the symbol **:HIGH** or **:LOW** depending on the state of the pin.
78 |
79 | ```ruby
80 | # Initialize pin P9_11 in INPUT mode
81 | GPIO.pin_mode(:P9_11, :IN)
82 |
83 | # Get the current state of P9_11
84 | state = GPIO.digital_read(:P9_11) => :LOW
85 | ```
86 |
87 | #### LEDs
88 | The on-board LEDs are addressable via GPIO output. They are available on pins **:USR0** through **:USR3**.
89 |
90 | This example will blink each LED in order 5 times.
91 |
92 | ```ruby
93 | # Initialize each LED pin
94 | leds = [ :USR0, :USR1, :USR2, :USR3 ]
95 | leds.each do |ledpin|
96 | GPIO.pin_mode(ledpin, :OUT)
97 | end
98 |
99 |
100 | # Run the following block 5 times
101 | 5.times do
102 | # Iterate over each LED
103 | leds.each do |ledpin|
104 | # Turn on the LED
105 | GPIO.digital_write(ledpin, :HIGH)
106 | # Delay 0.25 seconds
107 | sleep 0.25
108 | # Turn off the LED
109 | GPIO.digital_write(ledpin, :LOW)
110 | end
111 | end
112 | ```
113 |
114 | #### Edge Triggers
115 | The Beaglebone can also monitor for changes on a GPIO pin. This is called an edge trigger. Since this is interrupt based on the Beaglebone, waiting for a change does not waste CPU cycles by constantly polling the pin.
116 |
117 | The following trigger types are supported
118 | - Rising: Triggered when the state goes from low to high
119 | - Falling: Triggered when the state goes from high to low
120 | - Both: Triggered at any change in state
121 | - None: Triggering is disabled
122 |
123 | These trigger types are represented by the symbols :RISING, :FALLING, :BOTH, and :NONE
124 |
125 | This example will wait for a rising edge to continue, then output the type of edge trigger that was detected.
126 |
127 | ```ruby
128 | # Initialize pin P9_11 in INPUT mode
129 | GPIO.pin_mode(:P9_11, :IN)
130 |
131 | # Wait here until a rising edge is detected
132 | edge = GPIO.wait_for_edge(:P9_11, :RISING) => :RISING
133 |
134 | # Output the trigger type detected
135 | puts "Saw a #{edge} edge"
136 | ```
137 |
138 | #### Edge Triggers in the Background
139 | To avoid blocking while waiting for an edge trigger, the method **GPIO.run_on_edge** will run a callback when an edge trigger is detected. This method will spawn a new thread and wait for an edge trigger in the background. Only one of these threads may be active per pin.
140 |
141 | This example will detect edge triggers in the background and output information when triggered.
142 |
143 | ```ruby
144 | # Initialize pin P9_11 in INPUT mode
145 | GPIO.pin_mode(:P9_11, :IN)
146 |
147 | # Define callback to run when an edge trigger is detected
148 | # This method takes 3 arguments.
149 | # pin: The pin that triggered the event
150 | # edge: The event that triggered it
151 | # count: How many times it has been triggered
152 | callback = lambda { |pin,edge,count| puts "[#{count}] #{pin} #{edge}"}
153 |
154 | # Run the callback every time a change in state is detected
155 | # This method has two additional arguments that are optional.
156 | # Timeout: How long to wait for an event before terminating the thread
157 | # Repeats: How many times to run the event
158 | # By default, it will run forever every time the specified trigger is detected
159 | GPIO.run_on_edge(callback, :P9_11, :BOTH)
160 |
161 | # This code will run immediately after the previous call, as it does not block
162 | sleep 10
163 |
164 | # Stop the background thread waiting for an edge trigger after 10 seconds
165 | GPIO.stop_edge_wait(:P9_11)
166 |
167 | # This convenience method will run the callback only on the first detected change
168 | GPIO.run_once_on_edge(callback, :P9_11, :BOTH)
169 |
170 | # Change the trigger detection for the specified pin
171 | GPIO.set_gpio_edge(:P9_11, :RISING)
172 | ```
173 |
174 | #### Shift Registers
175 | This library will also support writing to shift registers using GPIO pins. Create a **ShiftRegister** object by initializing it with the latch pin, clock pin, and data pin.
176 |
177 | This example will trigger 8 pins of a shift register.
178 |
179 | ```ruby
180 | # P9_11 is connected to the latch pin
181 | # P9_12 is connected to the clock pin
182 | # P9_13 is connected to the data pin
183 |
184 | # Initialize the pins connected to shift register
185 | GPIO.pin_mode(:P9_11, :OUT)
186 | GPIO.pin_mode(:P9_12, :OUT)
187 | GPIO.pin_mode(:P9_13, :OUT)
188 |
189 | # Write value to shift register
190 | GPIO.shift_out(:P9_11, :P9_12, :P9_13, 0b11111111)
191 | ```
192 |
193 | ### Analog Inputs
194 | The Analog pins on the Beaglebone run at **1.8v**. Do not provide more than 1.8v to any analog pin or risk damaging the hardware. The header has pins available to provide a 1.8v for analog devices as well as a dedicated analog ground. Analog pins are only capable of reading input values.
195 |
196 | Analog pins do not require setup, and can be read at any time
197 |
198 | #### Reading
199 | To read the value from an analog pin, the method **AIN.read** is used. This will return a value between 0 and 1799.
200 |
201 | ```ruby
202 | # Read the input value in millivolts.
203 | mv = AIN.read(:P9_33) => 1799
204 | ```
205 |
206 | #### Waiting for Change
207 | To wait for the value of an analog pin to change by a specified voltage, the method **AIN.wait_for_change** is used.
208 |
209 | **AIN.wait_for_change** takes the following arguments.
210 | - pin: The symbol of the pin to monitor
211 | - mv_change: The amount of change in millivolts required before returning
212 | - interval: How often to poll the value of the pin in seconds
213 | - mv_last: (optional) The initial value to use as a point to detect change
214 |
215 | This method returns an array containing the initial voltage, the last polled voltage, and the number of times the pin was polled.
216 |
217 | ```ruby
218 | # Wait for 100mv of change on pin P9_33. Poll 10 times a second
219 | mv_start, mv_current, count = AIN.wait_for_change(:P9_33, 100, 0.1)
220 | ```
221 |
222 | #### Waiting for Change in the Background
223 | To avoid blocking while waiting for voltage change, the method **AIN.run_on_change** will run a callback every time the specified change is detected. This method will spawn a new thread and wait for change in the background. The method **AIN.run_once_on_change** is a convenience method to only be triggered once. Only one of these threads may be active per pin.
224 |
225 | This example waits for voltage change in the background and outputs information when change is detected.
226 |
227 | ```ruby
228 |
229 | # Define callback to run when condition is met
230 | # This method takes 4 arguments.
231 | # pin: The pin that triggered the event
232 | # mv_last: The initial voltage used to determine change
233 | # mv: The current voltage on the pin
234 | # count: How many times it has been triggered
235 | callback = lambda { |pin, mv_last, mv, count| puts "[#{count}] #{pin} #{mv_last} -> #{mv}" }
236 |
237 | # Run the callback every time the specified voltage change is detected
238 | # This method has one additional argument that is optional.
239 | # Repeats: How many times to will run the event
240 | # By default, it will run forever every time the specified condition is detected
241 | # Detect 10mv of change polling 10 times a second.
242 | AIN.run_on_change(callback, :P9_33, 10, 0.1)
243 |
244 | # This code will run immediately after the previous call, as it does not block
245 | sleep 20
246 |
247 | # Stop the background thread after 20 seconds
248 | AIN.stop_wait(:P9_33)
249 | ```
250 |
251 | #### Waiting for Threshold
252 | To wait for the value of an analog pin to cross certain threshold voltages, the method **AIN.wait_for_threshold** is used.
253 |
254 | **AIN.wait_for_threshold** takes the following arguments.
255 | - pin: The symbol of the pin to monitor
256 | - mv_lower: The lower threshold value in millivolts
257 | - mv_upper: The upper threshold value in millivolts
258 | - mv_reset: The voltage change required to cross out of the lower or upper threshold ranges.
259 | - interval: How often to poll the value of the pin in seconds
260 | - mv_last: (optional) The initial value to use as a point to detect change
261 | - state_last: (optional) The initial state to use as a point to detect change
262 |
263 | Three states are available.
264 | - :LOW: below or equal to mv_lower
265 | - :MID: above mv_lower and below mv_upper
266 | - :HIGH: above or equal to mv_upper
267 |
268 | This method returns an array containing the initial voltage, the last polled voltage, the initial state, the last polled state, and the number of times the pin was polled.
269 |
270 | ```ruby
271 | # Wait for the voltage on pin P9_33 to go below 200mv or above 1600mv.
272 | # To enter the :MID state from :HIGH or :LOW, it will have to cross the thresholds by at least 100mv.
273 | # Poll 10 times a second
274 | data = AIN.wait_for_threshold(:P9_33, 200, 1600, 100, 0.1) => [ 500, 150, :MID, :LOW, 53 ]
275 |
276 | # Assign variables from array
277 | mv_start, mv_current, state_start, state_current, count = data
278 | ```
279 |
280 | #### Waiting for Threshold in the Background
281 | To avoid blocking while waiting for a voltage threshold to be crossed, the method **AIN.run_on_threshold** will run a callback every time the specified change is detected. This method will spawn a new thread and wait for change in the background. The method **AIN.run_once_on_threshold** is a convenience method to only be triggered once. Only one of these threads may be active per pin.
282 |
283 | This example waits for voltage change in the background and outputs information when the specified threshold is crossed.
284 |
285 | ```ruby
286 | # Define callback to run when condition is met
287 | # This method takes 6 arguments.
288 | # pin: The pin that triggered the event
289 | # mv_last: The initial voltage used to determine change
290 | # mv: The current voltage on the pin
291 | # state_last: The initial state to use as a point to detect change
292 | # state: The current state of the pin
293 | # count: How many times it has been triggered
294 | callback = lambda { |pin, mv_last, mv, state_last, state, count|
295 | puts "[#{count}] #{pin} #{state_last} -> #{state} #{mv_last} -> #{mv}"
296 | }
297 |
298 | # Run the callback every time the specified voltage threshold is crossed
299 | # This method has one additional argument that is optional.
300 | # Repeats: How many times to will run the event
301 | # By default, it will run forever every time the specified condition is detected
302 | # Wait for the voltage on pin P9_33 to go below 200mv or above 1600mv.
303 | # To enter the :MID state from :HIGH or :LOW, it will have to cross the thresholds by at least 100mv.
304 | # Poll 10 times a second
305 | # Run callback when state changes
306 | AIN.run_on_threshold(callback, :P9_33, 200, 1600, 100, 0.1)
307 |
308 | # This code will run immediately after the previous call, as it does not block
309 | sleep 20
310 |
311 | # Stop the background thread after 20 seconds
312 | AIN.stop_wait(:P9_33)
313 | ```
314 |
315 | ### PWM
316 | The beaglebone supports PWM (pulse width modulated) output on certain pins. These pins output 3.3v. The output is controlled based on frequency and duty cycle.
317 |
318 | To initialize the pin **P9_14**, pass the symbol for that pin, the duty cycle, and the frequency in Hz to the **PWM.start** method.
319 |
320 | This example shows how to control PWM output of a specified pin.
321 |
322 | ```ruby
323 | # Initialize pin P9_14 for PWM output
324 | # This pin will now output a square wave at 10Hz with a 90% duty cycle, non-inverted.
325 | PWM.start(:P9_14, 90, 10, :NORMAL)
326 |
327 | # Change frequency to 20Hz. Duty cycle remains 90%
328 | PWM.set_frequency(:P9_14, 20)
329 |
330 | # Change the duty cycle to 50%
331 | PWM.set_duty_cycle(:P9_14, 50)
332 |
333 | # Adjust the frequency by setting the period in nanoseconds.
334 | PWM.set_period_ns(:P9_14, 31250000)
335 |
336 | # Adjust the duty cycle by setting the period in nanoseconds.
337 | PWM.set_duty_cycle_ns(:P9_14, 31250000)
338 |
339 | # Invert the output signal
340 | PWM.set_polarity(:P9_14, :INVERTED)
341 |
342 | # Stop the output signal
343 | PWM.stop(:P9_14)
344 |
345 | # Resume the output signal
346 | PWM.run(:P9_14)
347 |
348 | # Disable the output signal
349 | PWM.disable_pwm_pin(:P9_14)
350 | ```
351 |
352 | ### UART
353 | The beaglebone has a number of UART devices. These operate in TTL mode at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
354 |
355 | Please note, UART3 does not have an RX pin, and UART5 is only available if the HDMI device tree is not enabled.
356 |
357 | To initialize the UART device **UART1**, pass the symbol for that device and the speed to the **UART.setup** method.
358 |
359 | ```ruby
360 | # Initialize the pins for device UART1 into UART mode.
361 | UART.setup(:UART1, 9600)
362 |
363 | # Change the speed of a UART device by calling #set_speed
364 | UART.set_speed(:UART1, 115200)
365 |
366 | # Disable UART device
367 | UART.disable(:UART1)
368 | ```
369 |
370 | #### UART Writing
371 | Writing to a UART device is accomplished by calling the **UART.write** or **UART.writeln** methods
372 | ```ruby
373 | # Initialize the pins for device UART1 into UART mode.
374 | UART.setup(:UART1, 9600)
375 |
376 | # Write data to a UART1
377 | UART.write(:UART1, "DATA DATA DATA!")
378 |
379 | # Write data to UART1 followed by a line feed
380 | UART.writeln(:UART1, "A line feed follows")
381 | ```
382 |
383 | #### UART Reading
384 | There are many methods available for reading from UART devices. These are blocking methods and will not return until the requested data is available.
385 |
386 | ```ruby
387 | # Initialize the pins for device UART1 into UART mode.
388 | UART.setup(:UART1, 9600)
389 |
390 | # Read one character from UART1
391 | c = UART.readchar(:UART1) => "X"
392 |
393 | # Read 10 characters from UART1
394 | str = UART.readchars(:UART1, 10) => "0123456789"
395 |
396 | # Read a line from UART1
397 | line = UART.readline(:UART1) => "All the text up until the linefeed"
398 | ```
399 |
400 | #### UART Reading and Iterating
401 | Data read from the UART device may be iterated with the following methods. These are blocking methods and will run until the loop is broken.
402 |
403 | ```ruby
404 | # Initialize the pins for device UART1 into UART mode.
405 | UART.setup(:UART1, 9600)
406 |
407 | # Run block on every character read from UART1
408 | UART.each_char(:UART1) { |c| puts c }
409 |
410 | # Run block on every 5 character read from UART1
411 | UART.each_char(:UART1, 5) { |str| puts str }
412 |
413 | # Run block on each line read from UART1
414 | UART.each_line(:UART1) { |line| puts line }
415 | ```
416 |
417 | #### UART Reading and Iterating in the Background
418 | Data read from the UART device may be iterated in the background with the following methods. The data read is passed to the specified callback. These method will spawn a new thread and wait for data in the background. Only one of these threads may be active per pin.
419 |
420 | This example shows various methods of reading and processing data read from UART1 in the background.
421 |
422 | ```ruby
423 | # Initialize the pins for device UART1 into UART mode.
424 | UART.setup(:UART1, 9600)
425 |
426 | # Define the callback to be run. It takes 3 arguments
427 | # uart: the UART device that triggered the callback
428 | # data: the data read from the UART
429 | # count: how many times this was triggered
430 | callback = lambda { |uart, data, count| puts "[#{uart}:#{count}] #{data}" }
431 |
432 | # Run callback for every character read
433 | UART.run_on_each_char(callback, :UART1)
434 |
435 | # Run callback for every 3 characters read
436 | UART.run_on_each_chars(callback, :UART1, 3)
437 |
438 | # Run callback for every line read
439 | UART.run_on_each_line(callback, :UART1)
440 |
441 | # Run callback once after a character is read
442 | UART.run_once_on_each_char(callback, :UART1)
443 |
444 | # Run callback once after 3 characters are read
445 | UART.run_once_on_each_chars(callback, :UART1, 3)
446 |
447 | # Run callback once after reading a line
448 | UART.run_once_on_each_line(callback, :UART1)
449 |
450 | # Stop the currently running background thread
451 | UART.stop_read_wait(:UART1)
452 | ```
453 |
454 | ### I2C
455 | The beaglebone has a number of I2C devices. These operate at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
456 |
457 | To initialize the I2C device **I2C2**, pass the symbol for that device to the **I2C.setup** method.
458 |
459 | ```ruby
460 | # Initialize I2C device I2C2
461 | I2CDevice.setup(:I2C2)
462 | ```
463 |
464 | #### I2C Writing
465 | To write to an I2C device, the method **I2C.write** is used.
466 |
467 | **I2C.write** takes the following arguments.
468 | - i2c: symbol of the I2C device to write to
469 | - address: address of slave device
470 | - data: data to write
471 |
472 | #### I2C Reading
473 | To read from an I2C device, the method **I2C.read** is used.
474 |
475 | **I2C.read** takes the following arguments.
476 | - i2c: symbol of the I2C device to read from
477 | - address: address of slave device
478 | - bytes: bytes to read
479 | - register: (optional) register to start reading from
480 |
481 | #### LSM303DLHC Example
482 |
483 | This example communicates with an [LSM303DLHC](https://www.adafruit.com/products/1120) Accelerometer/Compass/Thermometer device.
484 |
485 | ```ruby
486 | #!/usr/bin/env ruby
487 | require 'beaglebone'
488 | include Beaglebone
489 |
490 | # Initialize I2C device I2C2
491 | I2CDevice.setup(:I2C2)
492 |
493 | # Put compass into continuous conversation mode
494 | I2C.write(:I2C2, 0x1e, [0x02, 0x00].pack("C*"))
495 |
496 | # Enable temperatuer sensor, 15hz register update
497 | I2C.write(:I2C2, 0x1e, [0x00, 0b10010000].pack("C*") )
498 |
499 | # Delay for the settings to take effect
500 | sleep(0.1)
501 |
502 | # Read axis data. It is made up of 3 big endian signed shorts starting at register 0x03
503 | raw = I2C.read(:I2C2, 0x1e, 6, [0x03].pack("C*"))
504 |
505 | # Coordinates are big endian signed shorts in x,z,y order
506 | x,z,y = raw.unpack("s>*")
507 |
508 | # Calculate angle of degrees from North
509 | degrees = (Math::atan2(y, x) * 180) / Math::PI
510 | degrees += 360 if degrees < 0
511 |
512 | # Read 2 byte big endian signed short from temperature register
513 | raw = I2C.read(:I2C2, 0x1e, 2, [0x31].pack("C*"))
514 |
515 | # Temperature is sent big endian, least significant digit last
516 | temp = raw.unpack("s>").first
517 |
518 | # Temperature data is 12 bits, last 4 are unused
519 | temp = temp >> 4
520 |
521 | # Each bit is 8c
522 | temp /= 8
523 |
524 | # Correction factor
525 | temp += 18
526 |
527 | # Convert to f
528 | temp = (temp * 1.8 + 32).to_i
529 |
530 | # Output data
531 | puts "#{Time.now.strftime("%H:%M")} Temperature: #{temp} degrees f Direction: #{degrees.to_i} degrees"
532 |
533 | # Disable I2C device
534 | I2C.disable(:I2C2)
535 | ```
536 |
537 | ### SPI
538 | The beaglebone has a number of SPI devices. These operate at 3.3v. Do not provide more than 3.3v to the pins or risk damaging the hardware.
539 |
540 | To initialize the SPI device **SPI0**, pass the symbol for that device to the **SPI.setup** method.
541 |
542 | The optional arguments are also available
543 | - mode: SPI mode, :SPI_MODE_0 through :SPI_MODE_3
544 | - speed: Speed of the SPI device
545 | - bpw: Bits per word
546 |
547 | ```ruby
548 | # Initialize SPI device SPI0
549 | SPI.setup(:SPI0, :SPI_MODE_0, 1000000, 8)
550 |
551 | # You can change SPI with the methods below.
552 |
553 | # Set mode of SPI0
554 | SPI.set_mode(:SPI0, :SPI_MODE_3)
555 |
556 | # Set speed of SPI0
557 | SPI.set_speed(:SPI0, 100000)
558 |
559 | # Set bits per word of SPI0
560 | SPI.set_bpw(:SPI0, 10)
561 |
562 | # Disable SPI device
563 | SPI.disable(:SPI0)
564 | ```
565 |
566 | #### SPI Data Transfer
567 | To transfer data to an SPI device, the method **SPI.xfer** is used.
568 |
569 | **SPI.xfer** takes the following arguments
570 | - spi: symbol for the SPI device to use
571 | - tx_data: data to transmit
572 | - readbytes: (optional) number of bytes to read, otherwise it sizeof tx_data is used
573 | - speed: (optional) speed of the transfer
574 | - delay: (optional) delay
575 | - bpw: (optonal) bits per word
576 |
577 | **SPI.xfer** returns the data read from the SPI device.
578 |
579 | #### MCP3008 Example
580 | This example communicates with an [MCP3008](http://www.adafruit.com/products/856) ADC device.
581 |
582 | ```ruby
583 | #!/usr/bin/env ruby
584 | require 'beaglebone'
585 | include Beaglebone
586 |
587 | # Initialize SPI device SPI0
588 | SPIDevice.new(:SPI0)
589 |
590 | # communicate with MCP3008
591 | # byte 1: start bit
592 | # byte 2: single(1)/diff(0),3 bites for channel, null pad
593 | # byte 3: don't care
594 | # Read value from channel 0
595 | raw = SPI.xfer(:SPI0, [ 0b00000001, 0b10000000, 0].pack("C*"))
596 |
597 | # Split data read into an array of characters
598 | data = raw.unpack("C*")
599 |
600 | # The returned data is stored starting at the last two bits of the second byte
601 | val = ((data[1] & 0b00000011) << 8 ) | data[2]
602 |
603 | # Display the value of channel 0
604 | puts "Value of channel 0: #{val}"
605 |
606 | # Read value from channel 1
607 | raw = SPI.xfer(:SPI0, [ 0b00000001, 0b10010000, 0].pack("C*"))
608 |
609 | # Split data read into an array of characters
610 | data = raw.unpack("C*")
611 |
612 | # The returned data is stored starting at the last two bits of the second byte
613 | val = ((data[1] & 0b00000011) << 8 ) | data[2]
614 |
615 | # Display the value of channel 1
616 | puts "Value of channel 1: #{val}"
617 |
618 | # Disable SPI device
619 | SPI.disable(:SPI0)
620 | ```
621 |
--------------------------------------------------------------------------------