Skip to content
Snippets Groups Projects
Commit 04dd8f49 authored by Quentin Bolsee's avatar Quentin Bolsee
Browse files

init commit

parent 230c12b1
Branches
No related tags found
No related merge requests found
# rp2040_gol_py # Micropython game of life
A very basic implementation of Conway's game of life for Micropython, accelerated by the numpy implementation provided by [ulab](https://github.com/v923z/micropython-ulab).
## Getting started ![](doc/rp2040_gol_py.mp4)
To make it easy for you to get started with GitLab, here's a list of recommended next steps. Using toroidal boundary conditions on the grid, one update cycle can be easily implemented:
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! ```py
def step(grid):
## Add your files """
computes one step of Conway's game of life on a toroidal 2D grid
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files """
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: count = np.zeros(a.shape, dtype=np.uint8)
count[:, :] = grid
``` # sum all 8 neighbors
cd existing_repo count += np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0)
git remote add origin https://gitlab.cba.mit.edu/quentinbolsee/rp2040_gol_py.git count += np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1)
git branch -M main count += np.roll(np.roll(grid, 1, axis=0), 1, axis=1) + np.roll(np.roll(grid, -1, axis=0), 1, axis=1)
git push -uf origin main count += np.roll(np.roll(grid, 1, axis=0), -1, axis=1) + np.roll(np.roll(grid, -1, axis=0), -1, axis=1)
# logical operator encoding the rules
return (count == 3) | (grid & (count == 4))
``` ```
## Integrate with your tools On a rp2040 running at `250MHz`, one full update cycle on a `128 x 64` grid takes `~76ms`, including blitting the array to a 1306 OLED display through I2C. This is a refresh rate of `~13Hz`, enough for realtime applications.
- [ ] [Set up project integrations](https://gitlab.cba.mit.edu/quentinbolsee/rp2040_gol_py/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals You can find the full code [here](./code).
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation ## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage ### Step 1: install Micropython
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support This implementation heavily relies on the ulab library. You can find a special version of Micropython with built-in ulab support [here](https://github.com/v923z/micropython-builder). For a generic rp2040 board, download [this](https://github.com/v923z/micropython-builder/releases/download/latest/RPI_PICO.uf2) file and place it on the device's flash storage after enabling the bootloader through a hard reset.
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap ### Step 2: install code
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing After installing Micropython on your device, interface with it using your favorite editor. If in doubt, you can use [Thonny](https://thonny.org/). Save the [main.py](./code/main.py) file on the device, as well as the [ssd1306.py](./code/ssd1306.py) library, with these exact filenames.
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. The default I2C pins are configured for a xiao rp2040:
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - SDA: 6
- SCL: 7
## Authors and acknowledgment You can change these if needed, in function `main()` in `main.py`.
Show your appreciation to those who have contributed to the project.
## License ### Step 3: start code
For open source projects, say how it is licensed.
## Project status By either pressing the run button in your editor or performing a reset of your device, the `main.py` should start and run the game of life.
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
import ssd1306
import framebuf
from machine import SoftI2C, Pin, freq
from ulab import numpy as np
import random
import time
def step(grid):
"""
computes one step of Conway's game of life on a toroidal 2D grid
"""
count = np.zeros(a.shape, dtype=np.uint8)
count[:, :] = grid
# sum all 8 neighbors
count += np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0)
count += np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1)
count += np.roll(np.roll(grid, 1, axis=0), 1, axis=1) + np.roll(np.roll(grid, -1, axis=0), 1, axis=1)
count += np.roll(np.roll(grid, 1, axis=0), -1, axis=1) + np.roll(np.roll(grid, -1, axis=0), -1, axis=1)
# logical operator encoding the rules
return (count == 3) | (grid & (count == 4))
def init_grid(grid):
height, width = grid.shape
# random initialization
for i in range(height):
for j in range(width):
grid[i, j] = random.getrandbits(1)
def main():
freq(250000000)
i2c = SoftI2C(scl=Pin(7), sda=Pin(6))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
width = 128
height = 64
a = np.zeros((height, width), dtype=np.bool)
init_grid(a)
i = 0
while True:
t1 = time.ticks_ms()
display.fill(0)
fb = framebuf.FrameBuffer(a.tobytes(), width, height, framebuf.GS8)
display.blit(fb, 0, 0)
display.show()
a = step(a)
t2 = time.ticks_ms()
i += 1
if i == 10:
print(f"dt: {time.ticks_diff(t2, t1)} ms")
i = 0
if __name__ == "__main__":
main()
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.width > 2 * self.height else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_data(self, buf):
self.write_list[1] = buf
self.i2c.writevto(self.addr, self.write_list)
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)
time.sleep_ms(10)
self.res(1)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(0)
self.cs(0)
self.spi.write(bytearray([cmd]))
self.cs(1)
def write_data(self, buf):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(1)
self.cs(0)
self.spi.write(buf)
self.cs(1)
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment