PICO-8 has a GPIO interface supporting 128 pins, each of which can store a 128-bit unsigned integer (0-255). However Raspberry PI and CHIP only support consuming each GPIO pin as a single bit (0 or 255), and only have pins for a small subset of the 128 virtual slots. The Pocket CHIP only has 6 fully-exposed pins (indices 2-7).
This means that if you want to pass GPIO information that can be used easily with any platform that runs PICO-8, you only get six on-and-off slots, which doesn't sound that great. Until you consider that you can still use those 6 slots to encode an integer up to 6 bits (-32 to 31 signed, or 0 to 63 unsigned!). Even a 3-bit int (0-7 unsigned) can often be enough to encode meaningful state information for many games, which can be used to trigger vibrations, color lights, etc.
The trouble is, taking a decimal value and encoding it as binary with PICO-8's built-in GPIO functions, then reading it again later, is not simple. PICO-8 Messenger provides utility functions which abstract away the bit-shifting and let you just read and write numbers.
Copy the functions you need from pico8-messenger.lua into your .p8 file.
-- included definition for write_gpio -- included definition for read_gpio -- write the number -1 to bits 2 through 4 write_gpio(-1, 2, 3) -- print out the number stored in bits 5 through 7 print(read_gpio(5, 3), 8, 8, 7)
You can download pico8-messenger.js and include it in your page with a script tag:
<script src="pico8-messenger.js"></script> <script> pico8_gpio = pico8_gpio || Array(128); // get some number stored in bits 2 through 4 var numFromPico8 = readFromGpio(pico8_gpio, 2, 3); // send the number 2 to pico-8 stored in bits 5 through 7 writeToGpio(pico8_gpio, 2, 5, 3); </script>
For all of these functions:
- num is the decimal integer to be stored
- pin_index or pinIndex is index in the GPIO array (0-127) where storage for this number should begin (in other words, the location of the largest, left-most bit)
- bits is the number of bits required to store the maximum value for this number
These functions wrap PICO-8's peek and poke functions to read and write data in the GPIO slots.
function write_gpio(num, pin_index, bits) function write_gpio_unsigned(num, pin_index, bits) function read_gpio(pin_index, bits) function read_gpio_unsigned(pin_index,bits)
All of these functions assume gpio is a 128-length array filled with numbers that are either 0 or 255. Although these are intended for handling PICO-8 data, they can be used anywhere it could be useful to encode numbers in a binary array.
function writeToGpio(gpio, num, pinIndex, bits) function writeToGpioUnsigned(gpio, num, pinIndex, bits) function readFromGpio(gpio, pinIndex, bits) function readFromGpioUnsigned(gpio, pinIndex, bits)
How many bits do I need?
[Please log in to post a comment]