├── .gitignore
├── CHANGELOG
├── COPYING
├── MANIFEST.in
├── README.md
├── cblrx
├── Makefile
└── src
│ └── cblrx.c
├── codebug_tether
├── __init__.py
├── colourtail.py
├── core.py
├── font.py
├── i2c.py
├── platform.py
├── serial_channel_device.py
├── sprites.py
└── version.py
├── docs
├── Makefile
├── conf.py
├── example.rst
├── index.rst
└── installation.rst
├── examples
├── batteryChecker.py
├── binary_counter.py
├── blink.py
├── clock.py
├── colourtail.py
├── dice.py
├── randomNumber.py
├── snake.py
└── tweets.py
├── firmware
├── codebug_tether_v0.4.3.cbg
├── codebug_tether_v0.5.0.cbg
├── codebug_tether_v0.6.0.cbg
├── codebug_tether_v0.7.0.cbg
├── codebug_tether_v0.7.3.cbg
├── codebug_tether_v0.8.0.cbg
├── codebug_tether_v0.8.4.cbg
└── codebug_tether_v0.8.5.cbg
├── requirements.txt
├── setup.py
└── tests.py
/.gitignore:
--------------------------------------------------------------------------------
1 | makedebpkg.sh
2 | dpkg-files
3 | *.deb
4 | _build
5 | *.log
6 | MANIFEST
7 | deb_dist
8 |
9 | # databases
10 | *.db
11 | .ds_store
12 | *.py[cod]
13 |
14 | # C extensions
15 | *.so
16 |
17 | # Packages
18 | *.egg
19 | *.egg-info
20 | dist
21 | build
22 | eggs
23 | parts
24 | bin
25 | var
26 | sdist
27 | develop-eggs
28 | .installed.cfg
29 | lib
30 | lib64
31 | __pycache__
32 |
33 | # Installer logs
34 | pip-log.txt
35 |
36 | # Unit test / coverage reports
37 | .coverage
38 | .tox
39 | nosetests.xml
40 |
41 | # Translations
42 | *.mo
43 |
44 | # Mr Developer
45 | .mr.developer.cfg
46 | .project
47 | .pydevproject
48 |
--------------------------------------------------------------------------------
/CHANGELOG:
--------------------------------------------------------------------------------
1 | Change Log
2 | ==========
3 |
4 | v0.9.1
5 | ------
6 | - removed conditional checking RPi version; now always uses /dev/ttyACM0
7 |
8 | v0.9.0
9 | ------
10 | - Added `scroll_sprite` method.
11 | - Moved platform checking code to its own module.
12 |
13 | v0.8.6
14 | ------
15 | - Fixed bug with vertical sprites not allocating the correct amount of
16 | sprite space.
17 |
18 | v0.8.5
19 | ------
20 | - Fixed timing issue with servos and USB response.
21 |
22 | v0.8.4
23 | ------
24 | - Default serial port is set to blank on error and added 'requires' to
25 | setup.py
26 | - Added new installation docs.
27 | - Fixed firmware bug with legs 0 and 1.
28 |
29 | v0.8.3
30 | ------
31 | - Nicer error message for Windows/OSX.
32 |
33 | v0.8.2
34 | ------
35 | - More robust OS and serial port check.
36 |
37 | v0.8.1
38 | ------
39 | - Figures out default serial port for Raspberry Pi 2 and below,
40 | Raspberry Pi 3 and above and MacOS.
41 |
42 | v0.8.0
43 | ------
44 | - Added servo support.
45 |
46 | v0.7.4
47 | ------
48 | - Fixed a bug with io_pwm() running three times faster than it should.
49 | Fixes #15.
50 |
51 | v0.7.3
52 | ------
53 | - Fixed a bug with colourtail timing issue in the firmware.
54 |
55 | v0.7.2
56 | ------
57 | - Fixed a bug with colourtail using the new set_bulk.
58 |
59 | v0.7.1
60 | ------
61 | - Fixed a bug with set_bulk and updated tests.
62 |
63 | v0.7.0
64 | ------
65 | - Fixed bytes error in serial_channel_device -- and/or/bulk commands
66 | work again.
67 | - Added support for analogue inputs and PWM.
68 |
69 | v0.6.1
70 | ------
71 | - Fixed error with `set_pullup`. Fixes issue #14.
72 |
73 | v0.6.0
74 | ------
75 | - Added UART support.
76 |
77 | v0.5.0
78 | ------
79 | - Updated packet layer, better support for bulk commands and AND/OR masks.
80 | - Added extension pin control.
81 | - Added I2C/SPI support.
82 | - Added Colour Tail (WS2812) support.
83 |
84 | v0.4.3
85 | ------
86 | - Updated docs.
87 |
88 | v0.4.2
89 | ------
90 | - Fixed `set_output()` but where setting value of one leg would reset
91 | the other legs.
92 |
93 | v0.4.1
94 | ------
95 | - Added timeout to serial initialisation and updated charmap `led_state`
96 | to `pixel_state` to match previous change.
97 | - Added `set_leg_io` method.
98 |
99 | v0.4.0
100 | ------
101 | - Changed led -> pixel
102 |
103 | v0.3.0
104 | ------
105 | - Removed confusing channel list.
106 | - Ready for release on GitHub.
107 |
108 | v0.2.0
109 | ------
110 | - Added and_mask into set packets.
111 |
112 | v0.1.2
113 | ------
114 | - Added some more examples.
115 | - Updated the readme.
116 |
117 | v0.1.1
118 | ------
119 | - Fixed CodeBug.get_input().
120 |
121 | v0.1.0
122 | ------
123 | - Inital dev release.
124 |
125 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
2 | include CHANGELOG
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | CodeBug Tether
2 | ==============
3 | Control CodeBug in tethered mode over Serial USB.
4 |
5 | Documentation: http://codebug-tether.readthedocs.org/
6 |
7 | Features:
8 |
9 | - LED control
10 | - Inputs/Outputs (legs, buttons, extension pins)
11 | - Input/Output configuration (direction and pullups)
12 | - Extension pin control (I/O, SPI, I2C)
13 |
14 |
15 | Updating Notes
16 | --------------
17 | Be sure to update the version number in:
18 |
19 | codebug_tether/version.py
20 | CHANGELOG
21 | docs/conf.py
22 |
--------------------------------------------------------------------------------
/cblrx/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT=cblrx
2 | SOURCES=src/cblrx.c
3 | LIBRARY=
4 | INCPATHS=
5 | LIBPATHS=
6 | LDFLAGS=
7 | CFLAGS=-c -Wall
8 | CC=gcc
9 |
10 | # ------------ MAGIC BEGINS HERE -------------
11 |
12 | # Automatic generation of some important lists
13 | OBJECTS=$(SOURCES:.c=.o)
14 | INCFLAGS=$(foreach TMP,$(INCPATHS),-I$(TMP))
15 | LIBFLAGS=$(foreach TMP,$(LIBPATHS),-L$(TMP))
16 |
17 | # Set up the output file names for the different output types
18 | ifeq "$(LIBRARY)" "shared"
19 | BINARY=lib$(PROJECT).so
20 | LDFLAGS += -shared
21 | else ifeq "$(LIBRARY)" "static"
22 | BINARY=lib$(PROJECT).a
23 | else
24 | BINARY=$(PROJECT)
25 | endif
26 |
27 | all: $(SOURCES) $(BINARY)
28 |
29 | $(BINARY): $(OBJECTS)
30 | # Link the object files, or archive into a static library
31 | ifeq "$(LIBRARY)" "static"
32 | ar rcs $(BINARY) $(OBJECTS)
33 | else
34 | $(CC) $(LIBFLAGS) $(OBJECTS) $(LDFLAGS) -o $@
35 | endif
36 |
37 | .c.o:
38 | $(CC) $(INCFLAGS) $(CFLAGS) -fPIC $< -o $@
39 |
40 | distclean: clean
41 | rm -f $(BINARY)
42 |
43 | clean:
44 | rm -f $(OBJECTS)
--------------------------------------------------------------------------------
/cblrx/src/cblrx.c:
--------------------------------------------------------------------------------
1 | // stdlib requires this before #define or segfault on ptsname
2 | #define _XOPEN_SOURCE 600
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 |
11 | #define PKT_BUF_SIZE 256
12 |
13 | #define CMD_ID(b) ((b >> 5) & 0x7)
14 | // #define CMD_ID_FILTER 0xE0 // top three bits is cmd_id
15 | #define CMD_ID_GET 0
16 | #define CMD_ID_SET 1
17 | #define CMD_ID_GET_BULK 2
18 | #define CMD_ID_SET_BULK 3
19 | #define CMD_ID_READ 4
20 | #define CMD_ID_WRITE 5
21 | #define CMD_ID_ACK 6
22 |
23 | #define CH_INDEX(b) ((b >> 2) & 0x7)
24 | #define OR_MASK(b) ((b >> 1) & 0x1)
25 |
26 |
27 | char rows[7] = {0, 0, 0, 0, 0, 0, 0};
28 |
29 |
30 | int openpt(void);
31 | char get_channel(int i);
32 | void set_channel(int i, char v, char or_mask);
33 | void draw_codebug(void);
34 | void send_ack(int fd);
35 |
36 |
37 | int main(void)
38 | {
39 | // some useful vars
40 | char cv; // channel value
41 | char buf[PKT_BUF_SIZE];
42 | int start_ch, i, len,read_count;
43 |
44 | int fd = openpt();
45 | if (fd < 0) {
46 | return 1;
47 | }
48 |
49 | printf("Fake CodeBug serial port is: %s\n", ptsname(fd));
50 |
51 | while (1) {
52 | // get first byte of packet
53 | read_count = read(fd, buf, PKT_BUF_SIZE);
54 | if (read_count < 0) {
55 | fprintf(stderr, "%s\n", strerror(errno));
56 | break;
57 | }
58 |
59 | // act accordingly
60 | switch (CMD_ID(buf[0])) {
61 | case CMD_ID_GET:
62 | // get and return channel value
63 | cv = get_channel(CH_INDEX(buf[0]));
64 | write(fd, &cv, 1);
65 | break;
66 |
67 | case CMD_ID_SET:
68 | set_channel(CH_INDEX(buf[0]), buf[1], OR_MASK(buf[0]));
69 | send_ack(fd);
70 | break;
71 |
72 | case CMD_ID_GET_BULK:
73 | start_ch = CH_INDEX(buf[0]);
74 | len = buf[1];
75 | for (i = 0; i < len; i++) {
76 | buf[i] = get_channel(start_ch+i);
77 | }
78 | write(fd, buf, len);
79 | break;
80 |
81 | case CMD_ID_SET_BULK:
82 | start_ch = CH_INDEX(buf[0]);
83 | len = buf[1];
84 | for (i = 0; i < len; i++) {
85 | set_channel(start_ch+i, buf[2+i], OR_MASK(buf[0]));
86 | }
87 | send_ack(fd);
88 | break;
89 |
90 | case CMD_ID_READ:
91 | printf("cmd: CMD_ID_READ\n");
92 | break;
93 |
94 | case CMD_ID_WRITE:
95 | printf("cmd: CMD_ID_WRITE\n");
96 | break;
97 |
98 | default:
99 | printf("ERR:Could not determine cmd.\n");
100 | return 1;
101 | }
102 |
103 | // displaying 'leds'
104 | system("clear");
105 | draw_codebug();
106 | }
107 |
108 | return 0;
109 | }
110 |
111 | int openpt(void)
112 | {
113 | int fd = posix_openpt(O_RDWR);
114 | if (fd < 0) {
115 | fprintf(stderr, "Error %d on posix_openpt()\n", errno);
116 | return -1;
117 | }
118 |
119 | // using read_count here becasue we don't need it yet
120 | if (grantpt(fd) != 0) {
121 | fprintf(stderr, "Error %d on grantpt()\n", errno);
122 | return -1;
123 | }
124 |
125 | if (unlockpt(fd) != 0) {
126 | fprintf(stderr, "Error %d on unlockpt()\n", errno);
127 | return -1;
128 | }
129 |
130 | return fd;
131 | }
132 |
133 | char get_channel(int i)
134 | {
135 | return rows[i] & 0x1f; // get_row
136 | }
137 |
138 | void set_channel(int i, char v, char or_mask)
139 | {
140 | if (or_mask) {
141 | v |= get_channel(i);
142 | }
143 | rows[i] = v & 0x1f; // set_row
144 | }
145 |
146 | void draw_codebug(void)
147 | {
148 | int i, j;
149 | char row[6] = {0, 0, 0, 0, 0, 0}; // sixth is EOL
150 | for (i = 4; i >= 0; i--) {
151 | for (j = 0; j <= 4; j++) {
152 | row[4-j] = (rows[i] >> j) & 1 ? '#' : '-';
153 | }
154 | printf("%s\n", row);
155 | }
156 | }
157 |
158 | void send_ack(int fd)
159 | {
160 | const char ack_pkt = CMD_ID_ACK << 5;
161 | write(fd, &ack_pkt, 1);
162 | }
163 |
--------------------------------------------------------------------------------
/codebug_tether/__init__.py:
--------------------------------------------------------------------------------
1 | from codebug_tether.core import (CodeBug,
2 | IO_DIGITAL_OUTPUT,
3 | IO_DIGITAL_INPUT,
4 | IO_ANALOGUE_INPUT,
5 | IO_PWM_OUTPUT,
6 | T2_PS_1_1,
7 | T2_PS_1_4,
8 | T2_PS_1_16,
9 | scale)
10 |
--------------------------------------------------------------------------------
/codebug_tether/colourtail.py:
--------------------------------------------------------------------------------
1 | """Colour tails interface for CodeBug."""
2 | from collections import namedtuple
3 | from codebug_tether.core import (CHANNEL_INDEX_COLOURTAIL_LENGTH,
4 | CHANNEL_INDEX_COLOURTAIL_CONTROL)
5 |
6 |
7 | # control
8 | # bit 1
9 | COLOURTAIL_CONTROL_GO_BUSY = 0x01
10 | # bit 2
11 | COLOURTAIL_CONTROL_INIT_NOT_UPDATE = 0x02
12 | # bit 3-8 (init bits - only work when COLOURTAIL_CONTROL_INIT_NOT_UPDATE == 1)
13 | COLOURTAIL_CONTROL_LEG0_NOT_CS = 0x04
14 |
15 | PIXEL_BUFFER_SIZE = 50
16 |
17 |
18 | RGBPixel = namedtuple('RGBPixel', ['red', 'green', 'blue'])
19 |
20 |
21 | class CodeBugColourTail():
22 | """CodeBugColourTail stores and sends RGB pixel values to a connected
23 | CodeBug Colour Tail (strip of WS2812s).
24 |
25 | You can use either the CS pin on the extension port or leg 0 to output
26 | colour tail value.
27 |
28 | Example use:
29 |
30 | from codebug_tether import CodeBug
31 | from codebug_tether.colourtail import CodeBugColourTail
32 |
33 | codebug = CodeBug()
34 | colourtail = CodeBugColourTail(codebug)
35 |
36 | # using CS pin
37 | colourtail.init()
38 | colourtail.set_pixel(0, 255, 0, 0) # red
39 | colourtail.set_pixel(1, 0, 255, 0) # green
40 | colourtail.set_pixel(2, 0, 0, 255) # blue
41 | colourtail.update() # turn on the LEDs
42 |
43 | # use leg 0 instead
44 | colourtail.init(use_leg_0_not_cs=True)
45 | colourtail.update()
46 |
47 | You can set the pixel buffer manually like so:
48 |
49 | from codebug_tether import CodeBug
50 | from codebug_tether.colourtail import (CodeBugColourTail, RGBPixel)
51 |
52 | codebug = CodeBug()
53 | colourtail = CodeBugColourTail(codebug)
54 |
55 | # using CS pin
56 | colourtail.init()
57 | colourtail.pixel_buffer[0] = RGBPixel(255, 0, 0)
58 | colourtail.pixel_buffer[1] = RGBPixel(0, 255, 0)
59 | colourtail.pixel_buffer[1] = RGBPixel(0, 0, 255)
60 | colourtail.update() # turn on the LEDs
61 |
62 | """
63 |
64 | pixel_buffer = [RGBPixel(0, 0, 0)]*PIXEL_BUFFER_SIZE
65 |
66 | def __init__(self, codebug):
67 | self.codebug = codebug
68 |
69 | def init(self, use_leg_0_not_cs=False):
70 | control = (COLOURTAIL_CONTROL_GO_BUSY |
71 | COLOURTAIL_CONTROL_INIT_NOT_UPDATE)
72 | if use_leg_0_not_cs:
73 | control |= COLOURTAIL_CONTROL_LEG0_NOT_CS
74 | self.codebug.set(CHANNEL_INDEX_COLOURTAIL_CONTROL, control)
75 |
76 | def get_pixel(self, index):
77 | return self.pixel_buffer[index]
78 |
79 | def set_pixel(self, index, red, green, blue):
80 | self.pixel_buffer[index] = RGBPixel(red=red, green=green, blue=blue)
81 |
82 | def update(self):
83 | # WS2812 order is green, red, blue
84 | codebug_buffer = [value
85 | for pixel in self.pixel_buffer[:PIXEL_BUFFER_SIZE]
86 | for value in (pixel.green, pixel.red, pixel.blue)]
87 | control = COLOURTAIL_CONTROL_GO_BUSY
88 | self.codebug.set_buffer(0, bytes(codebug_buffer))
89 | self.codebug.set_bulk(CHANNEL_INDEX_COLOURTAIL_LENGTH,
90 | bytes((len(self.pixel_buffer), control)))
91 |
--------------------------------------------------------------------------------
/codebug_tether/core.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | import time
3 | import serial
4 | import struct
5 | from .i2c import *
6 | from .serial_channel_device import SerialChannelDevice
7 | from .platform import get_platform_serial_port
8 |
9 |
10 | DEFAULT_SERIAL_PORT = get_platform_serial_port()
11 |
12 | IO_DIGITAL_OUTPUT = 0
13 | IO_DIGITAL_INPUT = 1
14 | IO_ANALOGUE_INPUT = 2
15 | IO_PWM_OUTPUT = 3
16 |
17 | # CHANNEL_INDEX_ROW_0 = 0
18 | # CHANNEL_INDEX_ROW_1 = 1
19 | # CHANNEL_INDEX_ROW_2 = 2
20 | # CHANNEL_INDEX_ROW_3 = 3
21 | # CHANNEL_INDEX_ROW_4 = 4
22 | (CHANNEL_INDEX_OUTPUT,
23 | CHANNEL_INDEX_LEG_INPUT,
24 | CHANNEL_INDEX_BUTTON_INPUT,
25 | CHANNEL_INDEX_ANALOGUE_CONF,
26 | CHANNEL_INDEX_ANALOGUE_INPUT,
27 | CHANNEL_INDEX_IO_DIRECTION_LEGS,
28 | CHANNEL_INDEX_IO_DIRECTION_EXT,
29 | CHANNEL_INDEX_PULLUPS,
30 | CHANNEL_INDEX_EXT_CONF,
31 | CHANNEL_INDEX_SPI_RATE,
32 | CHANNEL_INDEX_SPI_LENGTH,
33 | CHANNEL_INDEX_SPI_CONTROL,
34 | CHANNEL_INDEX_I2C_ADDR,
35 | CHANNEL_INDEX_I2C_LENGTH,
36 | CHANNEL_INDEX_I2C_CONTROL,
37 | CHANNEL_INDEX_UART_RX_OFFSET,
38 | CHANNEL_INDEX_UART_RX_LENGTH,
39 | CHANNEL_INDEX_UART_TX_OFFSET,
40 | CHANNEL_INDEX_UART_TX_LENGTH,
41 | CHANNEL_INDEX_UART_CONTROL,
42 | CHANNEL_INDEX_COLOURTAIL_LENGTH,
43 | CHANNEL_INDEX_COLOURTAIL_CONTROL,
44 | CHANNEL_INDEX_PWM_CONF_0,
45 | CHANNEL_INDEX_PWM_CONF_1,
46 | CHANNEL_INDEX_PWM_CONF_2,
47 | CHANNEL_INDEX_SERVO_PULSE_LENGTH,
48 | CHANNEL_INDEX_SERVO_CONF) = range(5, 32)
49 |
50 | EXTENSION_CONF_IO = 0x01
51 | EXTENSION_CONF_SPI = 0x02
52 | EXTENSION_CONF_I2C = 0x04
53 | EXTENSION_CONF_UART = 0x08
54 |
55 | UART_TX_BUFFER_INDEX = 0
56 | UART_RX_BUFFER_INDEX = 1
57 |
58 | UART_TX_GO_BUSY_MASK = 0x01
59 | UART_RX_GO_BUSY_MASK = 0x02
60 | UART_BAUD_300 = 0 << 2
61 | UART_BAUD_1200 = 1 << 2
62 | UART_BAUD_2400 = 2 << 2
63 | UART_BAUD_9600 = 3 << 2
64 | UART_BAUD_10417 = 4 << 2
65 | UART_BAUD_19200 = 5 << 2
66 | UART_BAUD_57600 = 6 << 2
67 | UART_BAUD_115200 = 7 << 2
68 |
69 | UART_DEFAULT_BAUD = 9600
70 |
71 | T2_PS_1_1 = 0
72 | T2_PS_1_4 = 1
73 | T2_PS_1_16 = 2
74 |
75 |
76 | class InvalidBaud(Exception):
77 | pass
78 |
79 |
80 | class CodeBug(SerialChannelDevice):
81 | """Manipulates CodeBug over a USB serial connection."""
82 |
83 | def __init__(self, serial_port=DEFAULT_SERIAL_PORT):
84 | super(CodeBug, self).__init__(serial.Serial(serial_port, timeout=2))
85 |
86 | def _int_input_index(self, input_index):
87 | """Returns an integer input index."""
88 | # 'A' is 8, 'B' is 9
89 | if isinstance(input_index, str):
90 | input_index = 8 if 'a' in input_index.lower() else 9
91 | return input_index
92 |
93 | def get_input(self, input_index):
94 | """Returns the state of an input. You can use 'A' and 'B' to
95 | access buttons A and B.
96 |
97 | >>> codebug = CodeBug()
98 | >>> codebug.get_input('A') # switch A is pressed
99 | 1
100 | >>> codebug.get_input(0) # assuming leg 0 is connected to GND
101 | 0
102 | >>> codebug.get_input(4) # extension I/O pin 4 is connected to GND
103 | 0
104 |
105 | """
106 | input_index = self._int_input_index(input_index)
107 | if input_index > 7:
108 | channel_index = CHANNEL_INDEX_BUTTON_INPUT
109 | input_index -= 8
110 | else:
111 | channel_index = CHANNEL_INDEX_LEG_INPUT
112 | return self.get_bit(channel_index, input_index)
113 |
114 | def read_analogue(self, leg_index):
115 | """Reads the analogue value of the leg at leg_index. The leg must
116 | first be configured as an analogue input. For example:
117 |
118 | >>> codebug = CodeBug()
119 | >>> codebug.set_leg_io(0, IO_ANALOG_INPUT)
120 | >>> codebug.read_analogue(0)
121 | 128
122 |
123 | """
124 | # set which leg to read (and do the read)
125 | self.set(CHANNEL_INDEX_ANALOGUE_CONF, leg_index)
126 | # return the value
127 | analogue_value = self.get(CHANNEL_INDEX_ANALOGUE_INPUT)
128 | return struct.unpack('B', analogue_value)[0]
129 |
130 | def set_pullup(self, input_index, state):
131 | """Sets the state of the input pullups. Turn off to enable touch
132 | sensitive pads (bridge GND and input with fingers).
133 |
134 | >>> codebug = CodeBug()
135 | >>> codebug.set_pullup(0, 1) # input pad 0 <10K OHMS
136 | >>> codebug.set_pullup(2, 0) # input pad 2 <22M OHMS touch sensitive
137 |
138 | """
139 | input_index = self._int_input_index(input_index)
140 | self.set_bit(CHANNEL_INDEX_PULLUPS, input_index, state)
141 |
142 | def set_output(self, output_index, state):
143 | """Sets the output index to state."""
144 | self.set_bit(CHANNEL_INDEX_OUTPUT, output_index, state)
145 |
146 | def get_output(self, output_index):
147 | """Returns the state of the output at index."""
148 | return self.get_bit(CHANNEL_INDEX_OUTPUT, output_index)
149 |
150 | def set_leg_io(self, leg_index, direction):
151 | """Sets the I/O direction of the leg at index. For example:
152 |
153 | >>> codebug = CodeBug()
154 | >>> codebug.set_leg_io(0, IO_DIGITAL_OUTPUT)
155 | >>> codebug.set_leg_io(0, IO_PWM_OUTPUT)
156 | >>> codebug.set_leg_io(1, IO_DIGITAL_INPUT)
157 | >>> codebug.set_leg_io(2, IO_ANALOG_INPUT)
158 |
159 | """
160 | if leg_index < 4:
161 | clear_mask = 0xff ^ (0b11 << leg_index * 2)
162 | direction_mask = (0b11 & direction) << leg_index * 2
163 | self.and_mask(CHANNEL_INDEX_IO_DIRECTION_LEGS, clear_mask)
164 | self.or_mask(CHANNEL_INDEX_IO_DIRECTION_LEGS, direction_mask)
165 | else:
166 | ext_index = leg_index - 4
167 | clear_mask = 0b11 << ext_index * 2
168 | direction_mask = (0b11 & direction) << ext_index * 2
169 | self.and_mask(CHANNEL_INDEX_IO_DIRECTION_EXT, clear_mask)
170 | self.or_mask(CHANNEL_INDEX_IO_DIRECTION_EXT, direction_mask)
171 |
172 | def pwm_on(self, t2_prescale, full_period, on_period):
173 | """Turns on the PWM generator with the given settings.
174 |
175 | Args:
176 | t2_prescale: One of T2_PS_1_1, T2_PS_1_4, T2_PS_1_16
177 | Scales down the 12MHz instruction clock by
178 | 1, 4 or 16.
179 | full_period: 8-bit value - which is scaled up to 10-bits
180 | (<< 2) - to which timer 2 will count up to
181 | before resetting PWM output to 1.
182 | on_period: 10-bit value to which timer 2 will count up to
183 | before setting PWM output to 0. Use this with
184 | full_period to control duty cycle. For example:
185 |
186 | # 12MHz / 16 with 50% duty cycle
187 | codebug.pwm_on(T2_PS_1_16, 0xff, 0x200)
188 |
189 | """
190 | # full period
191 | self.set(CHANNEL_INDEX_PWM_CONF_0, full_period)
192 | self.set(CHANNEL_INDEX_PWM_CONF_1, on_period & 0xff)
193 | go_busy = 1
194 | top_two_bit_on_period = (on_period >> 8) & 0b11
195 | conf = go_busy << 4 | t2_prescale << 2 | top_two_bit_on_period
196 | self.set(CHANNEL_INDEX_PWM_CONF_2, conf)
197 |
198 | def pwm_freq(self, frequency):
199 | """Turns on the PWM generator with the given frequency. For example:
200 |
201 | >>> codebug = CodeBug()
202 | >>> codebug.set_leg_io(0, IO_PWM_OUTPUT)
203 | >>> codebug.pwm_freq(1046)
204 | >>> time.sleep(2)
205 | >>> codebug.pwm_off()
206 |
207 | """
208 | # calculate pwm settings
209 | # 12MHz / 16 = 750k ticks per second
210 | full_period = int(750000 / frequency) - 1
211 | # for 50% duty cycle: shift up by 2 then /(2 i.e. 50% duty cycle)
212 | # on_period = (full_period << 2) / 2;
213 | # this is quicker
214 | on_period = full_period << 1
215 | self.pwm_on(T2_PS_1_16, full_period, on_period)
216 |
217 | def pwm_off(self):
218 | """Turns off the PWM generator."""
219 | go_busy_off_mask = 0xff ^ (1 << 4)
220 | self.and_mask(CHANNEL_INDEX_PWM_CONF_2, go_busy_off_mask)
221 |
222 | def servo_set(self, servo_index, pulse_length):
223 | """Set the servo at servo_index to pulse_length. Make sure that
224 | the leg is configured as IO_DIGITAL_OUTPUT (0).
225 | """
226 | pulse_length_msb = 0xff & (pulse_length >> 8)
227 | pulse_length_lsb = 0xff & pulse_length
228 | conf_msb = ((servo_index & 0xf) << 4) | 0x01
229 | conf_lsb = ((servo_index & 0xf) << 4) | 0x00
230 | self.set_bulk(CHANNEL_INDEX_SERVO_PULSE_LENGTH,
231 | bytes([pulse_length_msb, conf_msb]))
232 | self.set_bulk(CHANNEL_INDEX_SERVO_PULSE_LENGTH,
233 | bytes([pulse_length_lsb, conf_lsb]))
234 |
235 | def clear(self):
236 | """Clears the pixels on CodeBug.
237 |
238 | >>> codebug = CodeBug()
239 | >>> codebug.clear()
240 |
241 | """
242 | self.set_bulk(0, bytes([0]*5))
243 |
244 | def fill(self):
245 | """Sets all pixels on.
246 |
247 | >>> codebug = CodeBug()
248 | >>> codebug.fill()
249 |
250 | """
251 | self.set_bulk(0, bytes([0x1f]*5))
252 |
253 | def set_row(self, row, val):
254 | """Sets a row of PIXELs on CodeBug.
255 |
256 | >>> codebug = CodeBug()
257 | >>> codebug.set_row(0, 0b10101)
258 |
259 | """
260 | self.set(row, val)
261 |
262 | def get_row(self, row):
263 | """Returns a row of pixels on CodeBug.
264 |
265 | >>> codebug = CodeBug()
266 | >>> codebug.get_row(0)
267 | 21
268 |
269 | """
270 | row = self.get(min(row, 5)) # only row channels
271 | return struct.unpack('B', row)[0]
272 |
273 | def set_col(self, col, val):
274 | """Sets an entire column of PIXELs on CodeBug.
275 |
276 | >>> codebug = CodeBug()
277 | >>> codebug.set_col(0, 0b10101)
278 |
279 | """
280 | rows = struct.unpack('B'*5, self.get_bulk(0, 5))
281 | # clear col
282 | rows = [rows[i] & (0xff ^ (1 << (4-col))) for i in range(5)]
283 | # set cols
284 | val_bits = [(val >> i) & 1 for i in reversed(range(5))]
285 | rows = [rows[i] | (bit << (4-col)) for i, bit in enumerate(val_bits)]
286 | self.set_bulk(0, bytes(rows))
287 |
288 | def get_col(self, col):
289 | """Returns an entire column of PIXELs on CodeBug.
290 |
291 | >>> codebug = CodeBug()
292 | >>> codebug.get_col(0)
293 | 21
294 |
295 | """
296 | rows = struct.unpack('B'*5, self.get_bulk(0, 5))
297 | c = 0
298 | for row in rows:
299 | c <<= 1
300 | col_bit = 1 & (row >> (4 - col))
301 | c |= col_bit
302 | return c
303 |
304 | def set_pixel(self, x, y, state):
305 | """Sets an PIXEL on CodeBug.
306 |
307 | >>> codebug = CodeBug()
308 | >>> codebug.set_pixel(0, 0, 1)
309 |
310 | """
311 | channel = min(y, 5) # only row channels
312 | bit_index = 4 - x
313 | self.set_bit(channel, bit_index, state)
314 |
315 | def get_pixel(self, x, y):
316 | """Returns the state of an PIXEL on CodeBug.
317 |
318 | >>> codebug = CodeBug()
319 | >>> codebug.get_pixel(0, 0)
320 | 1
321 |
322 | """
323 | channel = min(y, 5)
324 | bit_index = 4 - x
325 | return self.get_bit(channel, bit_index)
326 |
327 | def draw_sprite(self, x, y, sprite, clear_first=True):
328 | """Draws a sprite at (x, y) on CodeBug's 5x5 display."""
329 | cb_display_sprite = sprite.get_sprite(-x, -y, 5, 5)
330 | cb_rows = [cb_display_sprite.get_row(y)
331 | for y in range(cb_display_sprite.height)]
332 | if clear_first:
333 | self.set_bulk(0, bytes(cb_rows))
334 | else:
335 | for i, row in enumerate(cb_rows):
336 | self.or_mask(i, bytes(row))
337 |
338 | def scroll_sprite(self, sprite, interval=0.1, direction='L'):
339 | """Scrolls a sprite.
340 |
341 | Args:
342 | sprite: The sprite to scroll.
343 | interval: The time delay between each movement in seconds.
344 | (optional)
345 | direction: The direction of the scroll ('L', 'R', 'U', 'D').
346 |
347 | """
348 | direction = direction.upper()[0] # only take the first char
349 | if direction == 'L':
350 | for i in range(sprite.width+5):
351 | self.draw_sprite(5-i, 0, sprite)
352 | time.sleep(interval)
353 | elif direction == 'D':
354 | for i in range(sprite.height+5):
355 | self.draw_sprite(0, 5-i, sprite)
356 | time.sleep(interval)
357 | elif direction == 'R':
358 | for i in reversed(range(sprite.width+5)):
359 | self.draw_sprite(5-i, 0, sprite)
360 | time.sleep(interval)
361 | elif direction == 'U':
362 | for i in reversed(range(sprite.height+5)):
363 | self.draw_sprite(0, 5-i, sprite)
364 | time.sleep(interval)
365 |
366 | def config_extension_io(self):
367 | self.set(CHANNEL_INDEX_EXT_CONF, EXTENSION_CONF_IO)
368 |
369 | def config_extension_spi(self):
370 | self.set(CHANNEL_INDEX_EXT_CONF, EXTENSION_CONF_SPI)
371 |
372 | def config_extension_i2c(self):
373 | self.set(CHANNEL_INDEX_EXT_CONF, EXTENSION_CONF_I2C)
374 |
375 | def config_extension_uart(self):
376 | self.set(CHANNEL_INDEX_EXT_CONF, EXTENSION_CONF_UART)
377 |
378 | def spi_transaction(self,
379 | data,
380 | cs_idle_high=1,
381 | input_sample_middle=1,
382 | spi_mode=0):
383 | """Run an SPI transaction using the extensions pins. Be sure to
384 | configure the extension pins first.
385 |
386 | Example:
387 |
388 | >>> import codebug_tether
389 | >>>
390 | >>> # setup
391 | >>> codebug = codebug_tether.CodeBug()
392 | >>> codebug.config_extension_spi()
393 | >>>
394 | >>> # transaction
395 | >>> tx = bytes((0x01, 0x02, 0x03)) # transmit this data
396 | >>> rx = codebug.spi_transaction(tx) # transaction returns data
397 | >>> print(rx)
398 | b'\xff\xff\xff'
399 |
400 | """
401 | # control channel
402 | spi_mode = (spi_mode & 0x03) << 3
403 | input_sample_middle = (input_sample_middle & 1) << 2
404 | cs_idle_high = (cs_idle_high & 1) << 1
405 | go = 0x01
406 | control = spi_mode | input_sample_middle | cs_idle_high | go
407 | # put data into the buffer
408 | self.set_buffer(0, bytes(list(data)))
409 | # set the length and control channels in one go
410 | self.set_bulk(CHANNEL_INDEX_SPI_LENGTH, bytes([len(data), control]))
411 | # return data from buffer
412 | return self.get_buffer(0, len(data))
413 |
414 | def i2c_transaction(self,
415 | *messages,
416 | add_stop_last_message=True,
417 | interval=0):
418 | """Run an I2C transaction using the extensions pins. Be sure to
419 | configure the extension pins first.
420 |
421 | Args:
422 | messages: The I2C messages.
423 | add_stop_last_message: Adds stop flag to the last
424 | I2CMessage.
425 | interval: Adds delay of `interval` seconds between I2C
426 | messages.
427 |
428 | Example:
429 |
430 | >>> import codebug_tether
431 | >>> from codebug_tether.i2c import (reading, writing)
432 | >>>
433 | >>> # example I2C address
434 | >>> i2c_addr = 0x1C
435 | >>>
436 | >>> # setup
437 | >>> codebug = codebug_tether.CodeBug()
438 | >>> codebug.config_extension_i2c()
439 |
440 | Single byte read transaction (read reg 0x12)
441 |
442 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12), # reg addr
443 | reading(i2c_addr, 1)) # read 1 reg
444 | (42,)
445 |
446 | Multiple byte read transaction (read regs 0x12-0x17)
447 |
448 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12), # reg addr
449 | reading(i2c_addr, 6)) # read 6 reg
450 | (65, 87, 47, 91, 43, 60)
451 |
452 | Single byte write transaction (write value 0x34 to reg 0x12)
453 |
454 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12, 0x34))
455 |
456 | Multiple byte write transaction
457 | (write values 0x34, 0x56, 0x78 to reg 0x12)
458 |
459 | >>> codebug.i2c_transaction(
460 | writing(i2c_addr, 0x12, 0x34, 0x56, 0x78))
461 |
462 | """
463 | # Can't use a tuple here because `+=` inside `send_msg` implicitly
464 | # declares rx_buffer as a local variable (to send_msg).
465 | rx_buffer = list()
466 |
467 | def send_msg(msg):
468 | """Sends a single i2c message."""
469 | # print("send_msg")
470 | # print("address", hex(msg.address))
471 | # print("msg.data", msg.data)
472 | # print("length", msg.length)
473 | # print("control", bin(msg.control))
474 | # print()
475 | self.set_buffer(0, bytes(msg.data))
476 | # set the i2c address, length and control all in one go
477 | self.set_bulk(CHANNEL_INDEX_I2C_ADDR,
478 | bytes([msg.address, msg.length, msg.control]))
479 | # if reading, add data to rx_buffer
480 | if msg.control & I2C_CONTROL_READ_NOT_WRITE:
481 | values = struct.unpack('B'*msg.length,
482 | self.get_buffer(0, msg.length))
483 | rx_buffer.extend(values)
484 | time.sleep(interval)
485 |
486 | if add_stop_last_message:
487 | # send all messages except for the last one
488 | for message in messages[:-1]:
489 | send_msg(message)
490 |
491 | # add stop control flag to the last message
492 | messages[-1].control |= I2C_CONTROL_STOP
493 | send_msg(messages[-1])
494 |
495 | else:
496 | # send all messages
497 | for message in messages:
498 | send_msg(message)
499 |
500 | return tuple(rx_buffer)
501 |
502 | def _get_uart_control_baud(self, baud):
503 | """Returns UART control value for given baud rate. Will raise
504 | InvalidBaud exception if baud is invalid.
505 | """
506 | baud_control = {300: 0 << 2,
507 | 1200: 1 << 2,
508 | 2400: 2 << 2,
509 | 9600: 3 << 2,
510 | 10417: 4 << 2,
511 | 19200: 5 << 2,
512 | 57600: 6 << 2,
513 | 115200: 7 << 2}
514 | if baud not in baud_control:
515 | raise InvalidBaud('{} is not a valid baud rate (valid baud '
516 | 'rates: {}).'.format(baud, tuple(baud_control.keys())))
517 | else:
518 | return baud_control[baud]
519 |
520 | def uart_set_baud(self, baud):
521 | self.set(CHANNEL_INDEX_UART_CONTROL, self._get_uart_control_baud(baud))
522 |
523 | def uart_tx(self, data_bytes, baud=UART_DEFAULT_BAUD):
524 | """Transmits data bytes over UART. Use this if you just want to
525 | send X amount of data. Be sure to configure the extension pins
526 | first. For example:
527 |
528 | >>> from codebug_tether import CodeBug
529 | >>> codebug = CodeBug()
530 | >>> codebug.config_extension_uart()
531 | >>> # send 0xAA, 0xBB over UART
532 | >>> codebug.uart_tx(bytes((0xAA, 0xBB)))
533 | >>> # send 0xAA, 0xBB over UART at 300 baud
534 | >>> codebug.uart_tx(bytes((0xAA, 0xBB)), baud=300)
535 |
536 | """
537 | self.uart_tx_set_buffer(data_bytes)
538 | self.uart_tx_start(len(data_bytes))
539 |
540 | def uart_tx_start(self, length, offset=0, baud=UART_DEFAULT_BAUD):
541 | """Transmits 'length' data bytes from UART buffer starting at
542 | 'offset' over UART. Be sure to configure the extension pins
543 | first. For example, you might want to fill the buffer with two
544 | commands (0xAA and 0xBB) which are sent over UART and only send
545 | one at a time:
546 |
547 | >>> from codebug_tether import CodeBug
548 | >>> codebug = CodeBug()
549 | >>> codebug.config_extension_uart()
550 | >>> codebug.uart_tx_set_buffer(bytes((0xAA, 0xBB)))
551 | >>> codebug.uart_tx_start(1, offset=0) # send 0xAA over UART
552 | >>> codebug.uart_tx_start(1, offset=1) # send 0xBB over UART
553 | >>> # send 0xAA over UART at 300 baud
554 | >>> codebug.uart_tx_start(1, offset=0, baud=300)
555 |
556 | """
557 | control = self._get_uart_control_baud(baud) | UART_TX_GO_BUSY_MASK
558 | self.set_bulk(CHANNEL_INDEX_UART_TX_OFFSET,
559 | bytes((offset, length, control)))
560 |
561 | def uart_tx_set_buffer(self, data_bytes, offset=0):
562 | """Add data_bytes to the UART buffer at offset."""
563 | self.set_buffer(UART_TX_BUFFER_INDEX, data_bytes, offset)
564 |
565 | def uart_rx_start(self, length, baud=UART_DEFAULT_BAUD, offset=0):
566 | """Begins receiving on the UART. RX will stop when length data is
567 | reached. Be sure to configure the extension pins first. For example
568 |
569 | >>> from codebug_tether import CodeBug
570 | >>> codebug = CodeBug()
571 | >>> codebug.config_extension_uart()
572 | >>> codebug.uart_rx_start(2) # ready to receive 2B over UART
573 | >>> # wait until data ready (alternatively, sleep X seconds)
574 | >>> while not codebug.uart_rx_is_ready():
575 | ... pass
576 | ...
577 | >>> codebug.uart_rx_get_buffer(2) # read out the two bytes
578 |
579 | """
580 | self.set_bulk(CHANNEL_INDEX_UART_RX_OFFSET, bytes((offset, length)))
581 | self.set(CHANNEL_INDEX_UART_CONTROL,
582 | self._get_uart_control_baud(baud) | UART_RX_GO_BUSY_MASK)
583 |
584 | def uart_rx_is_ready(self):
585 | """Returns True if the UART has finished receiving data."""
586 | uart_control = self.get(CHANNEL_INDEX_UART_CONTROL)[0]
587 | return uart_control & UART_RX_GO_BUSY_MASK == 0
588 |
589 | def uart_rx_get_buffer(self, length, offset=0):
590 | """Returns data bytes from UART buffer."""
591 | return self.get_buffer(UART_RX_BUFFER_INDEX, length, offset)
592 |
593 |
594 | def scale(x, from_low, from_high, to_low, to_high):
595 | # Hardware can only do 16bit maths
596 | def limit(v):
597 | max_value = 0x7fff
598 | min_value = -0x8000
599 | return max(min_value, min(max_value, v))
600 | x, from_low, from_high, to_low, to_high = map(
601 | limit, (x, from_low, from_high, to_low, to_high))
602 | # do the scale
603 | from_delta = from_high - from_low
604 | x_offset = x - from_low
605 | to_delta = to_high - to_low
606 | new_x = int((x_offset * to_delta) / from_delta)
607 | return to_low + new_x
608 |
--------------------------------------------------------------------------------
/codebug_tether/font.py:
--------------------------------------------------------------------------------
1 | class Font(object):
2 | """A pixel map of alphanumerical characters."""
3 |
4 | char_height = None
5 | char_width = None
6 |
7 | def get_char_map(self, character):
8 | raise NotImplementedError("This is a placeholder font.")
9 |
10 |
11 | class FourByFiveFont(Font):
12 |
13 | char_height = 5
14 | char_width = 4
15 |
16 | char_map = {
17 | ' ': [0x0, 0x0, 0x0, 0x0, 0x0],
18 | '!': [0x4, 0x4, 0x4, 0x0, 0x4],
19 | '"': [0xa, 0xa, 0x0, 0x0, 0x0],
20 | '#': [0x6, 0xf, 0x6, 0xf, 0x6],
21 | '$': [0x7, 0xa, 0x6, 0x5, 0xe],
22 | '%': [0x7, 0xe, 0x4, 0x7, 0xe],
23 | '&': [0x2, 0x5, 0x6, 0xa, 0x5],
24 | '\'': [0x1, 0x2, 0x0, 0x0, 0x0],
25 | '(': [0x4, 0x8, 0x8, 0x8, 0x4],
26 | ')': [0x4, 0x2, 0x2, 0x2, 0x4],
27 | '*': [0x0, 0x6, 0xf, 0x6, 0x0],
28 | '+': [0x0, 0x2, 0x7, 0x2, 0x0],
29 | ',': [0x0, 0x0, 0x0, 0x2, 0x4],
30 | '-': [0x0, 0x0, 0x0, 0xf, 0x0],
31 | '.': [0x0, 0x0, 0x0, 0x0, 0x4],
32 | '/': [0x1, 0x1, 0x2, 0x4, 0x8],
33 | '0': [0x6, 0xb, 0xf, 0xd, 0x6],
34 | '1': [0x2, 0x6, 0x2, 0x2, 0x2],
35 | '2': [0xe, 0x1, 0x6, 0x8, 0xf],
36 | '3': [0xe, 0x1, 0x6, 0x1, 0xe],
37 | '4': [0x2, 0x6, 0xa, 0xf, 0x2],
38 | '5': [0xf, 0x8, 0xe, 0x1, 0xe],
39 | '6': [0x6, 0x8, 0xe, 0x9, 0x6],
40 | '7': [0xf, 0x1, 0x2, 0x4, 0x8],
41 | '8': [0x6, 0x9, 0x6, 0x9, 0x6],
42 | '9': [0x6, 0x9, 0xf, 0x1, 0x6],
43 | ':': [0x0, 0x4, 0x0, 0x4, 0x0],
44 | ';': [0x0, 0x4, 0x0, 0x4, 0x8],
45 | '<': [0x2, 0x4, 0x8, 0x4, 0x2],
46 | '=': [0x0, 0xf, 0x0, 0xf, 0x0],
47 | '>': [0x4, 0x2, 0x1, 0x2, 0x4],
48 | '?': [0x6, 0x9, 0x2, 0x0, 0x2],
49 | '@': [0x6, 0xd, 0xb, 0x8, 0x6],
50 | 'A': [0x4, 0xa, 0xe, 0xa, 0xa],
51 | 'B': [0xe, 0x9, 0xe, 0x9, 0xe],
52 | 'C': [0x6, 0x9, 0x8, 0x9, 0x6],
53 | 'D': [0xe, 0x9, 0x9, 0x9, 0xe],
54 | 'E': [0xf, 0x8, 0xe, 0x8, 0xf],
55 | 'F': [0xf, 0x8, 0xe, 0x8, 0x8],
56 | 'G': [0x6, 0x8, 0xb, 0x9, 0x6],
57 | 'H': [0x9, 0x9, 0xf, 0x9, 0x9],
58 | 'I': [0xe, 0x4, 0x4, 0x4, 0xe],
59 | 'J': [0x1, 0x1, 0x1, 0x9, 0x6],
60 | 'K': [0x9, 0xa, 0xc, 0xa, 0x9],
61 | 'L': [0x8, 0x8, 0x8, 0x8, 0xf],
62 | 'M': [0x9, 0xf, 0xf, 0x9, 0x9],
63 | 'N': [0x9, 0xd, 0xf, 0xb, 0x9],
64 | 'O': [0x6, 0x9, 0x9, 0x9, 0x6],
65 | 'P': [0xe, 0x9, 0xe, 0x8, 0x8],
66 | 'Q': [0x6, 0x9, 0x9, 0xb, 0x7],
67 | 'R': [0xe, 0x9, 0xe, 0xa, 0x9],
68 | 'S': [0x7, 0x8, 0x6, 0x1, 0xe],
69 | 'T': [0xe, 0x4, 0x4, 0x4, 0x4],
70 | 'U': [0x9, 0x9, 0x9, 0x9, 0x6],
71 | 'V': [0x9, 0x9, 0x9, 0x6, 0x6],
72 | 'W': [0x9, 0x9, 0xf, 0xf, 0x9],
73 | 'X': [0x9, 0x9, 0x6, 0x9, 0x9],
74 | 'Y': [0x9, 0x5, 0x2, 0x2, 0x2],
75 | 'Z': [0xf, 0x2, 0x4, 0x8, 0xf],
76 | '[': [0xe, 0x8, 0x8, 0x8, 0xe],
77 | '\\': [0x8, 0x8, 0x4, 0x2, 0x1],
78 | ']': [0x7, 0x1, 0x1, 0x1, 0x7],
79 | '^': [0x4, 0xa, 0x0, 0x0, 0x0],
80 | '_': [0x0, 0x0, 0x0, 0x0, 0xf],
81 | '`': [0x4, 0x2, 0x0, 0x0, 0x0],
82 | 'a': [0x0, 0x5, 0xb, 0xb, 0x5],
83 | 'b': [0x8, 0x8, 0xe, 0x9, 0xe],
84 | 'c': [0x0, 0x7, 0x8, 0x8, 0x7],
85 | 'd': [0x1, 0x1, 0x7, 0x9, 0x7],
86 | 'e': [0x0, 0x6, 0xf, 0x8, 0x7],
87 | 'f': [0x3, 0x4, 0xe, 0x4, 0x4],
88 | 'g': [0x7, 0x9, 0x7, 0x1, 0x7],
89 | 'h': [0x8, 0x8, 0xe, 0x9, 0x9],
90 | 'i': [0x0, 0x2, 0x0, 0x2, 0x2],
91 | 'j': [0x1, 0x0, 0x1, 0x1, 0x6],
92 | 'k': [0x8, 0xa, 0xc, 0xa, 0x9],
93 | 'l': [0xc, 0x4, 0x4, 0x4, 0xe],
94 | 'm': [0x0, 0x9, 0xf, 0xf, 0x9],
95 | 'n': [0x0, 0xe, 0x9, 0x9, 0x9],
96 | 'o': [0x0, 0x6, 0x9, 0x9, 0x6],
97 | 'p': [0x0, 0xe, 0x9, 0xe, 0x8],
98 | 'q': [0x0, 0x6, 0x9, 0x7, 0x1],
99 | 'r': [0x0, 0xb, 0xc, 0x8, 0x8],
100 | 's': [0x0, 0x7, 0x4, 0x2, 0xe],
101 | 't': [0x4, 0xe, 0x4, 0x4, 0x3],
102 | 'u': [0x0, 0x9, 0x9, 0x9, 0x6],
103 | 'v': [0x0, 0x9, 0x9, 0x6, 0x6],
104 | 'w': [0x0, 0x9, 0xf, 0xf, 0x6],
105 | 'x': [0x0, 0x9, 0x6, 0x6, 0x9],
106 | 'y': [0x0, 0x9, 0x7, 0x1, 0x6],
107 | 'z': [0x0, 0xf, 0x2, 0x4, 0xf],
108 | '{': [0x6, 0x4, 0xc, 0x4, 0x6],
109 | '|': [0x4, 0x4, 0x0, 0x4, 0x4],
110 | '}': [0xc, 0x4, 0x6, 0x4, 0xc],
111 | '~': [0x0, 0x0, 0x5, 0xa, 0x0],
112 | }
113 |
114 | def get_char_map(self, character):
115 | return self.char_map[character]
116 |
--------------------------------------------------------------------------------
/codebug_tether/i2c.py:
--------------------------------------------------------------------------------
1 | """Handy I2C message building for CodeBug."""
2 | # I2C messages
3 | I2C_CONTROL_GO_BUSY = 0x01
4 | I2C_CONTROL_SEND_ADDR = 0x02
5 | I2C_CONTROL_MASTER_FINAL_ACK = 0x04
6 | I2C_CONTROL_WAIT_FOR_ACK = 0x08
7 | I2C_CONTROL_ACK_AFTER_READ = 0x10
8 | I2C_CONTROL_STOP = 0x20
9 | I2C_CONTROL_START = 0x40
10 | I2C_CONTROL_READ_NOT_WRITE = 0x80
11 |
12 |
13 | class CodeBugI2CMaster():
14 | """Performs I2C I/O transactions on the CodeBug I2C bus.
15 |
16 | Transactions are performed by passing one or more I2C I/O messages
17 | to the transaction method of the I2CMaster. I2C I/O messages are
18 | created with the reading and writing functions defined in the
19 | `codebug_tether.i2c module`.
20 |
21 | CodeBugI2CMaster acts as a context manager, allowing it to be used in a
22 | with statement. This is for compatibility with other I2CMasters,
23 | which this is intended to be used in place of. On its own there is
24 | no need to use this as a context manager.
25 |
26 | For example:
27 |
28 | import codebug_tether
29 | from codebug_tether.i2c import (I2CMaster, writing)
30 |
31 | codebug = codebug_tether.CodeBug()
32 |
33 | with I2CMaster(codebug) as i2c:
34 | i2c.transaction(writing(0x20, bytes([0x01, 0xFF])))
35 |
36 | """
37 | def __init__(self, codebug):
38 | """
39 | :param codebug: The CodeBug through which to send I2C data.
40 | :type codebug: `codebug_tether.core.CodeBug`
41 | """
42 | self.codebug = codebug
43 |
44 | def __enter__(self):
45 | return self
46 |
47 | def __exit__(self, exc_type, exc_value, traceback):
48 | pass
49 |
50 | def transaction(self, *msgs):
51 | """Perform an I2C I/O transaction. I2CMasters usually return one
52 | bytes array per read operation. Since CodeBug is only capable of one
53 | it doens't normally do this.
54 | """
55 | return [bytes(self.codebug.i2c_transaction(*msgs))]
56 |
57 |
58 | class I2CMessage():
59 | """Data structure for building I2C message patterns."""
60 |
61 | def __init__(self, control, address, data, length):
62 | self.control = control
63 | self.address = address
64 | self.data = data
65 | self.length = length
66 |
67 |
68 | # I2C message generators (feel free to go ahead and form your own I2C messages)
69 | def writing_bytes(addr, *data_bytes):
70 | """An I2C I/O message that writes one or more bytes of data.
71 |
72 | Each byte is passed as an argument to this function.
73 |
74 | writing_bytes(addr, 1, 2, 3)
75 |
76 | """
77 | return writing(addr, data_bytes)
78 |
79 |
80 | def writing(address, data_bytes):
81 | """Returns a standard I2C write message. Address is limited to 7 bits.
82 |
83 | The bytes are passed to this function as a sequence.
84 |
85 | writing_bytes(addr, (1, 2, 3))
86 |
87 | """
88 | data = bytes(data_bytes)
89 | return I2CMessage(control=(I2C_CONTROL_START |
90 | I2C_CONTROL_SEND_ADDR |
91 | I2C_CONTROL_WAIT_FOR_ACK |
92 | I2C_CONTROL_GO_BUSY),
93 | address=(0x7f & address),
94 | data=data,
95 | length=len(data))
96 |
97 |
98 | def reading(address, length):
99 | """Returns a standard I2C read message. Address is limited to 7 bits."""
100 | return I2CMessage(control=(I2C_CONTROL_START |
101 | I2C_CONTROL_SEND_ADDR |
102 | I2C_CONTROL_WAIT_FOR_ACK |
103 | I2C_CONTROL_ACK_AFTER_READ |
104 | I2C_CONTROL_READ_NOT_WRITE |
105 | I2C_CONTROL_GO_BUSY),
106 | address=(0x7f & address),
107 | data=list(),
108 | length=length)
109 |
--------------------------------------------------------------------------------
/codebug_tether/platform.py:
--------------------------------------------------------------------------------
1 | """Functions for figuring out specific things about the current platform."""
2 | import re
3 | import os
4 | import sys
5 | import glob
6 | import serial
7 |
8 |
9 | def get_platform_serial_port():
10 | # setup DEFAULT_SERIAL_PORT which is different on Windows, MacOS,
11 | # Raspberry Pi 2 and Raspberry Pi 3
12 | if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
13 | # On Windows or OSX take the first serial port we can find
14 | def serial_ports():
15 | """ Lists serial port names
16 |
17 | :raises EnvironmentError:
18 | On unsupported or unknown platforms
19 | :returns:
20 | A list of the serial ports available on the system
21 | """
22 | if sys.platform.startswith('win'):
23 | ports = ['COM%s' % (i + 1) for i in range(256)]
24 | elif (sys.platform.startswith('linux') or
25 | sys.platform.startswith('cygwin')):
26 | # this excludes your current terminal "/dev/tty"
27 | ports = glob.glob('/dev/tty[A-Za-z0-9]*')
28 | elif sys.platform.startswith('darwin'):
29 | ports = glob.glob('/dev/tty.*')
30 | else:
31 | raise EnvironmentError('Unsupported platform')
32 |
33 | result = []
34 | for port in ports:
35 | try:
36 | s = serial.Serial(port)
37 | s.close()
38 | result.append(port)
39 | except (OSError, serial.SerialException):
40 | pass
41 | return result
42 | # use the first one
43 | try:
44 | return serial_ports()[0]
45 | except IndexError:
46 | print('ERROR: Could not find any serial ports.', file=sys.stderr)
47 | return ''
48 | else:
49 | # otherwise assume we're on Raspberry Pi/Linux
50 | def get_rpi_revision():
51 | """Returns the version number from the revision line."""
52 | for line in open("/proc/cpuinfo"):
53 | if "Revision" in line:
54 | return re.sub('Revision\t: ([a-z0-9]+)\n', r'\1', line)
55 |
56 | rpi_revision = get_rpi_revision()
57 | # if (rpi_revision and
58 | # (rpi_revision != 'Beta') and
59 | # (int('0x'+rpi_revision, 16) >= 0xa02082)):
60 | # # RPi 3 and above
61 | # return '/dev/ttyS0'
62 | # else:
63 | # # RPi 2 and below
64 | # return '/dev/ttyACM0'
65 | return '/dev/ttyACM0'
66 |
--------------------------------------------------------------------------------
/codebug_tether/serial_channel_device.py:
--------------------------------------------------------------------------------
1 | '''
2 | Useful for interacting with serial devices which use channels.
3 | '''
4 | import struct
5 |
6 |
7 | ACK_BYTE = bytes((0xCB,))
8 |
9 | CMD_GET = 0
10 | CMD_SET = 1
11 | CMD_GET_BULK = 2
12 | CMD_SET_BULK = 3
13 | CMD_AND = 4
14 | CMD_OR = 5
15 | CMD_GET_BUFFER= 6
16 | CMD_SET_BUFFER = 7
17 |
18 |
19 | class SerialChannelDevice():
20 | """A serial device with single-byte channels and several-byte
21 | buffers.
22 |
23 | Channels can be GET/SET individually or in bulk.
24 |
25 | Buffers can be GET/SET in bulk only.
26 |
27 | Consult device documentation for channel/buffer implementation.
28 |
29 | +------------------------------------------------------------------+
30 | | Serial Channel Device |
31 | | |
32 | | Channels (1B) Buffers (XB) |
33 | | +-----------+ +-----------+-----------+-----------+-----------+ |
34 | | | ch0 | | buf0-0 | buf0-1 | ... | buf0-N | |
35 | | +-----------+ +-----------+-----------+-----------+-----------+ |
36 | | | ch1 | +-----------+-----------+-----------+-----------+ |
37 | | +-----------+ | buf1-0 | buf1-1 | ... | buf1-N | |
38 | | | ... | +-----------+-----------+-----------+-----------+ |
39 | | +-----------+ |
40 | | | chN | |
41 | | +-----------+ |
42 | +------------------------------------------------------------------+
43 | """
44 |
45 | def __init__(self, serial_port):
46 | self.serial_port = serial_port
47 |
48 | def get(self, channel_index):
49 | """Returns GetPacket as bytes.
50 |
51 | GET packet is for retreiving channel values.
52 |
53 | +--------+---------------+
54 | | cmd id | channel index |
55 | +--------+---------------+
56 | | 3 bits | 5 bits |
57 | +--------+---------------+
58 |
59 | """
60 | self.transaction(
61 | struct.pack('B', (CMD_GET << 5) | (channel_index & 0x1f)))
62 | # Serial port will now contain channel data
63 | return self.serial_port.read(1)
64 |
65 | def set(self, channel_index, value):
66 | """Returns SetPacket as bytes.
67 |
68 | SET packet for setting channel values.
69 |
70 | +--------+---------------+--------+
71 | | cmd id | channel index | value |
72 | +--------+---------------+--------+
73 | | 3 bits | 5 bits | 1 byte |
74 | +--------+---------------+--------+
75 |
76 | """
77 | self.transaction(
78 | struct.pack('BB',
79 | (CMD_SET << 5 | channel_index & 0x1f),
80 | value))
81 |
82 | def get_bulk(self, channel_index, length):
83 | """GET BULK packet for retrieving multiple adjacent channel
84 | values in one go.
85 |
86 | +--------+---------------------+--------+
87 | | cmd id | start channel index | length |
88 | +--------+---------------------+--------+
89 | | 3 bits | 5 bits | 1 byte |
90 | +--------+---------------------+--------+
91 |
92 | """
93 | self.transaction(
94 | struct.pack('BB',
95 | (CMD_GET_BULK << 5 | channel_index & 0x1f),
96 | length))
97 | # Serial port will now contain channel data
98 | return self.serial_port.read(length)
99 |
100 | def set_bulk(self, channel_index, value_bytes):
101 | """SET BULK packet for setting multiple adjacent channel values
102 | in one go.
103 |
104 | +--------+-----------------+-----+------------+
105 | | cmd id | start ch. index | len | values |
106 | +--------+-----------------+-----+------------+
107 | | 3 bits | 5 bits | 1B | 1+ byte(s) |
108 | +--------+-----------------+-----+------------+
109 |
110 | """
111 | self.transaction(
112 | struct.pack('BB',
113 | (CMD_SET_BULK << 5 | channel_index & 0x1f),
114 | len(value_bytes)) + value_bytes)
115 |
116 | def and_mask(self, channel_index, mask):
117 | """Returns AndPacket as bytes.
118 |
119 | AND packet for ANDing channel values.
120 |
121 | +--------+---------------+-----------+
122 | | cmd id | channel index | AND mask |
123 | +--------+---------------+-----------+
124 | | 3 bits | 5 bits | 1 byte |
125 | +--------+---------------+-----------+
126 |
127 | """
128 | self.transaction(
129 | struct.pack('B', (CMD_AND << 5 | channel_index & 0x1f)) + \
130 | bytes((mask,)))
131 |
132 | def or_mask(self, channel_index, mask):
133 | """Returns OrPacket as bytes.
134 |
135 | OR packet for ORing channel values.
136 |
137 | +--------+---------------+----------+
138 | | cmd id | channel index | OR mask |
139 | +--------+---------------+----------+
140 | | 3 bits | 5 bits | 1 byte |
141 | +--------+---------------+----------+
142 |
143 | """
144 | self.transaction(
145 | struct.pack('B', (CMD_OR << 5 | channel_index & 0x1f)) + \
146 | bytes((mask,)))
147 |
148 | def set_bit(self, channel_index, bit_index, state):
149 | """Sets a bit in a channel to state."""
150 | if state:
151 | self.or_mask(channel_index, 1 << bit_index)
152 | else:
153 | self.and_mask(channel_index, 0xff ^ (1 << bit_index))
154 |
155 | def get_bit(self, channel_index, bit_index):
156 | """Returns a bit from a channel."""
157 | value = struct.unpack('B', self.get(channel_index))[0]
158 | return (value >> bit_index) & 0x1
159 |
160 | def get_buffer(self, buffer_index, length, offset=0):
161 | """GET BUFFER packet for reading whole buffers.
162 |
163 | +--------+--------------+--------+--------+
164 | | cmd id | buffer index | offset | length |
165 | +--------+--------------+--------+--------+
166 | | 3 bits | 5 bits | 1 byte | 1 byte |
167 | +--------+--------------+--------+--------+
168 |
169 | """
170 | self.transaction(
171 | struct.pack('BBB',
172 | (CMD_GET_BUFFER << 5 | buffer_index & 0x1f),
173 | offset,
174 | length))
175 | # Serial port will now contain buffer data
176 | return self.serial_port.read(length)
177 |
178 | def set_buffer(self, buffer_index, value_bytes, offset=0):
179 | """SET BUFFER packet for setting whole buffers.
180 |
181 | +--------+--------------+--------+--------+------------+
182 | | cmd id | buffer index | offset | length | values |
183 | +--------+--------------+--------+--------+------------+
184 | | 3 bits | 5 bits | 1 byte | 1 byte | 1+ byte(s) |
185 | +--------+--------------+--------+--------+------------+
186 |
187 | """
188 | self.transaction(
189 | struct.pack('BBB',
190 | (CMD_SET_BUFFER << 5 | buffer_index & 0x1f),
191 | offset,
192 | len(value_bytes)) + value_bytes)
193 |
194 | def transaction(self, tx_bytes):
195 | """Sends a packet and waits for a ACK response."""
196 | # Send the packet
197 | self.serial_port.write(tx_bytes)
198 |
199 | # CodeBug will always return an ACK byte
200 | assert self.serial_port.read(1) == ACK_BYTE
201 |
--------------------------------------------------------------------------------
/codebug_tether/sprites.py:
--------------------------------------------------------------------------------
1 | """Sprites are two dimensional drawings/characters/letters."""
2 | from codebug_tether.font import FourByFiveFont
3 |
4 |
5 | class Sprite(object):
6 | """A two dimensional sprite."""
7 |
8 | def __init__(self, width, height):
9 | self.width = width
10 | self.height = height
11 | self.clear()
12 |
13 | def clear(self):
14 | # inner list is y so we can access it like: pixel_state[x][y]
15 | self.pixel_state = [[0 for i in range(self.height)]
16 | for j in range(self.width)]
17 |
18 | def set_pixel(self, x, y, state):
19 | self.pixel_state[x][y] = state
20 |
21 | def get_pixel(self, x, y):
22 | return self.pixel_state[x][y]
23 |
24 | def set_row(self, y, row):
25 | """Sets an entire row to be the value contained in line."""
26 | for x in range(self.width):
27 | state = (row >> (self.width - 1 - x)) & 1
28 | self.set_pixel(x, y, state)
29 |
30 | def get_row(self, y):
31 | """Returns an entire row as a number."""
32 | row_state = 0
33 | for x in range(self.width):
34 | row_state |= (self.get_pixel(x, y) & 1) << (self.width - 1 - x)
35 | return row_state;
36 |
37 | def set_col(self, x, line):
38 | """Sets an entire column to be the value contained in line."""
39 | for y in range(self.height):
40 | state = (line >> (self.height - 1 - y)) & 1
41 | self.set_pixel(x, y, state)
42 |
43 | def get_col(self, x):
44 | """Returns an entire column as a number."""
45 | col_state = 0
46 | for y in range(self.height):
47 | col_state |= (self.get_pixel(x, y) & 1) << (self.height - 1 - y)
48 | return col_state
49 |
50 | def render_sprite(self, x, y, sprite_to_draw):
51 | """Renders the sprite given as an argument on this sprite at (x, y)."""
52 | for j in range(sprite_to_draw.height):
53 | for i in range(sprite_to_draw.width):
54 | new_x = x + i
55 | new_y = y + j
56 | draw_x = 0 <= new_x < self.width
57 | draw_y = 0 <= new_y < self.height
58 | if draw_x and draw_y:
59 | self.set_pixel(new_x,
60 | new_y,
61 | sprite_to_draw.get_pixel(i, j))
62 |
63 | def get_sprite(self, x, y, width, height):
64 | """Returns a new sprite of dimensions width x height from the
65 | given location (x, y) from this sprite.
66 | """
67 | new_sprite = Sprite(width, height)
68 | for j in range(height):
69 | for i in range(width):
70 | new_x = x + i
71 | new_y = y + j
72 | get_x = 0 <= new_x < self.width
73 | get_y = 0 <= new_y < self.height
74 | if get_x and get_y:
75 | new_sprite.set_pixel(i, j, self.get_pixel(new_x, new_y))
76 | return new_sprite
77 |
78 | def clone(self):
79 | """Returns a clone of this Sprite."""
80 | return self.get_sprite(0, 0, self.width, self.height)
81 |
82 | def invert_diagonal(self):
83 | """Inverts this sprite across the diagonal axis."""
84 | new_sprite = Sprite(width=self.height, height=self.width)
85 | for x in range(self.width):
86 | new_sprite.set_row(x, self.get_col(x))
87 | self.height = new_sprite.height
88 | self.width = new_sprite.width
89 | self.pixel_state = new_sprite.pixel_state
90 |
91 | def invert_vertical(self):
92 | """Inverts this sprite across the vertical axis."""
93 | new_sprite = Sprite(self.width, self.height)
94 | for y in range(self.height):
95 | new_sprite.set_row(self.height-1-y, self.get_row(y))
96 | self.pixel_state = new_sprite.pixel_state
97 |
98 | def invert_horizontal(self):
99 | """Inverts this sprite across the horizontal axis."""
100 | new_sprite = Sprite(self.width, self.height)
101 | for x in range(self.width):
102 | new_sprite.set_col(self.width-1-x, self.get_col(x))
103 | self.pixel_state = new_sprite.pixel_state
104 |
105 | def rotate90(self, rotation=1):
106 | """Rotate the sprite clockwise in 90degs steps. Specify the
107 | number of times to rotate by 90degs.
108 | """
109 | rotation = rotation % 4
110 | if rotation == 1:
111 | self.invert_diagonal()
112 | self.invert_vertical()
113 | elif rotation == 2:
114 | self.invert_horizontal()
115 | self.invert_vertical()
116 | elif rotation == 3:
117 | self.invert_diagonal()
118 | self.invert_horizontal()
119 |
120 | def draw_rectangle(self, x, y, width, height, line_weight=0):
121 | """Draw a rectangle on this sprite. If line_weight is 0 then fill
122 | the rectangle.
123 | """
124 | if line_weight <= 0:
125 | for j in range(height):
126 | for i in range(width):
127 | self.set_pixel(x+i, y+j, 1)
128 | else:
129 | # draw vertical
130 | for height_pixel in range(height):
131 | for line in range(line_weight):
132 | self.set_pixel(x+line, y+height_pixel, 1)
133 | self.set_pixel(x+width-1-line, y+height_pixel, 1)
134 |
135 | # draw horizontal
136 | for width_pixel in range(width):
137 | for line in range(line_weight):
138 | self.set_pixel(x+width_pixel, y+line, 1)
139 | self.set_pixel(x+width_pixel, y+height-1-line, 1)
140 |
141 |
142 | class CharSprite(Sprite):
143 | """Character sprite displays an alphanumerical character using a Font."""
144 |
145 | def __init__(self, character, font=FourByFiveFont()):
146 | super().__init__(font.char_width, font.char_height)
147 | self.font = font
148 | self.render_char(character)
149 |
150 | def render_char(self, character):
151 | for i in range(self.height):
152 | self.set_row(self.height-i-1,
153 | self.font.get_char_map(character)[i])
154 |
155 |
156 | class StringSprite(Sprite):
157 | """String Sprite displays an alphanumerical string of characters
158 | using a Font.
159 | """
160 |
161 | def __init__(self, string, direction='R', font=FourByFiveFont()):
162 | string = str(string) # make sure str is string
163 | self.direction = direction
164 | self.font = font
165 |
166 | # calculate this sprites width and height
167 | if self.direction == 'R' or self.direction == 'L':
168 | # R:"Hello, World!" or L:"!dlroW ,olleH"
169 | spr_width = (font.char_width+1) * len(string)
170 | spr_height = font.char_height
171 | elif self.direction == 'U' or self.direction == 'D':
172 | """U:"! or D:"H
173 | d e
174 | l l
175 | r l
176 | o o
177 | W ,
178 |
179 | , W
180 | o o
181 | l r
182 | l l
183 | e d
184 | H" !"
185 | """
186 | spr_width = font.char_width
187 | spr_height = (font.char_height + 1) * len(string)
188 |
189 | super().__init__(spr_width, spr_height)
190 |
191 | self.render_str(string)
192 |
193 | def render_str(self, string):
194 | for i, c in enumerate(string):
195 | character = CharSprite(c, self.font)
196 | # width and height with 1 pixel space
197 | chr_width_sp = self.font.char_width + 1;
198 | chr_height_sp = self.font.char_height + 1;
199 | if self.direction == 'R':
200 | self.render_sprite(i * chr_width_sp, 0, character)
201 | elif self.direction == 'U':
202 | self.render_sprite(0, i * chr_height_sp, character)
203 | elif self.direction == 'D':
204 | # put the space before each letter (-1 to y)
205 | y = self.height-self.font.char_height-(i*chr_height_sp)-1
206 | self.render_sprite(0, y, character)
207 | elif self.direction == 'L':
208 | x = self.width - chr_width_sp - (i*chr_width_sp)
209 | self.render_sprite(x, 0, character)
210 |
--------------------------------------------------------------------------------
/codebug_tether/version.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.9.1'
2 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PiFaceDigitalIO.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PiFaceDigitalIO.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PiFaceDigitalIO"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PiFaceDigitalIO"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # CodeBug Tether documentation build configuration file, created by
5 | # sphinx-quickstart on Thu Jun 20 15:23:09 2013.
6 | #
7 | # This file is execfile()d with the current directory set to its containing dir.
8 | #
9 | # Note that not all possible configuration values are present in this
10 | # autogenerated file.
11 | #
12 | # All configuration values have a default; values that are commented out
13 | # serve to show the default.
14 |
15 | import sys, os
16 |
17 | # If extensions (or modules to document with autodoc) are in another directory,
18 | # add these directories to sys.path here. If the directory is relative to the
19 | # documentation root, use os.path.abspath to make it absolute, like shown here.
20 | sys.path.insert(0, os.path.abspath('..'))
21 |
22 | # -- General configuration -----------------------------------------------------
23 |
24 | # If your documentation needs a minimal Sphinx version, state it here.
25 | #needs_sphinx = '1.0'
26 |
27 | # Add any Sphinx extension module names here, as strings. They can be extensions
28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
29 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath']
30 |
31 | # Add any paths that contain templates here, relative to this directory.
32 | templates_path = ['_templates']
33 |
34 | # The suffix of source filenames.
35 | source_suffix = '.rst'
36 |
37 | # The encoding of source files.
38 | #source_encoding = 'utf-8-sig'
39 |
40 | # The master toctree document.
41 | master_doc = 'index'
42 |
43 | # General information about the project.
44 | project = 'CodeBug Tether'
45 | copyright = '2015, OpenLX'
46 |
47 | # The version info for the project you're documenting, acts as replacement for
48 | # |version| and |release|, also used in various other places throughout the
49 | # built documents.
50 | #
51 | # The short X.Y version.
52 | # The short X.Y version.
53 | # NOTE: this is the version of the firmware download too so don't change
54 | # this with minor changes in the software if the firmware hasn't changed!
55 | version = '0.8.5'
56 | # The full version, including alpha/beta/rc tags.
57 | release = '0.8.5'
58 |
59 | # The language for content autogenerated by Sphinx. Refer to documentation
60 | # for a list of supported languages.
61 | #language = None
62 |
63 | # There are two options for replacing |today|: either, you set today to some
64 | # non-false value, then it is used:
65 | #today = ''
66 | # Else, today_fmt is used as the format for a strftime call.
67 | #today_fmt = '%B %d, %Y'
68 |
69 | # List of patterns, relative to source directory, that match files and
70 | # directories to ignore when looking for source files.
71 | exclude_patterns = ['_build']
72 |
73 | # The reST default role (used for this markup: `text`) to use for all documents.
74 | #default_role = None
75 |
76 | # If true, '()' will be appended to :func: etc. cross-reference text.
77 | #add_function_parentheses = True
78 |
79 | # If true, the current module name will be prepended to all description
80 | # unit titles (such as .. function::).
81 | #add_module_names = True
82 |
83 | # If true, sectionauthor and moduleauthor directives will be shown in the
84 | # output. They are ignored by default.
85 | #show_authors = False
86 |
87 | # The name of the Pygments (syntax highlighting) style to use.
88 | pygments_style = 'sphinx'
89 |
90 | # A list of ignored prefixes for module index sorting.
91 | #modindex_common_prefix = []
92 |
93 |
94 | # -- Options for HTML output ---------------------------------------------------
95 |
96 | # The theme to use for HTML and HTML Help pages. See the documentation for
97 | # a list of builtin themes.
98 | html_theme = 'default'
99 | # html_theme = 'haiku'
100 | # html_theme = 'nature'
101 |
102 | # Theme options are theme-specific and customize the look and feel of a theme
103 | # further. For a list of options available for each theme, see the
104 | # documentation.
105 | #html_theme_options = {}
106 |
107 | # Add any paths that contain custom themes here, relative to this directory.
108 | #html_theme_path = []
109 |
110 | # The name for this set of Sphinx documents. If None, it defaults to
111 | # " v documentation".
112 | #html_title = None
113 |
114 | # A shorter title for the navigation bar. Default is the same as html_title.
115 | #html_short_title = None
116 |
117 | # The name of an image file (relative to this directory) to place at the top
118 | # of the sidebar.
119 | #html_logo = None
120 |
121 | # The name of an image file (within the static path) to use as favicon of the
122 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
123 | # pixels large.
124 | #html_favicon = None
125 |
126 | # Add any paths that contain custom static files (such as style sheets) here,
127 | # relative to this directory. They are copied after the builtin static files,
128 | # so a file named "default.css" will overwrite the builtin "default.css".
129 | html_static_path = ['_static']
130 |
131 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
132 | # using the given strftime format.
133 | #html_last_updated_fmt = '%b %d, %Y'
134 |
135 | # If true, SmartyPants will be used to convert quotes and dashes to
136 | # typographically correct entities.
137 | #html_use_smartypants = True
138 |
139 | # Custom sidebar templates, maps document names to template names.
140 | #html_sidebars = {}
141 |
142 | # Additional templates that should be rendered to pages, maps page names to
143 | # template names.
144 | #html_additional_pages = {}
145 |
146 | # If false, no module index is generated.
147 | #html_domain_indices = True
148 |
149 | # If false, no index is generated.
150 | #html_use_index = True
151 |
152 | # If true, the index is split into individual pages for each letter.
153 | #html_split_index = False
154 |
155 | # If true, links to the reST sources are added to the pages.
156 | #html_show_sourcelink = True
157 |
158 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
159 | #html_show_sphinx = True
160 |
161 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
162 | #html_show_copyright = True
163 |
164 | # If true, an OpenSearch description file will be output, and all pages will
165 | # contain a tag referring to it. The value of this option must be the
166 | # base URL from which the finished HTML is served.
167 | #html_use_opensearch = ''
168 |
169 | # This is the file name suffix for HTML files (e.g. ".xhtml").
170 | #html_file_suffix = None
171 |
172 | # Output file base name for HTML help builder.
173 | htmlhelp_basename = 'codebug_tetherdoc'
174 |
175 |
176 | # -- Options for LaTeX output --------------------------------------------------
177 |
178 | latex_elements = {
179 | # The paper size ('letterpaper' or 'a4paper').
180 | #'papersize': 'letterpaper',
181 |
182 | # The font size ('10pt', '11pt' or '12pt').
183 | #'pointsize': '10pt',
184 |
185 | # Additional stuff for the LaTeX preamble.
186 | #'preamble': '',
187 | }
188 |
189 | # Grouping the document tree into LaTeX files. List of tuples
190 | # (source start file, target name, title, author, documentclass [howto/manual]).
191 | latex_documents = [
192 | ('index', 'codebug_tether.tex', 'CodeBug Tether Documentation',
193 | 'Thomas Preston', 'manual'),
194 | ]
195 |
196 | # The name of an image file (relative to this directory) to place at the top of
197 | # the title page.
198 | #latex_logo = None
199 |
200 | # For "manual" documents, if this is true, then toplevel headings are parts,
201 | # not chapters.
202 | #latex_use_parts = False
203 |
204 | # If true, show page references after internal links.
205 | #latex_show_pagerefs = False
206 |
207 | # If true, show URL addresses after external links.
208 | #latex_show_urls = False
209 |
210 | # Documents to append as an appendix to all manuals.
211 | #latex_appendices = []
212 |
213 | # If false, no module index is generated.
214 | #latex_domain_indices = True
215 |
216 |
217 | # -- Options for manual page output --------------------------------------------
218 |
219 | # One entry per manual page. List of tuples
220 | # (source start file, name, description, authors, manual section).
221 | man_pages = [
222 | ('index', 'codebug_tether', 'CodeBug Tether Documentation',
223 | ['Thomas Preston'], 1)
224 | ]
225 |
226 | # If true, show URL addresses after external links.
227 | #man_show_urls = False
228 |
229 |
230 | # -- Options for Texinfo output ------------------------------------------------
231 |
232 | # Grouping the document tree into Texinfo files. List of tuples
233 | # (source start file, target name, title, author,
234 | # dir menu entry, description, category)
235 | texinfo_documents = [
236 | ('index', 'codebug_tether', 'CodeBug Tether Documentation',
237 | 'Thomas Preston', 'codebug_tether', 'One line description of project.',
238 | 'Miscellaneous'),
239 | ]
240 |
241 | # Documents to append as an appendix to all manuals.
242 | #texinfo_appendices = []
243 |
244 | # If false, no module index is generated.
245 | #texinfo_domain_indices = True
246 |
247 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
248 | #texinfo_show_urls = 'footnote'
249 |
250 |
251 | # Example configuration for intersphinx: refer to the Python standard library.
252 | intersphinx_mapping = {'http://docs.python.org/': None}
253 |
254 | todo_include_todos = True
255 |
256 | # A string of reStructuredText that will be included at the end of every
257 | # source file that is read. This is the right place to add substitutions
258 | # that should be available in every file.
259 | rst_epilog = """
260 | .. |firmwaredownload| raw:: html
261 |
262 | download
263 | """.format(version=version)
264 |
--------------------------------------------------------------------------------
/docs/example.rst:
--------------------------------------------------------------------------------
1 | .. _examples-label:
2 |
3 | ########
4 | Examples
5 | ########
6 |
7 |
8 | Basics
9 | ======
10 |
11 | ::
12 |
13 | >>> import codebug_tether
14 |
15 | >>> codebug = codebug_tether.CodeBug() # create a CodeBug object
16 |
17 | >>> codebug.set_pixel(2, 1, 1) # turn on the LED at (2, 1)
18 | >>> codebug.set_pixel(0, 0, 0) # turn off the LED at (0, 0)
19 | >>> codebug.get_pixel(0, 1) # return the LED state at (0, 1)
20 | 1
21 |
22 | >>> codebug.clear() # turn off all LEDs
23 |
24 | >>> codebug.set_row(0, 5) # set row 0 to 5 (binary: 00101)
25 | >>> codebug.set_row(1, 0x1a) # set row 1 to 26 (binary: 11010)
26 | >>> codebug.set_row(2, 0b10101) # set row 2 to 21 (binary: 10101)
27 | >>> bin(codebug.get_row(2))
28 | '0b10101'
29 |
30 | >>> codebug.set_col(0, 0x1f) # turn on all LEDs in column 0
31 | >>> codebug.get_col(0)
32 | 31
33 |
34 | >>> codebug.get_input('A') # returns the state of button 'A'
35 | 0
36 | >>> codebug.get_input(0) # returns the state of input 0
37 | 0
38 |
39 | >>> codebug.set_leg_io(0, 0) # set leg 0 to output
40 | >>> codebug.set_output(0, 1) # turn leg 0 'on' (1)
41 |
42 |
43 | .. note:: You can specify a different serial device for CodeBug by passing
44 | the class a string. For example:
45 | ``codebug = codebug_tether.CodeBug(serial_port='/dev/tty.USBmodem')``.
46 |
47 |
48 | Sprites
49 | =======
50 | You can use the sprites library to quickly draw things on CodeBug's display.
51 |
52 | ::
53 |
54 | >>> import codebug_tether
55 | >>> import codebug_tether.sprites
56 |
57 | >>> # create a 3x3 square with the middle pixel off
58 | >>> square_sprite = codebug_tether.sprites.Sprite(3, 3)
59 | >>> square_sprite.set_row(0, 0b111)
60 | >>> square_sprite.set_row(1, 0b101)
61 | >>> square_sprite.set_row(2, 0b111)
62 |
63 | >>> # draw it in the middle of CodeBug
64 | >>> codebug = codebug_tether.CodeBug()
65 | >>> codebug.draw_sprite(1, 1, square_sprite)
66 |
67 | >>> # write some text
68 | >>> message = codebug_tether.sprites.StringSprite('Hello CodeBug!')
69 | >>> codebug.draw_sprite(0, 0, message)
70 | >>> # move it along
71 | >>> codebug.draw_sprite(-2, 0, message)
72 | >>> # scroll a sprite
73 | >>> codebug.scroll_sprite(message)
74 |
75 | You can do some more interesting things with Sprites::
76 |
77 | >>> import codebug_tether.sprites
78 |
79 | >>> sprite = codebug_tether.sprites.Sprite(10, 10)
80 |
81 | >>> # basic gets and sets
82 | >>> sprite.set_pixel(0, 0, 1)
83 | >>> sprite.get_pixel(0, 0)
84 | 1
85 | >>> sprite.set_row(0, 0, 0b1111111111)
86 | >>> sprite.get_row(0)
87 | 1023
88 | >>> sprite.set_col(0, 0, 0b1111111111)
89 | >>> sprite.get_col(0)
90 | 1023
91 |
92 | >>> # transform the sprite
93 | >>> sprite.invert_horizontal()
94 | >>> sprite.invert_vertical()
95 | >>> sprite.invert_diagonal()
96 | >>> sprite.rotate90()
97 | >>> sprite.rotate90(rotation=2) # rotate 180 degrees
98 |
99 | >>> # clone or extract parts of the sprite
100 | >>> dolly_sprite = sprite.clone()
101 | >>> rectangle = sprite.get_sprite(3, 3, 5, 2)
102 |
103 | >>> # draw other sprites
104 | >>> sprite.render_sprite(1, 1, rectangle)
105 |
106 | You can also change the direction text is written in::
107 |
108 | >>> from codebug_tether.sprites import StringSprite
109 | >>> left_to_right_msg = StringSprite('Hello CodeBug!')
110 | >>> right_to_left_msg = StringSprite('Hello CodeBug!', direction='L')
111 | >>> top_to_bottom_msg = StringSprite('Hello CodeBug!', direction='D')
112 | >>> bottom_to_top_msg = StringSprite('Hello CodeBug!', direction='U')
113 |
114 |
115 | Analogue Input
116 | ==============
117 | You can read analogue inputs from all 8 of CodeBug's I/O legs/extension
118 | pins::
119 |
120 | >>> import codebug_tether
121 | >>> from codebug_tether import (IO_DIGITAL_INPUT,
122 | ... IO_ANALOGUE_INPUT,
123 | ... IO_PWM_OUTPUT,
124 | ... IO_DIGITAL_OUTPUT)
125 | ...
126 | >>> codebug = codebug_tether.CodeBug()
127 | >>> codebug.set_leg_io(0, IO_ANALOGUE_INPUT)
128 | >>> codebug.read_analogue(0)
129 | 128
130 |
131 |
132 | PWM Output
133 | ==========
134 | You can drive one synchronised PWM (Pulse Width Modulation) signal out
135 | of the first three legs on CodeBug. That is, the same PWM signal will
136 | be driven out of legs configured as PWM output::
137 |
138 | >>> import codebug_tether
139 | >>> from codebug_tether import (IO_DIGITAL_INPUT,
140 | ... IO_ANALOGUE_INPUT,
141 | ... IO_PWM_OUTPUT,
142 | ... IO_DIGITAL_OUTPUT,
143 | ... T2_PS_1_1,
144 | ... T2_PS_1_4,
145 | ... T2_PS_1_16)
146 |
147 | >>> codebug = codebug_tether.CodeBug()
148 | >>> # configure legs 0 and 1 to be PWM output
149 | >>> codebug.set_leg_io(0, IO_PWM_OUTPUT)
150 | >>> codebug.set_leg_io(1, IO_PWM_OUTPUT)
151 | >>> # shortcut method to specify a frequency (the note C == 1046 Hz)
152 | >>> codebug.pwm_freq(1046)
153 | >>> time.sleep(2)
154 | >>> codebug.pwm_off()
155 |
156 | Or you can be more specific with the duty cycle and timing::
157 |
158 | >>> # pwm on with 1:4 prescaler and 75% duty cycle @ ~977Hz
159 | >>> # Timer 2 prescale: 4Mhz clock / 4 = 1MHz timer speed
160 | >>> # full_period: 255 << 2 = 1024 (timer resets at this count; PWM = 1)
161 | >>> # on_period: 765 (PWM goes to zero at this count; PWM = 0)
162 | >>> # therefore duty cycle here is 75%
163 | >>> codebug.pwm_on(T2_PS_1_4, 255, 765)
164 | >>> time.sleep(2)
165 | >>> codebug.pwm_off()
166 |
167 |
168 | Servos
169 | ======
170 | It is possible to drive up to eight servos from CodeBug. Servos
171 | typically operate by sending them a PWM (Pulse Width Modulation) signal
172 | with a 20ms period and a 1-2ms duty cycle which controls the angle of
173 | the servo. For example::
174 |
175 | Pulse Length
176 | <-1-2ms->
177 | 1+---------+
178 | | |
179 | 0+ +--------------------------------------+
180 | <------------------20ms (50Hz)----------------->
181 | PWM Period
182 |
183 | A duty cycle of 1ms will typically correspond to 0° rotation and a duty
184 | cycle of 2ms will typically correspond to 180° rotation. Although the
185 | precise values may differ depending on the type of servo.
186 |
187 | In order to drive servos from CodeBug you can call the `servo_set()`
188 | method which takes the servo index (which leg you are driving the
189 | servo from) and the the pulse length specified in N 0.5μs. For example::
190 |
191 | >>> import codebug_tether
192 | >>> from codebug_tether import (IO_DIGITAL_OUTPUT, scale)
193 |
194 | >>> # init CodeBug and configure leg 0 to be digital output
195 | >>> codebug = codebug_tether.CodeBug()
196 | >>> codebug.set_leg_io(0, IO_DIGITAL_OUTPUT)
197 |
198 | >>> # set servo on leg 0 with pulse length of 1ms (2000 * 0.5μs)
199 | >>> codebug.servo_set(0, 2000)
200 |
201 | >>> # stop driving the servo on leg 0
202 | >>> codebug.servo_set(0, 0)
203 |
204 | You can use the scale function to easily calculate the required pulse
205 | length value like so::
206 |
207 | >>> import codebug_tether
208 | >>> from codebug_tether import (IO_DIGITAL_OUTPUT, scale)
209 |
210 | >>> # scale 50 in the range 0-100 to the range 0-255
211 | >>> scale(50, 0, 100, 0, 255)
212 | 127
213 |
214 | >>> # scale 10 in the range 0-30 to the range 100-400
215 | >>> scale(10, 0, 30, 100, 400)
216 | 200
217 |
218 | >>> # scale 90° in the range 0-180° to the range 2000-4000 * 0.5μs
219 | >>> scale(90, 0, 180, 2000, 4000)
220 | 3000
221 |
222 | >>> # init CodeBug and configure leg 0 to be digital output
223 | >>> codebug = codebug_tether.CodeBug()
224 | >>> codebug.set_leg_io(0, IO_DIGITAL_OUTPUT)
225 |
226 | >>> # drive the servo to be at 90 degrees
227 | >>> codebug.servo_set(0, scale(90, 0, 180, 2000, 4000))
228 |
229 |
230 | Colour Tail
231 | ===========
232 | You can control Colour Tails (WS2812's) attached to CodeBug. By default,
233 | ColourTails attach to the CS pin on the extension header. You can also
234 | configure ColourTails to be driven from leg 0.
235 |
236 | ::
237 |
238 | >>> import codebug_tether
239 | >>> import codebug_tether.colourtail
240 |
241 | >>> codebug = codebug_tether.CodeBug()
242 | >>> colourtail = codebug_tether.colourtail.CodeBugColourTail(codebug)
243 |
244 | >>> # draw arrow pointing to the Colour Tail
245 | >>> codebug.set_row(4, 0b00100)
246 | >>> codebug.set_row(3, 0b00100)
247 | >>> codebug.set_row(2, 0b10101)
248 | >>> codebug.set_row(1, 0b01110)
249 | >>> codebug.set_row(0, 0b00100)
250 |
251 | >>> # make sure the extension header is configured as I/O
252 | >>> codebug.config_extension_io()
253 |
254 | >>> # initialise the colourtail (using EXT_CS pin)
255 | >>> colourtail.init()
256 | >>> colourtail.set_pixel(0, 255, 0, 0) # red
257 | >>> colourtail.set_pixel(1, 0, 255, 0) # green
258 | >>> colourtail.set_pixel(2, 0, 0, 255) # blue
259 | >>> colourtail.update() # turn on the LEDs
260 |
261 | >>> # initialise the colourtail (using LEG_0 pin)
262 | >>> colourtail.init(use_leg_0_not_cs=True)
263 | >>> colourtail.set_pixel(0, 255, 0, 0) # red
264 | >>> colourtail.set_pixel(1, 255, 0, 0) # red
265 | >>> colourtail.set_pixel(2, 0, 255, 0) # green
266 | >>> colourtail.set_pixel(3, 0, 255, 0) # green
267 | >>> colourtail.set_pixel(4, 0, 0, 255) # blue
268 | >>> colourtail.set_pixel(5, 0, 0, 255) # blue
269 | >>> colourtail.update() # turn on the LEDs
270 |
271 |
272 | Extension Header
273 | ================
274 | You can use the extension header to drive SPI and I2C buses.
275 |
276 | .. DANGER::
277 | Powering CodeBug from 5V USB means that the VCC pin on the extension
278 | header will also be at 5V. Do not use this pin to power devices which
279 | require less than 5V.
280 |
281 | Connect your SPI/I2C device onto the SPI/I2C lines::
282 |
283 | + +
284 | + Back of CodeBug +
285 | + +
286 | +--------------------------+
287 | | CodeBug Extension Header |
288 | +--------------------------+
289 | | | | | | |
290 | CS GND SDO SCL SDI/A VCC
291 |
292 | +----------+---------------------+
293 | | Pin Name | Function |
294 | +----------+---------------------+
295 | | CS | Chip Select |
296 | | GND | Ground (0v) |
297 | | SDO | SPI MOSI |
298 | | SCL | SPI/I2C Clock |
299 | | SDI/A | SPI MISO / I2C data |
300 | | VCC | V+ (3V3, 5V) |
301 | +----------+---------------------+
302 |
303 | You can configure the extension header mode with the following methods::
304 |
305 | >>> import codebug_tether
306 |
307 | >>> codebug = codebug_tether.CodeBug()
308 |
309 | >>> codebug.config_extension_spi() # configure extension as SPI
310 | >>> codebug.config_extension_i2c() # configure extension as I2C
311 | >>> codebug.config_extension_uart() # configure extension as UART
312 | >>> codebug.config_extension_io() # reset extension as normal I/O
313 |
314 | SPI
315 | ---
316 | ::
317 |
318 | >>> import codebug_tether
319 |
320 | >>> codebug = codebug_tether.CodeBug()
321 | >>> codebug.config_extension_spi()
322 |
323 | >>> # send three bytes (get three bytes back -- SPI is duplex)
324 | >>> codebug.spi_transaction(bytes((0x12, 0x34, 0x56)))
325 | b'\xff\xff\xff'
326 |
327 |
328 | I2C
329 | ---
330 | ::
331 |
332 | >>> import codebug_tether
333 | >>> from codebug_tether.i2c import (reading, writing)
334 | >>>
335 | >>> # example I2C address
336 | >>> i2c_addr = 0x1C
337 | >>>
338 | >>> # setup
339 | >>> codebug = codebug_tether.CodeBug()
340 | >>> codebug.config_extension_i2c()
341 |
342 | Single byte read transaction (read reg 0x12)::
343 |
344 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12), # reg addr
345 | reading(i2c_addr, 1)) # read 1 reg
346 | (42,)
347 |
348 | Multiple byte read transaction (read regs 0x12-0x17)::
349 |
350 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12), # reg addr
351 | reading(i2c_addr, 6)) # read 6 reg
352 | (65, 87, 47, 91, 43, 60)
353 |
354 | Single byte write transaction (write value 0x34 to reg 0x12)::
355 |
356 | >>> codebug.i2c_transaction(writing(i2c_addr, 0x12, 0x34))
357 |
358 | Multiple byte write transaction (write values 0x34, 0x56, 0x78 to reg 0x12)::
359 |
360 | >>> codebug.i2c_transaction(
361 | writing(i2c_addr, 0x12, 0x34, 0x56, 0x78))
362 |
363 |
364 | UART
365 | ----
366 | Sending data::
367 |
368 | >>> import codebug_tether
369 | >>> codebug = codebug_tether.CodeBug()
370 | >>> codebug.config_extension_uart()
371 | >>>
372 | >>> # send 0xAA, 0xBB over UART
373 | >>> codebug.uart_tx(bytes((0xAA, 0xBB)))
374 | >>>
375 | >>> # send 0xAA, 0xBB over UART at 300 baud
376 | >>> codebug.uart_tx(bytes((0xAA, 0xBB)), baud=300)
377 |
378 | You can also write to the buffer first and then send data from within
379 | it::
380 |
381 | >>> import codebug_tether
382 | >>> codebug = codebug_tether.CodeBug()
383 | >>> codebug.config_extension_uart()
384 | >>>
385 | >>> codebug.uart_tx_set_buffer(bytes((0xAA, 0xBB)))
386 | >>>
387 | >>> codebug.uart_tx_start(1, offset=0) # send 0xAA over UART
388 | >>> codebug.uart_tx_start(1, offset=1) # send 0xBB over UART
389 | >>>
390 | >>> # send 0xAA over UART at 300 baud
391 | >>> codebug.uart_tx_start(1, offset=0, baud=300)
392 |
393 | Receiving data::
394 |
395 | >>> import codebug_tether
396 | >>> codebug = codebug_tether.CodeBug()
397 | >>> codebug.config_extension_uart()
398 | >>>
399 | >>> codebug.uart_rx_start(2) # ready to receive 2B over UART
400 | >>>
401 | >>> # wait until data ready (alternatively, sleep X seconds)
402 | >>> while not codebug.uart_rx_is_ready():
403 | ... pass
404 | ...
405 | >>> codebug.uart_rx_get_buffer(2) # read out the two bytes
406 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Welcome to CodeBug Tether's documentation!
2 | ==============================================
3 |
4 | The codebug_tether Python module provides classes for
5 | interacting with CodeBug over USB Serial.
6 |
7 | Links:
8 | - `The CodeBug Website `_
9 | - `CodeBug Activity: "Tethering CodeBug with Python" `_
10 |
11 | Contents:
12 |
13 | .. toctree::
14 | :maxdepth: 2
15 |
16 | codebug_tether
17 | installation
18 | example
19 |
20 |
21 | Indices and tables
22 | ==================
23 |
24 | * :ref:`genindex`
25 | * :ref:`modindex`
26 | * :ref:`search`
27 |
28 |
--------------------------------------------------------------------------------
/docs/installation.rst:
--------------------------------------------------------------------------------
1 | ############
2 | Installation
3 | ############
4 |
5 | Setting up CodeBug
6 | ==================
7 | In order to use CodeBug with codebug_tether you need to program CodeBug
8 | with ``codebug_tether.cbg`` (|firmwaredownload|).
9 |
10 | To do this, hold down button A and plug in CodeBug via USB --- it should
11 | appear as a USB drive --- then copy the ``codebug_tether.cbg`` file onto it.
12 | CodeBug is now ready to be used via serial USB. Press button B to exit
13 | programming mode.
14 |
15 | .. note:: When CodeBug is connected to a computer via USB is should now
16 | appear as a serial device. To reprogram CodeBug: hold down
17 | button A and (re)plug it into a USB port.
18 |
19 | Install codebug_tether on Windows
20 | =================================
21 | .. note:: These instructions are based on `The Hitchhikers Guide to Python: Installing Python on Windows `_
22 |
23 | Install Python
24 | --------------
25 | Download and install the latest version of Python 3 from `here `_.
26 | Make sure you tick the *Add Python 3 to environment variables* checkbox.
27 |
28 | Install codebug_tether
29 | ----------------------
30 | To install codebug_tether, open up a command prompt and type::
31 |
32 | pip install codebug_tether
33 |
34 | Restart Windows and then open IDLE. Plug in CodeBug and type::
35 |
36 | >>> import codebug_tether
37 | >>> codebug = codebug_tether.CodeBug()
38 | >>> codebug.set_pixel(2, 2, 1)
39 |
40 | The middle pixel on your CodeBug should light up.
41 |
42 | See :ref:`examples-label` for more ways to use codebug_tether.
43 |
44 |
45 | Install codebug_tether on OSX
46 | =============================
47 | .. note:: These instructions are based on `The Hitchhikers Guide to Python: Installing Python on Mac OS X `_
48 |
49 | Install Python
50 | --------------
51 | Download and install `Xcode `_ (if you haven't already) and then enable the command line tools by running (in a terminal)::
52 |
53 | xcode-select --install
54 |
55 | Now install Homebrew (a package manager for OSX)::
56 |
57 | /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
58 |
59 | The script will explain what changes it will make and prompt you before the installation begins. Once you’ve installed Homebrew, insert the Homebrew directory at the top of your **PATH** environment variable. You can do this by adding the following line at the bottom of your ~/.profile file::
60 |
61 | export PATH=/usr/local/bin:/usr/local/sbin:$PATH
62 |
63 | Now, we can install Python 3::
64 |
65 | brew install python3
66 |
67 | This will take a minute or two.
68 |
69 | Install codebug_tether
70 | ----------------------
71 | To install codebug_tether, open up a terminal and type::
72 |
73 | pip install codebug_tether
74 |
75 | To test it has worked, plug in CodeBug and open a Python shell by typing::
76 |
77 | python
78 |
79 | Your command prompt should have changed to::
80 |
81 | >>> _
82 |
83 | Now type::
84 |
85 | >>> import codebug_tether
86 | >>> codebug = codebug_tether.CodeBug()
87 | >>> codebug.set_pixel(2, 2, 1)
88 |
89 | The middle pixel on your CodeBug should light up.
90 |
91 | See :ref:`examples-label` for more ways to use codebug_tether.
92 |
93 |
94 | Install codebug_tether on Linux
95 | ===============================
96 | Install Python
97 | --------------
98 | Python 3 and pip should already be installed but for good measure run::
99 |
100 | sudo apt-get update
101 | sudo apt-get upgrade
102 | sudo apt-get install python3
103 |
104 | If `pip` isn't installed you can securely download it from here `get-pip.py `_.
105 |
106 | Then run the following::
107 |
108 | sudo python3 get-pip.py
109 |
110 |
111 | Install codebug_tether
112 | ----------------------
113 | To install codebug_tether, open up a terminal and type::
114 |
115 | sudo pip3 install codebug_tether
116 |
117 | To test it has worked, plug in CodeBug and open a Python shell by typing::
118 |
119 | python3
120 |
121 | Your command prompt should have changed to::
122 |
123 | >>> _
124 |
125 | Now type::
126 |
127 | >>> import codebug_tether
128 | >>> codebug = codebug_tether.CodeBug()
129 | >>> codebug.set_pixel(2, 2, 1)
130 |
131 | The middle pixel on your CodeBug should light up.
132 |
133 | See :ref:`examples-label` for more ways to use codebug_tether.
134 |
135 |
136 | Troubleshooting
137 | ===============
138 | Raspberry Pi - Disable Serial Port Login Shell
139 | ----------------------------------------------
140 | CodeBug uses the USB serial port which (on older Raspberry Pi models) is configured to output the login shell by default. You must disable this before CodeBug will work. To do so, run::
141 |
142 | sudo raspi-config
143 |
144 | Navigate to `Advanced Options` > `Serial`, disable the login shell and then reboot.
145 |
--------------------------------------------------------------------------------
/examples/batteryChecker.py:
--------------------------------------------------------------------------------
1 | import time
2 | import subprocess
3 | from codebug_tether import CodeBug
4 |
5 | # Mac
6 | batteryCommand = ["pmset", "-g", "batt"]
7 |
8 |
9 | def displayString(displayString):
10 | delay = 0.2
11 | if len(displayString) > 1:
12 | for i in range(len(displayString) * 5 + 5):
13 | cb.write_text(5 - i, 0, displayString)
14 | time.sleep(delay)
15 | else:
16 | cb.write_text(0, 0, displayString)
17 | time.sleep(5)
18 | cb.clear()
19 |
20 |
21 | if __name__ == '__main__':
22 | cb = CodeBug('/dev/tty.usbmodemfa141')
23 | cb.clear()
24 | while True:
25 | if cb.get_input("A"):
26 | outputString = subprocess.check_output(batteryCommand)
27 | # print outputString
28 | batteryLife = outputString.split("\t")[1].split("%")[0]
29 | # print batteryLife
30 | displayString(batteryLife+'%')
31 |
32 | elif cb.get_input("B"):
33 | outputString = subprocess.check_output(batteryCommand)
34 | batteryLife = int(outputString.split("\t")[1].split("%")[0])
35 | # print batteryLife
36 | rows = batteryLife/20
37 | # print rows
38 | for i in range(rows):
39 | cb.set_row(i,0b11111)
40 | # time.sleep(.1)
41 | units = batteryLife%20
42 | # print units
43 | unitleds = ((units)/4)
44 | # print unitleds
45 | for i in range(unitleds):
46 | cb.set_led(i,rows,1)
47 | time.sleep(4)
48 | cb.clear()
49 |
--------------------------------------------------------------------------------
/examples/binary_counter.py:
--------------------------------------------------------------------------------
1 | # only needed for testing
2 | import os
3 | import sys
4 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | sys.path.insert(0, parentdir)
6 |
7 | from codebug_tether import CodeBug
8 | import time
9 |
10 |
11 | if __name__ == '__main__':
12 | cb = CodeBug()
13 | cb.clear()
14 | for i in range(0x20):
15 | cb.set_row(0, i)
16 | time.sleep(1)
17 |
--------------------------------------------------------------------------------
/examples/blink.py:
--------------------------------------------------------------------------------
1 | import time
2 | from codebug_tether import CodeBug
3 |
4 |
5 | if __name__ == '__main__':
6 | cb = CodeBug()
7 | for i in range(10):
8 | cb.set_row(0, 0b10101)
9 | cb.set_row(1, 0b01010)
10 | cb.set_row(2, 0b10101)
11 | cb.set_row(3, 0b01010)
12 | cb.set_row(4, 0b10101)
13 | time.sleep(1)
14 | cb.set_row(0, 0b01010)
15 | cb.set_row(1, 0b10101)
16 | cb.set_row(2, 0b01010)
17 | cb.set_row(3, 0b10101)
18 | cb.set_row(4, 0b01010)
19 | time.sleep(1)
20 |
--------------------------------------------------------------------------------
/examples/clock.py:
--------------------------------------------------------------------------------
1 | # only needed for testing
2 | import os
3 | import sys
4 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | sys.path.insert(0, parentdir)
6 |
7 | import datetime
8 | from codebug_tether import CodeBug
9 | import time
10 | from random import randint
11 |
12 | # if len(sys.argv) != 3:
13 | # print "Give two numbers as arguments"
14 | # sys.exit(1)
15 |
16 | def displayString(displayString):
17 | for i in range(len(displayString) * 5 + 5):
18 | cb.write_text(5 - i, 0, displayString)
19 | time.sleep(delay)
20 |
21 | if __name__ == '__main__':
22 | cb = CodeBug('/dev/tty.usbmodemfa141')
23 | cb.clear()
24 | delay = 0.2
25 | while True:
26 | if cb.get_input("A"):
27 | now = datetime.datetime.now()
28 | timeString = "TIME: {}:{}".format(now.hour, now.minute)
29 | displayString(timeString)
30 |
31 | elif cb.get_input("B"):
32 | now = datetime.datetime.now()
33 | dateString = "DATE: {}/{}/{}".format(now.day, now.month, now.year)
34 | displayString(dateString)
--------------------------------------------------------------------------------
/examples/colourtail.py:
--------------------------------------------------------------------------------
1 | import time
2 | import datetime
3 | import codebug_tether
4 | import codebug_tether.colourtail
5 |
6 |
7 | if __name__ == '__main__':
8 | # initialise
9 | codebug = codebug_tether.CodeBug()
10 | colourtail = codebug_tether.colourtail.CodeBugColourTail(codebug)
11 |
12 | # draw arrow
13 | codebug.set_row(4, 0b00100)
14 | codebug.set_row(3, 0b00100)
15 | codebug.set_row(2, 0b10101)
16 | codebug.set_row(1, 0b01110)
17 | codebug.set_row(0, 0b00100)
18 |
19 | codebug.config_extension_io()
20 |
21 | # initialise the colourtail (using EXT_CS pin)
22 | colourtail.init()
23 | # colourtail.init(use_leg_0_not_cs=True)
24 | colourtail.set_pixel(0, 255, 0, 0) # red
25 | colourtail.set_pixel(1, 0, 255, 0) # green
26 | colourtail.set_pixel(2, 0, 0, 255) # blue
27 | colourtail.set_pixel(3, 0, 255, 0)
28 | colourtail.set_pixel(4, 255, 0, 0)
29 | colourtail.update() # turn on the LEDs
30 |
31 |
32 |
33 | # # do the loopy spiral thing
34 | # current_colour = 'red'
35 | # red = 0
36 | # green = 0
37 | # blue = 0
38 | # i = 0
39 | # num_leds = 5
40 | # while True:
41 | # if current_colour == 'red':
42 | # red += 1
43 | # if red >= 255:
44 | # red = 0
45 | # current_colour = 'green'
46 | # elif current_colour == 'green':
47 | # green += 1
48 | # if green >= 255:
49 | # green = 0
50 | # current_colour = 'blue'
51 | # elif current_colour == 'blue':
52 | # blue += 1
53 | # if blue >= 255:
54 | # blue = 0
55 | # current_colour = 'red'
56 | # colourtail.set_pixel(i, red, green, blue)
57 | # colourtail.update() # turn on the LEDs
58 | # i = (i + 1) % num_leds
59 | # time.sleep(0.005)
60 |
--------------------------------------------------------------------------------
/examples/dice.py:
--------------------------------------------------------------------------------
1 | # only needed for testing
2 | import os
3 | import sys
4 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | sys.path.insert(0, parentdir)
6 |
7 | from codebug_tether import CodeBug
8 | import time
9 | from random import randint
10 |
11 | sprites = [[0b00000,
12 | 0b00000,
13 | 0b00100,
14 | 0b00000,
15 | 0b00000,],
16 | [0b10000,
17 | 0b00000,
18 | 0b00000,
19 | 0b00000,
20 | 0b00001,],
21 | [0b10000,
22 | 0b00000,
23 | 0b00100,
24 | 0b00000,
25 | 0b00001,],
26 | [0b10001,
27 | 0b00000,
28 | 0b00000,
29 | 0b00000,
30 | 0b10001,],
31 | [0b10001,
32 | 0b00000,
33 | 0b00100,
34 | 0b00000,
35 | 0b10001,],
36 | [0b10001,
37 | 0b00000,
38 | 0b10001,
39 | 0b00000,
40 | 0b10001,]]
41 |
42 | def diceRoll():
43 | return randint(0,5)
44 |
45 | def drawSprite(number):
46 | sprite = sprites[number]
47 | for i, row in enumerate(sprite):
48 | cb.set_row(i, row)
49 |
50 | if __name__ == '__main__':
51 | cb = CodeBug()
52 | cb.clear()
53 | while True:
54 | if cb.get_input("A"):
55 | cb.clear()
56 | time.sleep(.5)
57 | drawSprite(diceRoll())
58 | time.sleep(1)
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/examples/randomNumber.py:
--------------------------------------------------------------------------------
1 | # only needed for testing
2 | import os
3 | import sys
4 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | sys.path.insert(0, parentdir)
6 |
7 | from codebug_tether import CodeBug
8 | import time
9 | from random import randint
10 |
11 | if len(sys.argv) != 3:
12 | print "Give two numbers as arguments"
13 | sys.exit(1)
14 |
15 | def diceRoll():
16 | return randint(1,6)
17 |
18 | if __name__ == '__main__':
19 | cb = CodeBug('/dev/tty.usbmodemfa141')
20 | cb.clear()
21 | delay = 0.2
22 | while True:
23 | if cb.get_input("A"):
24 | number = str(randint(int(sys.argv[1]), int(sys.argv[2])))
25 | for i in range(len(number) * 5 + 5):
26 | cb.write_text(5 - i, 0, number)
27 | time.sleep(delay)
28 | time.sleep(1)
--------------------------------------------------------------------------------
/examples/snake.py:
--------------------------------------------------------------------------------
1 | # only needed for testing
2 | import os
3 | import sys
4 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | sys.path.insert(0, parentdir)
6 |
7 | from codebug_tether import CodeBug
8 | import time
9 |
10 | gridSize = 4
11 |
12 | FOWARD = 0
13 | CLOCKWISE = 1
14 | ANTICLOCKWISE = -1
15 |
16 | NORTH = 0
17 | EAST = 1
18 | SOUTH = 2
19 | WEST = 3
20 |
21 | directions = ["NORTH","EAST","SOUTH","WEST"]
22 |
23 | movement = WEST
24 | # direction = FOWARD
25 |
26 | snakeDirections = [WEST,WEST,WEST]
27 |
28 | counter = 0
29 | levelcounter = 0
30 | headX = 2
31 | headY = 2
32 | snakeLength = len(snakeDirections)
33 | tailX = headX + snakeLength -1
34 | tailY = headY
35 | gameOver = False
36 |
37 | # debug_directions = [FOWARD,CLOCKWISE,CLOCKWISE,FOWARD,FOWARD,CLOCKWISE,CLOCKWISE,FOWARD,ANTICLOCKWISE,ANTICLOCKWISE,FOWARD,FOWARD,FOWARD]
38 |
39 | if __name__ == '__main__':
40 | cb = CodeBug('/dev/tty.usbmodemfa141')
41 | cb.clear()
42 | delay = 0.2
43 | for i, x in enumerate(snakeDirections):
44 | cb.set_led(headX+i,headY, 1)
45 | cb.set_led(headX+1,headY, 1)
46 |
47 | while not gameOver:
48 | if counter % 2500000 == 2490000:
49 | if cb.get_input("A"):
50 | # if debug_directions[0] == ANTICLOCKWISE:
51 | if movement == NORTH:
52 | movement = WEST
53 | else:
54 | movement += ANTICLOCKWISE
55 |
56 | elif cb.get_input("B"):
57 | # elif debug_directions[0] == CLOCKWISE:
58 | movement = (movement+CLOCKWISE)%4
59 | # del debug_directions[0]
60 |
61 | print directions[movement]
62 | print directions[snakeDirections[-1]]
63 |
64 | snakeDirections = [movement] + snakeDirections
65 | if movement == NORTH:
66 | headY += 1
67 | elif movement == EAST:
68 | headX += 1
69 | elif movement == SOUTH:
70 | headY -= 1
71 | else:
72 | headX -= 1
73 |
74 | if headX > -1 and headX <= gridSize and headY > -1 and headY <= gridSize:
75 | if cb.get_led(headX, headY):
76 | print "You hit yourself!"
77 | gameOver = True
78 |
79 | cb.set_led(headX, headY, 1)
80 |
81 | if levelcounter%10 != 2:
82 | del snakeDirections[-1]
83 | cb.set_led(tailX, tailY, 0)
84 | if snakeDirections[-1] == NORTH:
85 | tailY += 1
86 | elif snakeDirections[-1] == EAST:
87 | tailX += 1
88 | elif snakeDirections[-1] == SOUTH:
89 | tailY -= 1
90 | else:
91 | tailX -= 1
92 | levelcounter +=1
93 | else:
94 | print "You hit a wall!"
95 | gameOver = True
96 |
97 | counter +=1
98 |
--------------------------------------------------------------------------------
/examples/tweets.py:
--------------------------------------------------------------------------------
1 | # -*- encoding: utf-8 -*-
2 | """twitter demo for CodeBug Tether.
3 | Call with no arguments to pull latest tweets from home timeline.
4 | Call with string argument to search for that term
5 | """
6 | # only needed for testing
7 | import os
8 | import sys
9 | parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10 | sys.path.insert(0, parentdir)
11 |
12 | import time
13 | import threading
14 | import sys
15 | import os
16 | try:
17 | import twitter # http://mike.verdone.ca/twitter/
18 | except ImportError:
19 | print("You need to install Python Twitter Tools "
20 | "(http://mike.verdone.ca/twitter/).")
21 | sys.exit(1)
22 | from codebug_tether import CodeBug
23 |
24 |
25 | UPDATE_INTERVAL = 60
26 |
27 | CONSUMER_KEY = ""
28 | CONSUMER_SECRET = ""
29 | # CONSUMER_KEY = ""
30 | # CONSUMER_SECRET = ""
31 |
32 | OAUTH_TOKEN = ""
33 | OAUTH_TOKEN_SECRET = ""
34 |
35 |
36 | class NoTweetsError(Exception):
37 | pass
38 |
39 |
40 | class TwitterTicker(object):
41 | def __init__(self, codebug, oauth_token, oauth_secret, search_term=None):
42 | self.twitter = twitter.Twitter(
43 | auth=twitter.OAuth(
44 | oauth_token, oauth_secret,
45 | CONSUMER_KEY, CONSUMER_SECRET)
46 | )
47 | self.search_term = search_term
48 | self.codebug = codebug
49 | try:
50 | self.current_tweet = self.get_latest_tweet()
51 | except NoTweetsError:
52 | self.current_tweet = None
53 | self.display_tweet(self.current_tweet)
54 | self.timer = None
55 |
56 | # @property
57 | # def page(self):
58 | # return self._current_page
59 |
60 | # @page.setter
61 | # def page(self, new_page):
62 | # num_pages = 1 + int(len(self.current_tweet['text']) / PAGE_WIDTH)
63 | # new_page %= num_pages
64 | # self.display_tweet(self.current_tweet, new_page)
65 |
66 | def get_latest_tweet(self):
67 | if self.search_term is None:
68 | return self.twitter.statuses.home_timeline()[0]
69 |
70 | try:
71 | latest_tweets = self.twitter.search.tweets(
72 | q=self.search_term,
73 | since_id=self.current_tweet['id'])['statuses']
74 | except AttributeError:
75 | latest_tweets = self.twitter.search.tweets(
76 | q=self.search_term)['statuses']
77 |
78 | try:
79 | return latest_tweets[0]
80 | except IndexError:
81 | raise NoTweetsError()
82 |
83 | def update(self, event=None):
84 | """Updated the screen with the latest tweet."""
85 | print("Updating...")
86 | try:
87 | latest_tweet = self.get_latest_tweet()
88 | except NoTweetsError:
89 | return
90 | else:
91 | if self.current_tweet is None or \
92 | latest_tweet['id'] != self.current_tweet['id']:
93 | self.current_tweet = latest_tweet
94 | self.display_tweet(self.current_tweet)
95 |
96 | def auto_update(self):
97 | self.update()
98 | # update again soon
99 | self.timer = threading.Timer(UPDATE_INTERVAL, self.auto_update)
100 | self.timer.start()
101 |
102 | def display_tweet(self, tweet, page=0):
103 | self._current_page = page
104 | text = tweet['text']
105 | print("DISPLAYING TWEET", text)
106 | self.codebug.clear()
107 | delay = 0.05
108 | for i in range(len(text) * 5 + 5):
109 | self.codebug.write_text(5 - i, 0, text)
110 | time.sleep(delay)
111 |
112 | def close(self):
113 | if self.timer is not None:
114 | self.timer.cancel()
115 | self.cad.lcd.clear()
116 | self.cad.lcd.backlight_off()
117 |
118 | def next_page(self, event=None):
119 | self.page += 1
120 |
121 | def previous_page(self, event=None):
122 | self.page -= 1
123 |
124 |
125 | if __name__ == "__main__":
126 | try:
127 | search_term = sys.argv[1]
128 | except IndexError:
129 | search_term = None
130 | print("Using home timeline.")
131 | else:
132 | print("Searching for", search_term)
133 |
134 | twitter_creds = os.path.expanduser('~/.twitter_piface_demo_credentials')
135 | if not os.path.exists(twitter_creds):
136 | twitter.oauth_dance("CodeBug Tether Twitter",
137 | CONSUMER_KEY,
138 | CONSUMER_SECRET,
139 | twitter_creds)
140 |
141 | oauth_token, oauth_secret = twitter.read_token_file(twitter_creds)
142 |
143 | codebug = CodeBug()
144 |
145 | global twitterticker
146 | twitterticker = TwitterTicker(codebug,
147 | oauth_token,
148 | oauth_secret,
149 | search_term)
150 | twitterticker.auto_update() # start the updating process
151 |
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.4.3.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.4.3.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.5.0.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.5.0.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.6.0.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.6.0.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.7.0.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.7.0.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.7.3.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.7.3.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.8.0.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.8.0.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.8.4.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.8.4.cbg
--------------------------------------------------------------------------------
/firmware/codebug_tether_v0.8.5.cbg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codebugtools/codebug_tether/d2ac777f1e551959515840f9dd936dc2e039248f/firmware/codebug_tether_v0.8.5.cbg
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pyserial
2 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from distutils.core import setup
3 |
4 |
5 | VERSION_FILE = 'codebug_tether/version.py'
6 | PY3 = sys.version_info[0] >= 3
7 |
8 |
9 | def get_version():
10 | if PY3:
11 | version_vars = {}
12 | with open(VERSION_FILE) as f:
13 | code = compile(f.read(), VERSION_FILE, 'exec')
14 | exec(code, None, version_vars)
15 | return version_vars['__version__']
16 | else:
17 | execfile(VERSION_FILE)
18 | return __version__
19 |
20 |
21 | setup(
22 | name='codebug_tether',
23 | version=get_version(),
24 | description='Control CodeBug over Serial USB.',
25 | author='Thomas Preston',
26 | author_email='thomas.preston@openlx.org.uk',
27 | license='GPLv3+',
28 | url='https://github.com/codebugtools/codebug_tether',
29 | packages=['codebug_tether'],
30 | requires=['pyserial'],
31 | long_description=open('README.md').read() + open('CHANGELOG').read(),
32 | classifiers=[
33 | "License :: OSI Approved :: GNU Affero General Public License v3 or "
34 | "later (AGPLv3+)",
35 | "Programming Language :: Python :: 3",
36 | "Development Status :: 5 - Production/Stable",
37 | "Intended Audience :: Developers",
38 | "Topic :: Software Development :: Libraries :: Python Modules",
39 | ],
40 | keywords='codebug tether raspberrypi openlx',
41 | )
42 |
--------------------------------------------------------------------------------
/tests.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # import os
3 | # import sys
4 | # parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5 | # sys.path.insert(0, parentdir)
6 | import time
7 | import serial
8 | import struct
9 | import unittest
10 | from codebug_tether.core import CodeBug
11 | from codebug_tether.sprites import (Sprite, StringSprite)
12 |
13 |
14 | class TestCodeBug(unittest.TestCase):
15 |
16 | def setUp(self):
17 | self.codebug = CodeBug()
18 |
19 | def test_get_input(self):
20 | # configure as inputs
21 | for i in range(7):
22 | self.codebug.set_leg_io(i, 1)
23 | # and just print them
24 | for i in ['A', 'B'] + list(range(8)):
25 | print("Input {} is {}".format(i, self.codebug.get_input(i)))
26 |
27 | def test_set_output(self):
28 | num_outputs = 8
29 | for i in range(num_outputs):
30 | self.codebug.set_leg_io(i, 0) # set to output
31 | for i in range(num_outputs):
32 | self.codebug.set_output(i, 1) # set to ON
33 |
34 | # check that they are all on
35 | for i in range(num_outputs):
36 | self.assertEqual(
37 | self.codebug.get_output(i),
38 | 1,
39 | 'self.codebug.get_output({}) != 1'.format(i))
40 |
41 | # then turn off again
42 | for i in range(num_outputs):
43 | self.codebug.set_output(i, 0) # set to OFF
44 |
45 | # def test_set_leg_io(self):
46 | # self.codebug.set_leg_io(0, 0)
47 | # self.codebug.set_leg_io(1, 1)
48 | # self.codebug.set_leg_io(2, 0)
49 | # self.codebug.set_leg_io(3, 1)
50 | # self.codebug.set_leg_io(4, 0)
51 | # self.codebug.set_leg_io(5, 1)
52 | # self.codebug.set_leg_io(6, 0)
53 | # self.codebug.set_leg_io(7, 1)
54 | # value = struct.unpack('B',
55 | # self.codebug.get(CHANNEL_INDEX_IO_DIRECTION))[0]
56 | # self.assertEqual(value, 0xAA)
57 |
58 | # self.codebug.set_leg_io(0, 1)
59 | # self.codebug.set_leg_io(1, 0)
60 | # self.codebug.set_leg_io(2, 1)
61 | # self.codebug.set_leg_io(3, 0)
62 | # self.codebug.set_leg_io(4, 1)
63 | # self.codebug.set_leg_io(5, 0)
64 | # self.codebug.set_leg_io(6, 1)
65 | # self.codebug.set_leg_io(7, 0)
66 | # value = struct.unpack('B',
67 | # self.codebug.get(CHANNEL_INDEX_IO_DIRECTION))[0]
68 | # self.assertEqual(value, 0x55)
69 |
70 | # # safely back to inputs
71 | # for i in range(7):
72 | # self.codebug.set_leg_io(i, 1)
73 |
74 | def test_clear(self):
75 | self.codebug.clear()
76 | rows = struct.unpack('B'*5, self.codebug.get_bulk(0, 5))
77 | self.assertEqual(rows, (0,)*5)
78 |
79 | def test_set_row(self):
80 | for test_value in (0x0A, 0x15):
81 | for i in range(5):
82 | self.codebug.set_row(i, test_value)
83 | rows = self.codebug.get_bulk(0, 5)
84 | self.assertEqual(rows, bytes((test_value,)*5))
85 | self.codebug.clear()
86 |
87 | def test_get_row(self):
88 | for test_value in (0x0A, 0x15):
89 | self.codebug.set_bulk(0, bytes([test_value]*5))
90 | for i in range(5):
91 | self.assertEqual(self.codebug.get_row(i), test_value)
92 | self.codebug.clear()
93 |
94 | def test_set_col(self):
95 | for i in range(5):
96 | self.codebug.set_col(i, 0x0A)
97 | rows = struct.unpack('B'*5, self.codebug.get_bulk(0, 5))
98 | self.assertEqual(rows, (0x00, 0x1F, 0x00, 0x1F, 0x00))
99 | self.codebug.clear()
100 |
101 | for i in range(5):
102 | self.codebug.set_col(i, 0x15)
103 | rows = struct.unpack('B'*5, self.codebug.get_bulk(0, 5))
104 | self.assertEqual(rows, (0x1F, 0x00, 0x1F, 0x00, 0x1F))
105 | self.codebug.clear()
106 |
107 | def test_get_col(self):
108 | self.codebug.set_bulk(0, bytes((0x00, 0x1F, 0x00, 0x1F, 0x00)))
109 | for i in range(5):
110 | self.assertEqual(self.codebug.get_col(i), 0x0A)
111 | self.codebug.clear()
112 | self.codebug.set_bulk(0, bytes((0x1F, 0x00, 0x1F, 0x00, 0x1F)))
113 | for i in range(5):
114 | self.assertEqual(self.codebug.get_col(i), 0x15)
115 | self.codebug.clear()
116 |
117 | def test_set_pixel(self):
118 | self.codebug.clear()
119 | for y in range(5):
120 | for x in range(5):
121 | self.codebug.set_pixel(x, y, 1)
122 | value = struct.unpack('B', self.codebug.get(y))[0]
123 | self.assertEqual(value, 1 << (4-x))
124 | self.codebug.set_pixel(x, y, 0)
125 |
126 | def test_get_pixel(self):
127 | self.codebug.clear()
128 | for y in range(5):
129 | for x in range(5):
130 | for i in range(2):
131 | self.codebug.set_pixel(x, y, i)
132 | get_value = self.codebug.get_pixel(x, y)
133 | self.assertEqual(get_value, i)
134 |
135 | def test_get_set_buffer(self):
136 | v = bytes(range(255))
137 | self.codebug.set_buffer(0, bytes(v))
138 | self.assertEqual(self.codebug.get_buffer(0, len(v)), v)
139 | v = bytes(range(100))
140 | self.codebug.set_buffer(0, bytes(v), 100)
141 | self.assertEqual(self.codebug.get_buffer(0, 255),
142 | bytes(range(100))+bytes(range(100))+bytes(range(100+100, 255)))
143 | self.assertEqual(self.codebug.get_buffer(0, 101, 100),
144 | bytes(range(100))+bytes((range(255)[200],)))
145 |
146 | def test_draw_sprite(self):
147 | self.codebug.clear()
148 |
149 | def fill_sprite(s):
150 | for x in range(s.width):
151 | for y in range(s.height):
152 | s.set_pixel(x, y, 1)
153 |
154 | sprite = Sprite(4, 4)
155 | fill_sprite(sprite)
156 |
157 | self.codebug.draw_sprite(0, 0, sprite)
158 | self.assertEqual(self.codebug.get_row(4), 0x00)
159 | self.assertEqual(self.codebug.get_row(3), 0x1E)
160 | self.assertEqual(self.codebug.get_row(2), 0x1E)
161 | self.assertEqual(self.codebug.get_row(1), 0x1E)
162 | self.assertEqual(self.codebug.get_row(0), 0x1E)
163 |
164 | self.codebug.draw_sprite(1, 1, sprite)
165 | self.assertEqual(self.codebug.get_row(4), 0x0F)
166 | self.assertEqual(self.codebug.get_row(3), 0x0F)
167 | self.assertEqual(self.codebug.get_row(2), 0x0F)
168 | self.assertEqual(self.codebug.get_row(1), 0x0F)
169 | self.assertEqual(self.codebug.get_row(0), 0x00)
170 |
171 | sprite = Sprite(2, 3)
172 | fill_sprite(sprite)
173 | self.codebug.draw_sprite(0, 0, sprite)
174 | self.assertEqual(self.codebug.get_row(4), 0x00)
175 | self.assertEqual(self.codebug.get_row(3), 0x00)
176 | self.assertEqual(self.codebug.get_row(2), 0x18)
177 | self.assertEqual(self.codebug.get_row(1), 0x18)
178 | self.assertEqual(self.codebug.get_row(0), 0x18)
179 |
180 | sprite = Sprite(3, 3)
181 | fill_sprite(sprite)
182 | sprite.set_pixel(1, 2, 0) # key the sprite
183 |
184 | self.codebug.draw_sprite(0, 0, sprite)
185 | self.assertEqual(self.codebug.get_row(4), 0x00)
186 | self.assertEqual(self.codebug.get_row(3), 0x00)
187 | self.assertEqual(self.codebug.get_row(2), 0x14)
188 | self.assertEqual(self.codebug.get_row(1), 0x1C)
189 | self.assertEqual(self.codebug.get_row(0), 0x1C)
190 |
191 | self.codebug.draw_sprite(2, 2, sprite)
192 | self.assertEqual(self.codebug.get_row(4), 0x05)
193 | self.assertEqual(self.codebug.get_row(3), 0x07)
194 | self.assertEqual(self.codebug.get_row(2), 0x07)
195 | self.assertEqual(self.codebug.get_row(1), 0x00)
196 | self.assertEqual(self.codebug.get_row(0), 0x00)
197 |
198 | hello_str = StringSprite('Hello!')
199 | self.codebug.draw_sprite(0, 0, hello_str)
200 | self.assertEqual(self.codebug.get_row(4), 0x12)
201 | self.assertEqual(self.codebug.get_row(3), 0x12)
202 | self.assertEqual(self.codebug.get_row(2), 0x1E)
203 | self.assertEqual(self.codebug.get_row(1), 0x12)
204 | self.assertEqual(self.codebug.get_row(0), 0x12)
205 | self.codebug.draw_sprite(-7, 0, hello_str)
206 | self.assertEqual(self.codebug.get_row(4), 0x03)
207 | self.assertEqual(self.codebug.get_row(3), 0x11)
208 | self.assertEqual(self.codebug.get_row(2), 0x19)
209 | self.assertEqual(self.codebug.get_row(1), 0x01)
210 | self.assertEqual(self.codebug.get_row(0), 0x1B)
211 |
212 |
213 | class TestSprites(unittest.TestCase):
214 |
215 | def test_string_sprite(self):
216 | expected = [[1, 1, 1, 1, 1],
217 | [0, 0, 1, 0, 0],
218 | [0, 0, 1, 0, 0],
219 | [1, 1, 0, 0, 0],
220 | [0, 0, 0, 0, 0],
221 | [0, 1, 1, 0, 0],
222 | [1, 0, 1, 1, 0],
223 | [1, 0, 1, 1, 0],
224 | [1, 0, 1, 0, 0],
225 | [0, 0, 0, 0, 0],
226 | [1, 0, 0, 0, 1],
227 | [1, 1, 1, 1, 1],
228 | [1, 0, 0, 0, 0],
229 | [0, 0, 0, 0, 0],
230 | [0, 0, 0, 0, 0],
231 | [1, 0, 0, 0, 1],
232 | [1, 1, 1, 1, 1],
233 | [1, 0, 0, 0, 0],
234 | [0, 0, 0, 0, 0],
235 | [0, 0, 0, 0, 0],
236 | [0, 1, 1, 0, 0],
237 | [1, 0, 0, 1, 0],
238 | [1, 0, 0, 1, 0],
239 | [0, 1, 1, 0, 0],
240 | [0, 0, 0, 0, 0]]
241 | s = StringSprite("hello")
242 | self.assertEqual(s.pixel_state, expected)
243 |
244 | def test_rotate90(self):
245 |
246 | def fill_sprite(s):
247 | for x in range(s.width):
248 | for y in range(s.height):
249 | s.set_pixel(x, y, 1)
250 |
251 | s = Sprite(5, 5)
252 | # key the sprite so that looks like this:
253 | # 1 1 0 1 1
254 | # 1 1 0 1 1
255 | # 1 1 1 1 0
256 | # 1 1 1 1 1
257 | # 1 1 1 1 1
258 | fill_sprite(s)
259 | s.set_pixel(2, 4, 0)
260 | s.set_pixel(2, 3, 0)
261 | s.set_pixel(4, 2, 0)
262 | expected = [[1, 1, 1, 1, 1],
263 | [1, 1, 1, 1, 1],
264 | [1, 1, 1, 0, 0],
265 | [1, 1, 1, 1, 1],
266 | [1, 1, 0, 1, 1]]
267 | self.assertEqual(s.pixel_state, expected)
268 |
269 | # rotate 90deg
270 | s2 = s.clone()
271 | s2.rotate90(1)
272 | expected = [[1, 1, 1, 1, 1],
273 | [1, 1, 1, 1, 1],
274 | [0, 1, 1, 1, 1],
275 | [1, 1, 0, 1, 1],
276 | [1, 1, 0, 1, 1]]
277 | self.assertEqual(s2.pixel_state, expected)
278 |
279 | # rotate 180deg
280 | s2 = s.clone()
281 | s2.rotate90(2)
282 | expected = [[1, 1, 0, 1, 1],
283 | [1, 1, 1, 1, 1],
284 | [0, 0, 1, 1, 1],
285 | [1, 1, 1, 1, 1],
286 | [1, 1, 1, 1, 1]]
287 | self.assertEqual(s2.pixel_state, expected)
288 |
289 | # rotate 270deg
290 | s2 = s.clone()
291 | s2.rotate90(3)
292 | expected = [[1, 1, 0, 1, 1],
293 | [1, 1, 0, 1, 1],
294 | [1, 1, 1, 1, 0],
295 | [1, 1, 1, 1, 1],
296 | [1, 1, 1, 1, 1]]
297 | self.assertEqual(s2.pixel_state, expected)
298 |
299 | def test_invert(self):
300 |
301 | def fill_sprite(s):
302 | for x in range(s.width):
303 | for y in range(s.height):
304 | s.set_pixel(x, y, 1)
305 |
306 | s = Sprite(5, 5)
307 | # key the sprite so that looks like this:
308 | # 1 1 0 1 1
309 | # 1 1 0 1 1
310 | # 1 1 1 1 0
311 | # 1 1 1 1 1
312 | # 1 1 1 1 1
313 | fill_sprite(s)
314 | s.set_pixel(2, 4, 0)
315 | s.set_pixel(2, 3, 0)
316 | s.set_pixel(4, 2, 0)
317 | expected = [[1, 1, 1, 1, 1],
318 | [1, 1, 1, 1, 1],
319 | [1, 1, 1, 0, 0],
320 | [1, 1, 1, 1, 1],
321 | [1, 1, 0, 1, 1]]
322 | self.assertEqual(s.pixel_state, expected)
323 |
324 | s2 = s.clone()
325 | s2.invert_vertical()
326 | expected = [[1, 1, 1, 1, 1],
327 | [1, 1, 1, 1, 1],
328 | [0, 0, 1, 1, 1],
329 | [1, 1, 1, 1, 1],
330 | [1, 1, 0, 1, 1]]
331 | self.assertEqual(s2.pixel_state, expected)
332 |
333 | s2 = s.clone()
334 | s2.invert_horizontal()
335 | expected = [[1, 1, 0, 1, 1],
336 | [1, 1, 1, 1, 1],
337 | [1, 1, 1, 0, 0],
338 | [1, 1, 1, 1, 1],
339 | [1, 1, 1, 1, 1]]
340 | self.assertEqual(s2.pixel_state, expected)
341 |
342 |
343 | if __name__ == "__main__":
344 | unittest.main()
345 |
--------------------------------------------------------------------------------