├── .gitignore ├── LICENSE ├── README.md ├── boot.py ├── cydr.py ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── images │ └── Arduino_IDE_issue.png ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── examples ├── speaker_demo.py ├── touch_demo.py ├── wifi_advance_demo.py └── wifi_simple_demo.py ├── images └── Empty └── resources ├── README.md ├── ili9341.py └── xpt2046.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Build and Release Folders 2 | bin-debug/ 3 | bin-release/ 4 | [Oo]bj/ 5 | [Bb]in/ 6 | 7 | # Other files and folders 8 | .settings/ 9 | 10 | # Executables 11 | *.swf 12 | *.air 13 | *.ipa 14 | *.apk 15 | 16 | # Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` 17 | # should NOT be excluded as they contain compiler settings and other important 18 | # information for Eclipse / Flash Builder. 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Mr. James 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MicroPython_CYD_ESP32-2432S028R 2 | This is a higher-level library to allows MicroPython users to easily control the ESP32-2432S028R, more commonly known as the Cheap Yellow Display (CYD). 3 | 4 | ## Dependencies 5 | This library depends on: 6 | * [MicroPython](https://micropython.org/download/ESP32_GENERIC/) - Firmware: v1.23.0 (2024-06-02) .bin (UPDATED) 7 | * [rdagger/micropython-ili9341](https://github.com/rdagger/micropython-ili9341/) - ili9341.py, Retrieved: 12/2/23 8 | * [rdagger/micropython-ili9341](https://github.com/rdagger/micropython-ili9341/) - xpt2046.py, Retrieved: 12/2/23 9 | 10 | A copy of rdagger's ili9341 and xpt2046 libraries are available in the _resources_ folder. 11 | 12 | 13 | ## Installation 14 | Follow MicroPython's [installation instructions](https://micropython.org/download/ESP32_GENERIC/) to get your CYD board ready. Use your preferred MicroPython IDE (e.g. [Thonny](https://thonny.org/)) to transfer cydr.py, boot.py, ili9341.py, and xpt2046.py to your CYD board. 15 | 16 | 17 | ## Usage 18 | You can create a new main.py file and use: 19 | ```python 20 | from cydr import CYD 21 | cyd = CYD() 22 | ``` 23 | or 24 | ```python 25 | from cydr import CYD 26 | cyd = CYD(rgb_pmw=False, speaker_gain=512, 27 | display_width=240, display_height=320, 28 | wifi_ssid = None, wifi_password = None) 29 | ``` 30 | to access the CYD or you can use one of the example programs provided in the repository. 31 | 32 | 33 | ## License 34 | The repository's code is made available under the terms of the MIT license. Please take a look at license.md for more information. 35 | -------------------------------------------------------------------------------- /boot.py: -------------------------------------------------------------------------------- 1 | # This file is executed on every boot (including wake-boot from deepsleep) 2 | #import esp 3 | #esp.osdebug(None) 4 | #import webrepl 5 | #webrepl.start() 6 | 7 | from machine import Pin 8 | 9 | print("Booting...") 10 | RGB = Pin(21, Pin.OUT) # Set RGB LED pin 11 | RGB.value(0) # Turn off RGB LED -------------------------------------------------------------------------------- /cydr.py: -------------------------------------------------------------------------------- 1 | # CYDc Library 2 | # Tags: Micropython Cheap Yellow Device DIYmall ESP32-2432S028R 3 | # Last Updated: June 14, 2024 4 | # Author(s): James Tobin 5 | # License: MIT 6 | # https://github.com/jtobinart/MicroPython_CYD_ESP32-2432S028R 7 | 8 | ###################################################### 9 | # MIT License 10 | ###################################################### 11 | ''' 12 | Copyright (c) 2023 James Tobin 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of this 14 | software and associated documentation files (the "Software"), to deal in the Software 15 | without restriction, including without limitation the rights to use, copy, modify, 16 | merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 17 | permit persons to whom the Software is furnished to do so, subject to the following 18 | conditions: 19 | The above copyright notice and this permission notice shall be included in all copies 20 | or substantial portions of the Software. 21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 22 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 23 | PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 24 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 25 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 26 | OR OTHER DEALINGS IN THE SOFTWARE. 27 | ''' 28 | 29 | ###################################################### 30 | # Library Information 31 | ###################################################### 32 | ''' 33 | cydr.py: 34 | 35 | v1.3 36 | - Simple WIFI functions added. Users may connect to an existing WIFI netowrk while creating a instance of the CYD 37 | class by assigning values to wifi_ssid and wifi_password (replace None with your WIFI login information: 38 | cyd = CYD(rgb_pmw=False, speaker_gain=512, display_width=240, display_height=320, wifi_ssid = None, wifi_password = None) 39 | or users can connect to a network by calling the cyd.wifi_connect("ssid", "password") after CYD instance has been created. 40 | - Users can also create an Access Point (AP) for other devices to connect to by using cyd.wifi_create_ap("ssid"). 41 | - Users can now specify the dimensions of their display while creating an instance of the CYD class by assigning new values 42 | to display_width and display_height. 43 | 44 | v1.2 45 | SD card initialization and mounting have been streamed lined and users no longer need to declare that they want to 46 | use the SD card when creating an instance of the CYD class. 47 | 48 | v1.1 49 | Double Tap detection implemented. XPT2046 touch switched from SPI to SoftSPI. 50 | 51 | v1.0 52 | This is a higher-level library to control DIYmall's ESP32-2432S028R, also known as the Cheap Yellow Display (CYD). 53 | 54 | TO DO: 55 | - Implement continuous touch 56 | - Implement DAC pin 26 for the speaker instead of using PWM 57 | - SD card creates a critical error when using keyboard interrupt 58 | - Implement easy Bluetooth functions 59 | ''' 60 | 61 | ###################################################### 62 | # Pin Reference 63 | ###################################################### 64 | """ 65 | Pins 66 | 0 Digital Boot Button 67 | 1 Digital Connector P1 - TX 68 | 2 Digital Display - TFT_RS / TFT_DC 69 | 3 Digital Connector P1 - RX 70 | 4 Digital RGB LED - Red 71 | 5 Digital SD Card - SS [VSPI] 72 | 6 Digital Unpopulated Pad U4: pin 6 - SCK / CLK 73 | 7 Digital Unpopulated Pad U4: pin 2 - SDO / SD0 74 | 8 Digital Unpopulated Pad U4: pin 5 - SDI / SD1 75 | 9 Digital Unpopulated Pad U4: pin 7 - SHD / SD2 76 | 10 Digital Unpopulated Pad U4: pin 3 - SWP / SD3 77 | 11 Digital Unpopulated Pad U4: pin 1 - SCS / CMD 78 | 12 Digital Display - TFT_SDO / TFT_MISO [HSPI] 79 | 13 Digital Display - TFT_SDI / TFT_MOSI [HSPI] 80 | 14 Digital Display - TFT_SCK [HSPI] 81 | 15 Digital Display - TFT_CS [HSPI] 82 | 16 Digital RGB LED - Green 83 | 17 Digital RGB LED - Blue 84 | 18 Digital SD Card - SCK [VSPI] 85 | 19 Digital SD Card - MISO [VSPI] 86 | 21 Digital Display & Connector P3 - TFT_BL (BackLight) / I2C SDA 87 | 22 Digital Connector P3 & CN1 - I2C SCL 88 | 23 Digital SD Card - MOSI [VSPI] 89 | 25 Digital Touch XPT2046 - CLK [Software SPI] 90 | 26 Analog Speaker - !!!Speaker ONLY! Connected to Amp!!! 91 | 27 Digital Connector CN1 - Can be used as a capacitive touch sensor pin. 92 | 32 Digital Touch XPT2046 - MOSI [Software SPI] 93 | 33 Digital Touch XPT2046 - CS [Software SPI] 94 | 34 Analog LDR Light Sensor - !!!Input ONLY!!! 95 | 35 Digital P3 Connector - !!!Input ONLY w/ NO pull-ups!!! 96 | 36 Digital Touch XPT2046 - IRQ !!!Input ONLY!!! 97 | 39 Digital Touch XPT2046 - MISO !!!Input ONLY!!! [Software SPI] 98 | 99 | """ 100 | 101 | ###################################################### 102 | # Import 103 | ###################################################### 104 | from ili9341 import Display, color565 105 | from xpt2046 import Touch 106 | from machine import Pin, SPI, ADC, PWM, SDCard, SoftSPI 107 | import network 108 | import os 109 | import time 110 | 111 | class CYD(object): 112 | ###################################################### 113 | # Color Variables 114 | ###################################################### 115 | BLACK = color565( 0, 0, 0) 116 | RED = color565(255, 0, 0) 117 | GREEN = color565( 0, 255, 0) 118 | CYAN = color565( 0, 255, 255) 119 | BLUE = color565( 0, 0, 255) 120 | PURPLE = color565(255, 0, 255) 121 | WHITE = color565(255, 255, 255) 122 | 123 | ###################################################### 124 | # Function List 125 | ###################################################### 126 | ''' 127 | cyd = CYD(rgb_pmw=False, speaker_gain=512, display_width=240, display_height=320, wifi_ssid = None, wifi_password = None) # Initialize CYD class 128 | cyd.display.ili9341_function_name() # Use to access ili9341 functions. 129 | cyd._touch_handler(x, y) # Called when a touch occurs. (INTERNAL USE ONLY) 130 | cyd.touches() # GETS the last touch coordinates. 131 | cyd.double_tap(x, y, error_margin = 5) # Check for double taps. 132 | cyd.rgb(color) # SETS rgb LED color. 133 | cyd._remap(value, in_min, in_max, out_min, out_max) # Converts a value form one scale to another. (INTERNAL USE ONLY) 134 | cyd.light() # GETS the current light sensor value. 135 | cyd.button_boot() # GETS the current boot button value. 136 | cyd.backlight(value) # SETS backlight brightness. 137 | cyd.play_tone(freq, duration, gain=0) # Plays a tone for a given duration. 138 | cyd.mount_sd() # Mounts SD card 139 | cyd.unmount_sd() # Unmounts SD card. 140 | cyd.wifi_connect(ssid, password) # Connects to a WLAN network. 141 | cyd.wifi_isconnected() # Checks to see that the wifi connection is connected. 142 | cyd.wifi_ip() # Get the CYD's IPv4 address on your WLAN. 143 | cyd.wifi_create_ap(_ssid) # Creates an Access Point (AP) WLAN network. 144 | cyd.shutdown() # Safely shutdown CYD device. 145 | ''' 146 | def __init__(self, rgb_pmw=False, speaker_gain=512, display_width=240, display_height=320, wifi_ssid = None, wifi_password = None): 147 | ''' 148 | Initialize CDYc 149 | 150 | Args: 151 | rgb_pmw (Default = False): Sets RGB LED to static mode. (on/off), if false 152 | Sets RGB LED to dynamic mode. (16.5+ million color combination), if true 153 | Warning: RGB LED never completely turns off in dynamic mode. 154 | 155 | speaker_gain (Default = 512): Sets speaker's volume. The full gain range is 0 - 1023. 156 | display_width (Default = 240): Reset if needed. 157 | display_height (Default = 320): Reset if needed. 158 | ''' 159 | # Display 160 | hspi = SPI(1, baudrate=40000000, sck=Pin(14), mosi=Pin(13)) 161 | self.display = Display(hspi, dc=Pin(2), cs=Pin(15), rst=Pin(0), width=display_width, height=display_height) 162 | self._x = 0 163 | self._y = 0 164 | 165 | # Backlight 166 | self.tft_bl = Pin(21, Pin.OUT) 167 | self.tft_bl.value(1) #Turn on backlight 168 | 169 | # Touch 170 | self.last_tap = (-1,-1) 171 | sspi = SoftSPI(baudrate=500000, sck=Pin(25), mosi=Pin(32), miso=Pin(39)) 172 | self._touch = Touch(sspi, cs=Pin(33), int_pin=Pin(36), int_handler=self._touch_handler) 173 | 174 | # Boot Button 175 | self._button_boot = Pin(0, Pin.IN) 176 | 177 | # LDR: Light Sensor (Measures Darkness) 178 | self._ldr = ADC(34) 179 | 180 | # RGB LED 181 | self._rgb_pmw = rgb_pmw 182 | if self._rgb_pmw == False: 183 | self.RGBr = Pin(4, Pin.OUT, value=1) # Red 184 | self.RGBg = Pin(16, Pin.OUT, value=1) # Green 185 | self.RGBb = Pin(17, Pin.OUT, value=1) # Blue 186 | else: 187 | self.RGBr = PWM(Pin(4), freq=200, duty=1023) # Red 188 | self.RGBg = PWM(Pin(16), freq=200, duty=1023) # Green 189 | self.RGBb = PWM(Pin(17), freq=200, duty=1023) # Blue 190 | print("RGB PMW Ready") 191 | 192 | # Speaker 193 | self._speaker_pin = Pin(26, Pin.OUT) 194 | self.speaker_gain = int(min(max(speaker_gain, 0),1023)) # Min 0, Max 1023 195 | self.speaker_pwm = PWM(self._speaker_pin, freq=440, duty=0) 196 | 197 | # SD Card 198 | # The user needs to run mount_sd() to access SD card. 199 | self._sd_ready = False 200 | self._sd_mounted = False 201 | 202 | # WIFI 203 | if wifi_ssid is not None: 204 | print("Connecting to wifi...") 205 | self.wifi_connect(wifi_ssid, wifi_password) # connect to WLAN Network 206 | 207 | print("CYD ready...") 208 | 209 | ###################################################### 210 | # Touchscreen Press Event 211 | ###################################################### 212 | def _touch_handler(self, x, y): 213 | ''' 214 | Interrupt Handler 215 | This function is called each time the screen is touched. 216 | ''' 217 | # X needs to be flipped 218 | x = (self.display.width - 1) - x 219 | 220 | self._x = x 221 | self._y = y 222 | 223 | #print("Touch:", x, y) 224 | 225 | def touches(self): 226 | ''' 227 | Returns last stored touch data. 228 | 229 | Return: 230 | x: x coordinate of finger 1 231 | y: y coordinate of finger 1 232 | ''' 233 | x = self._x 234 | y = self._y 235 | 236 | self._x = 0 237 | self._y = 0 238 | 239 | return x, y 240 | 241 | def double_tap(self, x, y, error_margin = 10): 242 | ''' 243 | Returns whether or not a double tap was detected. 244 | 245 | Return: 246 | True: Double-tap detected. 247 | False: Single tap detected. 248 | ''' 249 | # Double tap to exit 250 | if self.last_tap[0] - error_margin <= x and self.last_tap[0] + error_margin >= x: 251 | if self.last_tap[1] - error_margin <= y and self.last_tap[1] + error_margin >= y: 252 | self.last_tap = (-1,-1) 253 | return True 254 | self.last_tap = (x,y) 255 | return False 256 | 257 | ###################################################### 258 | # RGB LED 259 | ###################################################### 260 | def rgb(self, color): 261 | ''' 262 | Set RGB LED color. 263 | 264 | Args: 265 | color: Array containing three int values (r,g,b). 266 | if rgb_pmw == False, then static mode is activated. 267 | r (0 or 1): Red brightness. 268 | g (0 or 1): Green brightness. 269 | b (0 or 1): Blue brightness. 270 | if rgb_pmw == True, then dynamic mode is activated. 271 | r (0-255): Red brightness. 272 | g (0-255): Green brightness. 273 | b (0-255): Blue brightness. 274 | ''' 275 | r, g, b = color 276 | if self._rgb_pmw == False: 277 | self.RGBr.value(1 if min(max(r, 0),1) == 0 else 0) 278 | self.RGBg.value(1 if min(max(g, 0),1) == 0 else 0) 279 | self.RGBb.value(1 if min(max(b, 0),1) == 0 else 0) 280 | else: 281 | self.RGBr.duty(int(min(max(self._remap(r,0,255,1023,0), 0),1023))) 282 | self.RGBg.duty(int(min(max(self._remap(g,0,255,1023,0), 0),1023))) 283 | self.RGBb.duty(int(min(max(self._remap(b,0,255,1023,0), 0),1023))) 284 | 285 | def _remap(self, value, in_min, in_max, out_min, out_max): 286 | ''' 287 | Internal function for remapping values from one scale to a second. 288 | ''' 289 | in_span = in_max - in_min 290 | out_span = out_max - out_min 291 | scale = out_span / in_span 292 | return out_min + (value - in_min) * scale 293 | 294 | ###################################################### 295 | # Light Sensor 296 | ###################################################### 297 | def light(self): 298 | ''' 299 | Light Sensor (Measures darkness) 300 | 301 | Return: a value from 0.0 to 1.0 302 | ''' 303 | return self._ldr.read_u16()/65535 304 | 305 | ###################################################### 306 | # Button 307 | ###################################################### 308 | def button_boot(self): 309 | ''' 310 | Gets the Boot button's current state 311 | ''' 312 | return self._button_boot.value 313 | 314 | ###################################################### 315 | # Backlight 316 | ###################################################### 317 | def backlight(self, val): 318 | ''' 319 | Sets TFT Backlight Off/On 320 | 321 | Arg: 322 | val: 0 or 1 (0 = off/ 1 = on) 323 | ''' 324 | self.tft_bl.value(min(max(val, 0),1)) 325 | 326 | ###################################################### 327 | # Speaker 328 | ###################################################### 329 | def play_tone(self, freq, duration, gain=0): 330 | ''' 331 | Plays a tone (Optional speaker must be attached!) 332 | 333 | Args: 334 | freq: Frequency of the tone. 335 | duration: How long does the tone play for. 336 | gain: volume 337 | ''' 338 | self.speaker_pwm.freq(freq) 339 | if gain == 0: 340 | gain = self.speaker_gain 341 | self.speaker_pwm.duty(gain) # Turn on speaker by resetting speaker gain 342 | time.sleep_ms(duration) 343 | self.speaker_pwm.duty(0) # Turn off speaker by resetting gain to zero 344 | 345 | ###################################################### 346 | # SD Card 347 | ###################################################### 348 | def mount_sd(self): 349 | ''' 350 | Mounts SD Card 351 | ''' 352 | try: 353 | if self._sd_ready == False: 354 | self.sd = SDCard(slot=2) 355 | self._sd_ready = True 356 | if self._sd_ready == True: 357 | os.mount(self.sd, '/sd') # mount 358 | self._sd_mounted = True 359 | print("SD card mounted. Do not remove!") 360 | 361 | except: 362 | print("Failed to mount SD card") 363 | 364 | def unmount_sd(self): 365 | ''' 366 | Unmounts SD Card 367 | ''' 368 | try: 369 | if self._sd_mounted == True: 370 | os.unmount('/sd') # mount 371 | self._sd_mounted = False 372 | print("SD card unmounted. Safe to remove SD card!") 373 | except: 374 | print("Failed to unmount SD card") 375 | 376 | ###################################################### 377 | # Wifi 378 | ###################################################### 379 | def wifi_connect(self, ssid, password): 380 | ''' 381 | Connects to a WLAN network. 382 | The CYD (client) can connect to an existing WLAN network (station). 383 | 384 | Args: 385 | ssid: The name of the network you want to connect to. 386 | password: The network password for the ssid you are connecting to. 387 | ''' 388 | self.wifi = network.WLAN(network.STA_IF) # Creates a station interface 389 | self.wifi.active(True) 390 | self.wifi.config(reconnects=3) # Sets timeout count 391 | print('connecting to network...') 392 | self.wifi.connect(ssid, password) # Connects to an existing network 393 | while not self.wifi.isconnected(): 394 | pass 395 | print('network config:', self.wifi_ip()) # Get the interface's IPv4 addresses 396 | 397 | def wifi_isconnected(self): 398 | ''' 399 | Checks to see that the wifi connection is connected. 400 | 401 | Returns: 402 | True: Device connected to a network. 403 | False: Device not connected to a network. 404 | ''' 405 | return self.wifi.isconnected() 406 | 407 | def wifi_ip(self): 408 | ''' 409 | Get the CYD's IPv4 address on your WLAN. 410 | 411 | Returns: The IP address of your device. 412 | ''' 413 | ip, _, _, _ = self.wifi.ifconfig() 414 | return ip 415 | 416 | def wifi_create_ap(self, _ssid): 417 | ''' 418 | Creates an Access Point (AP) WLAN network. 419 | Other devices (clients) can connect to this CYD (station) via wifi. 420 | 421 | Args: 422 | _ssid: The name of your new AP. This is the wifi id that client devices are going to connect to. 423 | ''' 424 | self.wifi_ap = network.WLAN(network.AP_IF) # Create AP interface 425 | self.wifi_ap.config(ssid=_ssid) # Set the SSID of your AP 426 | self.wifi_ap.config(max_clients=10) # Set how many devices can connect to your AP network 427 | self.wifi_ap.active(True) # Activate the AP interface 428 | print('network config:', self.wifi_ip()) # Get your device's IPv4 address 429 | 430 | 431 | ###################################################### 432 | # Shutdown 433 | ###################################################### 434 | def shutdown(self): 435 | ''' 436 | Resets CYD and properly shuts down. 437 | ''' 438 | self.display.fill_rectangle(0, 0, self.display.width-1, self.display.height-1, self.BLACK) 439 | self.display.draw_rectangle(2, 2, self.display.width-5, self.display.height-5, self.RED) 440 | self.display.draw_text8x8(self.display.width // 2 - 52, self.display.height // 2 - 4, "Shutting Down", self.WHITE, background=self.BLACK) 441 | time.sleep(2.0) 442 | self.unmount_sd() 443 | self.speaker_pwm.deinit() 444 | if self._rgb_pmw == False: 445 | self.RGBr.value(1) 446 | self.RGBg.value(1) 447 | self.RGBb.value(1) 448 | else: 449 | self.rgb(0,0,0) 450 | self.tft_bl.value(0) 451 | self.display.cleanup() 452 | print("========== Goodbye ==========") 453 | -------------------------------------------------------------------------------- /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 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/ReadtheDocsTemplate" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ReadtheDocsTemplate" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Read the Docs Template documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Aug 26 14:19:49 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # 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 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [] 32 | 33 | # Add any paths that contain templates here, relative to this directory. 34 | templates_path = ['_templates'] 35 | 36 | # The suffix of source filenames. 37 | source_suffix = '.rst' 38 | 39 | # The encoding of source files. 40 | #source_encoding = 'utf-8-sig' 41 | 42 | # The master toctree document. 43 | master_doc = 'index' 44 | 45 | # General information about the project. 46 | project = u'Read the Docs Template' 47 | copyright = u'2014, Read the Docs' 48 | 49 | # The version info for the project you're documenting, acts as replacement for 50 | # |version| and |release|, also used in various other places throughout the 51 | # built documents. 52 | # 53 | # The short X.Y version. 54 | version = '1.0' 55 | # The full version, including alpha/beta/rc tags. 56 | release = '1.0' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | #language = None 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | #today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | #today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = ['_build'] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all 73 | # 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 | # If true, keep warnings as "system message" paragraphs in the built documents. 94 | #keep_warnings = False 95 | 96 | 97 | # -- Options for HTML output ---------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = 'default' 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | #html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | #html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | #html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | #html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | #html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | #html_favicon = None 126 | 127 | # Add any paths that contain custom static files (such as style sheets) here, 128 | # relative to this directory. They are copied after the builtin static files, 129 | # so a file named "default.css" will overwrite the builtin "default.css". 130 | html_static_path = ['_static'] 131 | 132 | # Add any extra paths that contain custom files (such as robots.txt or 133 | # .htaccess) here, relative to this directory. These files are copied 134 | # directly to the root of the documentation. 135 | #html_extra_path = [] 136 | 137 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 138 | # using the given strftime format. 139 | #html_last_updated_fmt = '%b %d, %Y' 140 | 141 | # If true, SmartyPants will be used to convert quotes and dashes to 142 | # typographically correct entities. 143 | #html_use_smartypants = True 144 | 145 | # Custom sidebar templates, maps document names to template names. 146 | #html_sidebars = {} 147 | 148 | # Additional templates that should be rendered to pages, maps page names to 149 | # template names. 150 | #html_additional_pages = {} 151 | 152 | # If false, no module index is generated. 153 | #html_domain_indices = True 154 | 155 | # If false, no index is generated. 156 | #html_use_index = True 157 | 158 | # If true, the index is split into individual pages for each letter. 159 | #html_split_index = False 160 | 161 | # If true, links to the reST sources are added to the pages. 162 | #html_show_sourcelink = True 163 | 164 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 165 | #html_show_sphinx = True 166 | 167 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 168 | #html_show_copyright = True 169 | 170 | # If true, an OpenSearch description file will be output, and all pages will 171 | # contain a tag referring to it. The value of this option must be the 172 | # base URL from which the finished HTML is served. 173 | #html_use_opensearch = '' 174 | 175 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 176 | #html_file_suffix = None 177 | 178 | # Output file base name for HTML help builder. 179 | htmlhelp_basename = 'ReadtheDocsTemplatedoc' 180 | 181 | 182 | # -- Options for LaTeX output --------------------------------------------- 183 | 184 | latex_elements = { 185 | # The paper size ('letterpaper' or 'a4paper'). 186 | #'papersize': 'letterpaper', 187 | 188 | # The font size ('10pt', '11pt' or '12pt'). 189 | #'pointsize': '10pt', 190 | 191 | # Additional stuff for the LaTeX preamble. 192 | #'preamble': '', 193 | } 194 | 195 | # Grouping the document tree into LaTeX files. List of tuples 196 | # (source start file, target name, title, 197 | # author, documentclass [howto, manual, or own class]). 198 | latex_documents = [ 199 | ('index', 'ReadtheDocsTemplate.tex', u'Read the Docs Template Documentation', 200 | u'Read the Docs', 'manual'), 201 | ] 202 | 203 | # The name of an image file (relative to this directory) to place at the top of 204 | # the title page. 205 | #latex_logo = None 206 | 207 | # For "manual" documents, if this is true, then toplevel headings are parts, 208 | # not chapters. 209 | #latex_use_parts = False 210 | 211 | # If true, show page references after internal links. 212 | #latex_show_pagerefs = False 213 | 214 | # If true, show URL addresses after external links. 215 | #latex_show_urls = False 216 | 217 | # Documents to append as an appendix to all manuals. 218 | #latex_appendices = [] 219 | 220 | # If false, no module index is generated. 221 | #latex_domain_indices = True 222 | 223 | 224 | # -- Options for manual page output --------------------------------------- 225 | 226 | # One entry per manual page. List of tuples 227 | # (source start file, name, description, authors, manual section). 228 | man_pages = [ 229 | ('index', 'readthedocstemplate', u'Read the Docs Template Documentation', 230 | [u'Read the Docs'], 1) 231 | ] 232 | 233 | # If true, show URL addresses after external links. 234 | #man_show_urls = False 235 | 236 | 237 | # -- Options for Texinfo output ------------------------------------------- 238 | 239 | # Grouping the document tree into Texinfo files. List of tuples 240 | # (source start file, target name, title, author, 241 | # dir menu entry, description, category) 242 | texinfo_documents = [ 243 | ('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation', 244 | u'Read the Docs', 'ReadtheDocsTemplate', 'One line description of project.', 245 | 'Miscellaneous'), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | #texinfo_show_urls = 'footnote' 256 | 257 | # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | #texinfo_no_detailmenu = False 259 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/images/Arduino_IDE_issue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jtobinart/MicroPython_CYD_ESP32-2432S028R/6ef7b313e4787250a0e85c9a31e610a318289d3c/docs/images/Arduino_IDE_issue.png -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Test 2 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | Install the package with pip:: 6 | 7 | $ pip install read-the-docs-template 8 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 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. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use this template, simply update it:: 6 | 7 | import read-the-docs-template 8 | -------------------------------------------------------------------------------- /examples/speaker_demo.py: -------------------------------------------------------------------------------- 1 | # CYDr Speaker Demo 2 | # Tags: Micropython Cheap Yellow Device DIYmall ESP32-2432S028R 3 | # Last Updated: Jan. 15, 2024 4 | # Author(s): James Tobin 5 | # License: MIT 6 | # https://github.com/jtobinart/MicroPython_CYD_ESP32-2432S028R 7 | 8 | import time 9 | from cydr import CYD 10 | 11 | cyd = CYD() 12 | 13 | cyd.display.fill_rectangle(0, 0, cyd.display.width-1, cyd.display.height-1, cyd.BLUE) 14 | 15 | 16 | duration = 500 # How long to play each note. (in milliseconds) 17 | pause = 2.0 # How long to pause in between each tone. (in seconds) 18 | 19 | # Play tone 1 20 | print("Playing Tone 1") 21 | cyd.display.draw_text8x8(cyd.display.width // 2 - 56, cyd.display.height // 2 - 4, "Playing Tone 1", cyd.WHITE, background=cyd.BLUE) 22 | 23 | cyd.play_tone(220, duration) # A4 Tone 24 | time.sleep(pause) 25 | 26 | # Play tone 2 27 | print("Playing Tone 2") 28 | cyd.display.draw_text8x8(cyd.display.width // 2 - 56, cyd.display.height // 2 - 4, "Playing Tone 2", cyd.WHITE, background=cyd.BLUE) 29 | 30 | cyd.play_tone(440, duration) # C5 Tone 31 | time.sleep(pause) 32 | 33 | cyd.shutdown() 34 | -------------------------------------------------------------------------------- /examples/touch_demo.py: -------------------------------------------------------------------------------- 1 | # CYDr Touchscreen Demo 2 | # Tags: Micropython Cheap Yellow Device DIYmall ESP32-2432S028R 3 | # Last Updated: June 15, 2024 4 | # Author(s): James Tobin 5 | # License: MIT 6 | # https://github.com/jtobinart/MicroPython_CYD_ESP32-2432S028R 7 | 8 | from cydr import CYD 9 | import time 10 | 11 | # Create an instance of CYD 12 | cyd = CYD() 13 | 14 | # Draw "TOUCH ME" at the top of the display. 15 | cyd.display.draw_text8x8(cyd.display.width // 2 - 32, 10, "TOUCH ME", cyd.WHITE, background=cyd.RED) 16 | 17 | # List of color choices 18 | colors = [cyd.RED, cyd.GREEN, cyd.BLUE] 19 | 20 | c = 0 # Initial color choice 21 | r = 4 # Radius of cirlces 22 | 23 | while True: 24 | time.sleep(0.05) 25 | x, y = cyd.touches() # 26 | 27 | # Check that there ar new touch points (Default values are x = 0, y = 0) 28 | if x == 0 and y == 0: 29 | continue 30 | 31 | # Double tap to exit 32 | if cyd.double_tap(x,y): 33 | break 34 | 35 | print("Touches:", x, y) 36 | 37 | # Prevent circles from appearing off-screen. 38 | y = min(max(((cyd.display.height - 1) - y), (r+1)),(cyd.display.height-(r+1))) 39 | x = min(max(((cyd.display.width - 1) - x), (r+1)),(cyd.display.width-(r+1))) 40 | 41 | # Create circle 42 | cyd.display.fill_circle(x, y, r, colors[c]) 43 | 44 | cyd.shutdown() 45 | -------------------------------------------------------------------------------- /examples/wifi_advance_demo.py: -------------------------------------------------------------------------------- 1 | # CYDr Advance WIFI Demo 2 | # Tags: Micropython Cheap Yellow Device DIYmall ESP32-2432S028R 3 | # Last Updated: June 15, 2024 4 | # Author(s): James Tobin 5 | # License: MIT 6 | # https://github.com/jtobinart/MicroPython_CYD_ESP32-2432S028R 7 | 8 | from cydr import CYD 9 | import time 10 | import network 11 | import urequests 12 | 13 | # Create an instance of CYD with WIFI support 14 | ssid = "change_me" # The name of the WIFI network you want to connect to. 15 | password = "change_me" # The password of the WIFI network you want to connect to. 16 | 17 | cyd = CYD() 18 | 19 | # Create a WIFI interface. 20 | wifi = network.WLAN(network.STA_IF) 21 | wifi.active(True) 22 | 23 | text = "You are in:" 24 | cyd.display.draw_text8x8(cyd.display.width // 2 - int((len(text)*8)/2), cyd.display.height // 2 - 16, text, cyd.WHITE) 25 | 26 | url = "http://ip-api.com/json/" 27 | 28 | end_time = 0 29 | 30 | while not wifi.isconnected(): 31 | 32 | #Attempt to connect to WIFI network 33 | print("Connecting to network...") 34 | wifi.connect(ssid, password) 35 | time.sleep(0.1) 36 | 37 | while wifi.isconnected(): 38 | x, y = cyd.touches() # Get recent taps x, y 39 | 40 | if time.ticks_ms() > end_time: 41 | r = urequests.get(url).json() 42 | #print(r) # Uncomment to print all data. 43 | text = str(r['city']) 44 | 45 | # draw text 46 | cyd.display.draw_text8x8(cyd.display.width // 2 - int((len(text)*8)/2), cyd.display.height // 2 - 4, text, cyd.WHITE) 47 | 48 | # reset end_time 49 | # We don't want to overburden the server and the CYD with requests so we request updates every 3 minutes. 50 | # This method also allows the other functions like the touch function to work in the background. 51 | end_time = time.ticks_ms() + 180000 # 60000ms = 1 minute 52 | 53 | # Check that there ar new touch points (Default values are x = 0, y = 0) 54 | if x == 0 and y == 0: 55 | continue 56 | 57 | # Double tap to exit 58 | if cyd.double_tap(x,y): 59 | cyd.shutdown() 60 | -------------------------------------------------------------------------------- /examples/wifi_simple_demo.py: -------------------------------------------------------------------------------- 1 | # CYDr Simple WIFI Demo 2 | # Tags: Micropython Cheap Yellow Device DIYmall ESP32-2432S028R 3 | # Last Updated: June 15, 2024 4 | # Author(s): James Tobin 5 | # License: MIT 6 | # https://github.com/jtobinart/MicroPython_CYD_ESP32-2432S028R 7 | 8 | from cydr import CYD 9 | import time 10 | import urequests 11 | 12 | # Create an instance of CYD with WIFI support 13 | ssid = "change_me" # The name of the WIFI network you want to connect to. 14 | password = "change_me" # The password of the WIFI network you want to connect to. 15 | 16 | cyd = CYD(wifi_ssid=ssid, wifi_password=password) 17 | url = "http://api.coindesk.com/v1/bpi/currentprice.json" 18 | #url = "http://api.open-notify.org/astros.json" 19 | #url = "http://ip-api.com/json/" 20 | 21 | end_time = 0 22 | 23 | while cyd.wifi_isconnected(): 24 | x, y = cyd.touches() # Get recent taps x, y 25 | 26 | if time.ticks_ms() > end_time: 27 | r = urequests.get(url).json() 28 | print(r['bpi']['USD']['rate_float']) 29 | text = "B" + str(r['bpi']['USD']['rate_float']) 30 | 31 | # draw text 32 | cyd.display.draw_text8x8(cyd.display.width // 2 - 40, cyd.display.height // 2 - 4, text, cyd.WHITE, background=cyd.RED) 33 | 34 | # reset end_time 35 | # We don't want to overburden the server and the CYD with requests so we request updates every 3 minutes. 36 | end_time = time.ticks_ms() + 180000 # 60000ms = 1 minute 37 | 38 | # Check that there ar new touch points (Default values are x = 0, y = 0) 39 | if x == 0 and y == 0: 40 | continue 41 | 42 | # Double tap to exit 43 | if cyd.double_tap(x,y): 44 | cyd.shutdown() 45 | 46 | -------------------------------------------------------------------------------- /images/Empty: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /resources/README.md: -------------------------------------------------------------------------------- 1 | I do not hold rights overy anthing in this folder. Please contact their authors' for licensing information. 2 | -------------------------------------------------------------------------------- /resources/ili9341.py: -------------------------------------------------------------------------------- 1 | # File: ili9341.py 2 | # Repository: micropython-ili9341 3 | # Retrieved: Dec. 2, 2023 4 | # Author(s): rdagger 5 | # License: MIT 6 | # https://github.com/rdagger/micropython-ili9341/ 7 | 8 | """ILI9341 LCD/Touch module.""" 9 | from time import sleep 10 | from math import cos, sin, pi, radians 11 | from sys import implementation 12 | from framebuf import FrameBuffer, RGB565 # type: ignore 13 | 14 | 15 | def color565(r, g, b): 16 | """Return RGB565 color value. 17 | 18 | Args: 19 | r (int): Red value. 20 | g (int): Green value. 21 | b (int): Blue value. 22 | """ 23 | return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3 24 | 25 | 26 | class Display(object): 27 | """Serial interface for 16-bit color (5-6-5 RGB) IL9341 display. 28 | 29 | Note: All coordinates are zero based. 30 | """ 31 | 32 | # Command constants from ILI9341 datasheet 33 | NOP = const(0x00) # No-op 34 | SWRESET = const(0x01) # Software reset 35 | RDDID = const(0x04) # Read display ID info 36 | RDDST = const(0x09) # Read display status 37 | SLPIN = const(0x10) # Enter sleep mode 38 | SLPOUT = const(0x11) # Exit sleep mode 39 | PTLON = const(0x12) # Partial mode on 40 | NORON = const(0x13) # Normal display mode on 41 | RDMODE = const(0x0A) # Read display power mode 42 | RDMADCTL = const(0x0B) # Read display MADCTL 43 | RDPIXFMT = const(0x0C) # Read display pixel format 44 | RDIMGFMT = const(0x0D) # Read display image format 45 | RDSELFDIAG = const(0x0F) # Read display self-diagnostic 46 | INVOFF = const(0x20) # Display inversion off 47 | INVON = const(0x21) # Display inversion on 48 | GAMMASET = const(0x26) # Gamma set 49 | DISPLAY_OFF = const(0x28) # Display off 50 | DISPLAY_ON = const(0x29) # Display on 51 | SET_COLUMN = const(0x2A) # Column address set 52 | SET_PAGE = const(0x2B) # Page address set 53 | WRITE_RAM = const(0x2C) # Memory write 54 | READ_RAM = const(0x2E) # Memory read 55 | PTLAR = const(0x30) # Partial area 56 | VSCRDEF = const(0x33) # Vertical scrolling definition 57 | MADCTL = const(0x36) # Memory access control 58 | VSCRSADD = const(0x37) # Vertical scrolling start address 59 | PIXFMT = const(0x3A) # COLMOD: Pixel format set 60 | WRITE_DISPLAY_BRIGHTNESS = const(0x51) # Brightness hardware dependent! 61 | READ_DISPLAY_BRIGHTNESS = const(0x52) 62 | WRITE_CTRL_DISPLAY = const(0x53) 63 | READ_CTRL_DISPLAY = const(0x54) 64 | WRITE_CABC = const(0x55) # Write Content Adaptive Brightness Control 65 | READ_CABC = const(0x56) # Read Content Adaptive Brightness Control 66 | WRITE_CABC_MINIMUM = const(0x5E) # Write CABC Minimum Brightness 67 | READ_CABC_MINIMUM = const(0x5F) # Read CABC Minimum Brightness 68 | FRMCTR1 = const(0xB1) # Frame rate control (In normal mode/full colors) 69 | FRMCTR2 = const(0xB2) # Frame rate control (In idle mode/8 colors) 70 | FRMCTR3 = const(0xB3) # Frame rate control (In partial mode/full colors) 71 | INVCTR = const(0xB4) # Display inversion control 72 | DFUNCTR = const(0xB6) # Display function control 73 | PWCTR1 = const(0xC0) # Power control 1 74 | PWCTR2 = const(0xC1) # Power control 2 75 | PWCTRA = const(0xCB) # Power control A 76 | PWCTRB = const(0xCF) # Power control B 77 | VMCTR1 = const(0xC5) # VCOM control 1 78 | VMCTR2 = const(0xC7) # VCOM control 2 79 | RDID1 = const(0xDA) # Read ID 1 80 | RDID2 = const(0xDB) # Read ID 2 81 | RDID3 = const(0xDC) # Read ID 3 82 | RDID4 = const(0xDD) # Read ID 4 83 | GMCTRP1 = const(0xE0) # Positive gamma correction 84 | GMCTRN1 = const(0xE1) # Negative gamma correction 85 | DTCA = const(0xE8) # Driver timing control A 86 | DTCB = const(0xEA) # Driver timing control B 87 | POSC = const(0xED) # Power on sequence control 88 | ENABLE3G = const(0xF2) # Enable 3 gamma control 89 | PUMPRC = const(0xF7) # Pump ratio control 90 | 91 | ROTATE = { 92 | 0: 0x88, 93 | 90: 0xE8, 94 | 180: 0x48, 95 | 270: 0x28 96 | } 97 | 98 | def __init__(self, spi, cs, dc, rst, 99 | width=240, height=320, rotation=0): 100 | """Initialize OLED. 101 | 102 | Args: 103 | spi (Class Spi): SPI interface for OLED 104 | cs (Class Pin): Chip select pin 105 | dc (Class Pin): Data/Command pin 106 | rst (Class Pin): Reset pin 107 | width (Optional int): Screen width (default 240) 108 | height (Optional int): Screen height (default 320) 109 | rotation (Optional int): Rotation must be 0 default, 90. 180 or 270 110 | """ 111 | self.spi = spi 112 | self.cs = cs 113 | self.dc = dc 114 | self.rst = rst 115 | self.width = width 116 | self.height = height 117 | if rotation not in self.ROTATE.keys(): 118 | raise RuntimeError('Rotation must be 0, 90, 180 or 270.') 119 | else: 120 | self.rotation = self.ROTATE[rotation] 121 | 122 | # Initialize GPIO pins and set implementation specific methods 123 | if implementation.name == 'circuitpython': 124 | self.cs.switch_to_output(value=True) 125 | self.dc.switch_to_output(value=False) 126 | self.rst.switch_to_output(value=True) 127 | self.reset = self.reset_cpy 128 | self.write_cmd = self.write_cmd_cpy 129 | self.write_data = self.write_data_cpy 130 | else: 131 | self.cs.init(self.cs.OUT, value=1) 132 | self.dc.init(self.dc.OUT, value=0) 133 | self.rst.init(self.rst.OUT, value=1) 134 | self.reset = self.reset_mpy 135 | self.write_cmd = self.write_cmd_mpy 136 | self.write_data = self.write_data_mpy 137 | self.reset() 138 | # Send initialization commands 139 | self.write_cmd(self.SWRESET) # Software reset 140 | sleep(.1) 141 | self.write_cmd(self.PWCTRB, 0x00, 0xC1, 0x30) # Pwr ctrl B 142 | self.write_cmd(self.POSC, 0x64, 0x03, 0x12, 0x81) # Pwr on seq. ctrl 143 | self.write_cmd(self.DTCA, 0x85, 0x00, 0x78) # Driver timing ctrl A 144 | self.write_cmd(self.PWCTRA, 0x39, 0x2C, 0x00, 0x34, 0x02) # Pwr ctrl A 145 | self.write_cmd(self.PUMPRC, 0x20) # Pump ratio control 146 | self.write_cmd(self.DTCB, 0x00, 0x00) # Driver timing ctrl B 147 | self.write_cmd(self.PWCTR1, 0x23) # Pwr ctrl 1 148 | self.write_cmd(self.PWCTR2, 0x10) # Pwr ctrl 2 149 | self.write_cmd(self.VMCTR1, 0x3E, 0x28) # VCOM ctrl 1 150 | self.write_cmd(self.VMCTR2, 0x86) # VCOM ctrl 2 151 | self.write_cmd(self.MADCTL, self.rotation) # Memory access ctrl 152 | self.write_cmd(self.VSCRSADD, 0x00) # Vertical scrolling start address 153 | self.write_cmd(self.PIXFMT, 0x55) # COLMOD: Pixel format 154 | self.write_cmd(self.FRMCTR1, 0x00, 0x18) # Frame rate ctrl 155 | self.write_cmd(self.DFUNCTR, 0x08, 0x82, 0x27) 156 | self.write_cmd(self.ENABLE3G, 0x00) # Enable 3 gamma ctrl 157 | self.write_cmd(self.GAMMASET, 0x01) # Gamma curve selected 158 | self.write_cmd(self.GMCTRP1, 0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, 0x4E, 159 | 0xF1, 0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00) 160 | self.write_cmd(self.GMCTRN1, 0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, 0x31, 161 | 0xC1, 0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F) 162 | self.write_cmd(self.SLPOUT) # Exit sleep 163 | sleep(.1) 164 | self.write_cmd(self.DISPLAY_ON) # Display on 165 | sleep(.1) 166 | self.clear() 167 | 168 | def block(self, x0, y0, x1, y1, data): 169 | """Write a block of data to display. 170 | 171 | Args: 172 | x0 (int): Starting X position. 173 | y0 (int): Starting Y position. 174 | x1 (int): Ending X position. 175 | y1 (int): Ending Y position. 176 | data (bytes): Data buffer to write. 177 | """ 178 | self.write_cmd(self.SET_COLUMN, 179 | x0 >> 8, x0 & 0xff, x1 >> 8, x1 & 0xff) 180 | self.write_cmd(self.SET_PAGE, 181 | y0 >> 8, y0 & 0xff, y1 >> 8, y1 & 0xff) 182 | self.write_cmd(self.WRITE_RAM) 183 | self.write_data(data) 184 | 185 | def cleanup(self): 186 | """Clean up resources.""" 187 | self.clear() 188 | self.display_off() 189 | self.spi.deinit() 190 | print('display off') 191 | 192 | def clear(self, color=0, hlines=8): 193 | """Clear display. 194 | 195 | Args: 196 | color (Optional int): RGB565 color value (Default: 0 = Black). 197 | hlines (Optional int): # of horizontal lines per chunk (Default: 8) 198 | Note: 199 | hlines was introduced to deal with memory allocation on some 200 | boards. Smaller values allocate less memory but take longer 201 | to execute. hlines must be a factor of the display height. 202 | For example, for a 240 pixel height, valid values for hline 203 | would be 1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64, 80, 160. 204 | Higher values may result in memory allocation errors. 205 | """ 206 | w = self.width 207 | h = self.height 208 | assert hlines > 0 and h % hlines == 0, ( 209 | "hlines must be a non-zero factor of height.") 210 | # Clear display 211 | if color: 212 | line = color.to_bytes(2, 'big') * (w * hlines) 213 | else: 214 | line = bytearray(w * 2 * hlines) 215 | for y in range(0, h, hlines): 216 | self.block(0, y, w - 1, y + hlines - 1, line) 217 | 218 | def display_off(self): 219 | """Turn display off.""" 220 | self.write_cmd(self.DISPLAY_OFF) 221 | 222 | def display_on(self): 223 | """Turn display on.""" 224 | self.write_cmd(self.DISPLAY_ON) 225 | 226 | def draw_circle(self, x0, y0, r, color): 227 | """Draw a circle. 228 | 229 | Args: 230 | x0 (int): X coordinate of center point. 231 | y0 (int): Y coordinate of center point. 232 | r (int): Radius. 233 | color (int): RGB565 color value. 234 | """ 235 | f = 1 - r 236 | dx = 1 237 | dy = -r - r 238 | x = 0 239 | y = r 240 | self.draw_pixel(x0, y0 + r, color) 241 | self.draw_pixel(x0, y0 - r, color) 242 | self.draw_pixel(x0 + r, y0, color) 243 | self.draw_pixel(x0 - r, y0, color) 244 | while x < y: 245 | if f >= 0: 246 | y -= 1 247 | dy += 2 248 | f += dy 249 | x += 1 250 | dx += 2 251 | f += dx 252 | self.draw_pixel(x0 + x, y0 + y, color) 253 | self.draw_pixel(x0 - x, y0 + y, color) 254 | self.draw_pixel(x0 + x, y0 - y, color) 255 | self.draw_pixel(x0 - x, y0 - y, color) 256 | self.draw_pixel(x0 + y, y0 + x, color) 257 | self.draw_pixel(x0 - y, y0 + x, color) 258 | self.draw_pixel(x0 + y, y0 - x, color) 259 | self.draw_pixel(x0 - y, y0 - x, color) 260 | 261 | def draw_ellipse(self, x0, y0, a, b, color): 262 | """Draw an ellipse. 263 | 264 | Args: 265 | x0, y0 (int): Coordinates of center point. 266 | a (int): Semi axis horizontal. 267 | b (int): Semi axis vertical. 268 | color (int): RGB565 color value. 269 | Note: 270 | The center point is the center of the x0,y0 pixel. 271 | Since pixels are not divisible, the axes are integer rounded 272 | up to complete on a full pixel. Therefore the major and 273 | minor axes are increased by 1. 274 | """ 275 | a2 = a * a 276 | b2 = b * b 277 | twoa2 = a2 + a2 278 | twob2 = b2 + b2 279 | x = 0 280 | y = b 281 | px = 0 282 | py = twoa2 * y 283 | # Plot initial points 284 | self.draw_pixel(x0 + x, y0 + y, color) 285 | self.draw_pixel(x0 - x, y0 + y, color) 286 | self.draw_pixel(x0 + x, y0 - y, color) 287 | self.draw_pixel(x0 - x, y0 - y, color) 288 | # Region 1 289 | p = round(b2 - (a2 * b) + (0.25 * a2)) 290 | while px < py: 291 | x += 1 292 | px += twob2 293 | if p < 0: 294 | p += b2 + px 295 | else: 296 | y -= 1 297 | py -= twoa2 298 | p += b2 + px - py 299 | self.draw_pixel(x0 + x, y0 + y, color) 300 | self.draw_pixel(x0 - x, y0 + y, color) 301 | self.draw_pixel(x0 + x, y0 - y, color) 302 | self.draw_pixel(x0 - x, y0 - y, color) 303 | # Region 2 304 | p = round(b2 * (x + 0.5) * (x + 0.5) + 305 | a2 * (y - 1) * (y - 1) - a2 * b2) 306 | while y > 0: 307 | y -= 1 308 | py -= twoa2 309 | if p > 0: 310 | p += a2 - py 311 | else: 312 | x += 1 313 | px += twob2 314 | p += a2 - py + px 315 | self.draw_pixel(x0 + x, y0 + y, color) 316 | self.draw_pixel(x0 - x, y0 + y, color) 317 | self.draw_pixel(x0 + x, y0 - y, color) 318 | self.draw_pixel(x0 - x, y0 - y, color) 319 | 320 | def draw_hline(self, x, y, w, color): 321 | """Draw a horizontal line. 322 | 323 | Args: 324 | x (int): Starting X position. 325 | y (int): Starting Y position. 326 | w (int): Width of line. 327 | color (int): RGB565 color value. 328 | """ 329 | if self.is_off_grid(x, y, x + w - 1, y): 330 | return 331 | line = color.to_bytes(2, 'big') * w 332 | self.block(x, y, x + w - 1, y, line) 333 | 334 | def draw_image(self, path, x=0, y=0, w=320, h=240): 335 | """Draw image from flash. 336 | 337 | Args: 338 | path (string): Image file path. 339 | x (int): X coordinate of image left. Default is 0. 340 | y (int): Y coordinate of image top. Default is 0. 341 | w (int): Width of image. Default is 320. 342 | h (int): Height of image. Default is 240. 343 | """ 344 | x2 = x + w - 1 345 | y2 = y + h - 1 346 | if self.is_off_grid(x, y, x2, y2): 347 | return 348 | with open(path, "rb") as f: 349 | chunk_height = 1024 // w 350 | chunk_count, remainder = divmod(h, chunk_height) 351 | chunk_size = chunk_height * w * 2 352 | chunk_y = y 353 | if chunk_count: 354 | for c in range(0, chunk_count): 355 | buf = f.read(chunk_size) 356 | self.block(x, chunk_y, 357 | x2, chunk_y + chunk_height - 1, 358 | buf) 359 | chunk_y += chunk_height 360 | if remainder: 361 | buf = f.read(remainder * w * 2) 362 | self.block(x, chunk_y, 363 | x2, chunk_y + remainder - 1, 364 | buf) 365 | 366 | def draw_letter(self, x, y, letter, font, color, background=0, 367 | landscape=False, rotate_180=False): 368 | """Draw a letter. 369 | 370 | Args: 371 | x (int): Starting X position. 372 | y (int): Starting Y position. 373 | letter (string): Letter to draw. 374 | font (XglcdFont object): Font. 375 | color (int): RGB565 color value. 376 | background (int): RGB565 background color (default: black) 377 | landscape (bool): Orientation (default: False = portrait) 378 | rotate_180 (bool): Rotate text by 180 degrees 379 | """ 380 | buf, w, h = font.get_letter(letter, color, background, landscape) 381 | if rotate_180: 382 | # Manually rotate the buffer by 180 degrees 383 | # ensure bytes pairs for each pixel retain color565 384 | new_buf = bytearray(len(buf)) 385 | num_pixels = len(buf) // 2 386 | for i in range(num_pixels): 387 | # The index for the new buffer's byte pair 388 | new_idx = (num_pixels - 1 - i) * 2 389 | # The index for the original buffer's byte pair 390 | old_idx = i * 2 391 | # Swap the pixels 392 | new_buf[new_idx], new_buf[new_idx + 1] = buf[old_idx], buf[old_idx + 1] 393 | buf = new_buf 394 | 395 | # Check for errors (Font could be missing specified letter) 396 | if w == 0: 397 | return w, h 398 | 399 | if landscape: 400 | y -= w 401 | if self.is_off_grid(x, y, x + h - 1, y + w - 1): 402 | return 0, 0 403 | self.block(x, y, 404 | x + h - 1, y + w - 1, 405 | buf) 406 | else: 407 | if self.is_off_grid(x, y, x + w - 1, y + h - 1): 408 | return 0, 0 409 | self.block(x, y, 410 | x + w - 1, y + h - 1, 411 | buf) 412 | return w, h 413 | 414 | def draw_line(self, x1, y1, x2, y2, color): 415 | """Draw a line using Bresenham's algorithm. 416 | 417 | Args: 418 | x1, y1 (int): Starting coordinates of the line 419 | x2, y2 (int): Ending coordinates of the line 420 | color (int): RGB565 color value. 421 | """ 422 | # Check for horizontal line 423 | if y1 == y2: 424 | if x1 > x2: 425 | x1, x2 = x2, x1 426 | self.draw_hline(x1, y1, x2 - x1 + 1, color) 427 | return 428 | # Check for vertical line 429 | if x1 == x2: 430 | if y1 > y2: 431 | y1, y2 = y2, y1 432 | self.draw_vline(x1, y1, y2 - y1 + 1, color) 433 | return 434 | # Confirm coordinates in boundary 435 | if self.is_off_grid(min(x1, x2), min(y1, y2), 436 | max(x1, x2), max(y1, y2)): 437 | return 438 | # Changes in x, y 439 | dx = x2 - x1 440 | dy = y2 - y1 441 | # Determine how steep the line is 442 | is_steep = abs(dy) > abs(dx) 443 | # Rotate line 444 | if is_steep: 445 | x1, y1 = y1, x1 446 | x2, y2 = y2, x2 447 | # Swap start and end points if necessary 448 | if x1 > x2: 449 | x1, x2 = x2, x1 450 | y1, y2 = y2, y1 451 | # Recalculate differentials 452 | dx = x2 - x1 453 | dy = y2 - y1 454 | # Calculate error 455 | error = dx >> 1 456 | ystep = 1 if y1 < y2 else -1 457 | y = y1 458 | for x in range(x1, x2 + 1): 459 | # Had to reverse HW ???? 460 | if not is_steep: 461 | self.draw_pixel(x, y, color) 462 | else: 463 | self.draw_pixel(y, x, color) 464 | error -= abs(dy) 465 | if error < 0: 466 | y += ystep 467 | error += dx 468 | 469 | def draw_lines(self, coords, color): 470 | """Draw multiple lines. 471 | 472 | Args: 473 | coords ([[int, int],...]): Line coordinate X, Y pairs 474 | color (int): RGB565 color value. 475 | """ 476 | # Starting point 477 | x1, y1 = coords[0] 478 | # Iterate through coordinates 479 | for i in range(1, len(coords)): 480 | x2, y2 = coords[i] 481 | self.draw_line(x1, y1, x2, y2, color) 482 | x1, y1 = x2, y2 483 | 484 | def draw_pixel(self, x, y, color): 485 | """Draw a single pixel. 486 | 487 | Args: 488 | x (int): X position. 489 | y (int): Y position. 490 | color (int): RGB565 color value. 491 | """ 492 | if self.is_off_grid(x, y, x, y): 493 | return 494 | self.block(x, y, x, y, color.to_bytes(2, 'big')) 495 | 496 | def draw_polygon(self, sides, x0, y0, r, color, rotate=0): 497 | """Draw an n-sided regular polygon. 498 | 499 | Args: 500 | sides (int): Number of polygon sides. 501 | x0, y0 (int): Coordinates of center point. 502 | r (int): Radius. 503 | color (int): RGB565 color value. 504 | rotate (Optional float): Rotation in degrees relative to origin. 505 | Note: 506 | The center point is the center of the x0,y0 pixel. 507 | Since pixels are not divisible, the radius is integer rounded 508 | up to complete on a full pixel. Therefore diameter = 2 x r + 1. 509 | """ 510 | coords = [] 511 | theta = radians(rotate) 512 | n = sides + 1 513 | for s in range(n): 514 | t = 2.0 * pi * s / sides + theta 515 | coords.append([int(r * cos(t) + x0), int(r * sin(t) + y0)]) 516 | 517 | # Cast to python float first to fix rounding errors 518 | self.draw_lines(coords, color=color) 519 | 520 | def draw_rectangle(self, x, y, w, h, color): 521 | """Draw a rectangle. 522 | 523 | Args: 524 | x (int): Starting X position. 525 | y (int): Starting Y position. 526 | w (int): Width of rectangle. 527 | h (int): Height of rectangle. 528 | color (int): RGB565 color value. 529 | """ 530 | x2 = x + w - 1 531 | y2 = y + h - 1 532 | self.draw_hline(x, y, w, color) 533 | self.draw_hline(x, y2, w, color) 534 | self.draw_vline(x, y, h, color) 535 | self.draw_vline(x2, y, h, color) 536 | 537 | def draw_sprite(self, buf, x, y, w, h): 538 | """Draw a sprite (optimized for horizontal drawing). 539 | 540 | Args: 541 | buf (bytearray): Buffer to draw. 542 | x (int): Starting X position. 543 | y (int): Starting Y position. 544 | w (int): Width of drawing. 545 | h (int): Height of drawing. 546 | """ 547 | x2 = x + w - 1 548 | y2 = y + h - 1 549 | if self.is_off_grid(x, y, x2, y2): 550 | return 551 | self.block(x, y, x2, y2, buf) 552 | 553 | def draw_text(self, x, y, text, font, color, background=0, 554 | landscape=False, rotate_180=False, spacing=1): 555 | """Draw text. 556 | 557 | Args: 558 | x (int): Starting X position 559 | y (int): Starting Y position 560 | text (string): Text to draw 561 | font (XglcdFont object): Font 562 | color (int): RGB565 color value 563 | background (int): RGB565 background color (default: black) 564 | landscape (bool): Orientation (default: False = portrait) 565 | rotate_180 (bool): Rotate text by 180 degrees 566 | spacing (int): Pixels between letters (default: 1) 567 | """ 568 | iterable_text = reversed(text) if rotate_180 else text 569 | for letter in iterable_text: 570 | # Get letter array and letter dimensions 571 | w, h = self.draw_letter(x, y, letter, font, color, background, 572 | landscape, rotate_180) 573 | # Stop on error 574 | if w == 0 or h == 0: 575 | print('Invalid width {0} or height {1}'.format(w, h)) 576 | return 577 | 578 | if landscape: 579 | # Fill in spacing 580 | if spacing: 581 | self.fill_hrect(x, y - w - spacing, h, spacing, background) 582 | # Position y for next letter 583 | y -= (w + spacing) 584 | else: 585 | # Fill in spacing 586 | if spacing: 587 | self.fill_hrect(x + w, y, spacing, h, background) 588 | # Position x for next letter 589 | x += (w + spacing) 590 | 591 | # # Fill in spacing 592 | # if spacing: 593 | # self.fill_vrect(x + w, y, spacing, h, background) 594 | # # Position x for next letter 595 | # x += w + spacing 596 | 597 | def draw_text8x8(self, x, y, text, color, background=0, 598 | rotate=0): 599 | """Draw text using built-in MicroPython 8x8 bit font. 600 | 601 | Args: 602 | x (int): Starting X position. 603 | y (int): Starting Y position. 604 | text (string): Text to draw. 605 | color (int): RGB565 color value. 606 | background (int): RGB565 background color (default: black). 607 | rotate(int): 0, 90, 180, 270 608 | """ 609 | w = len(text) * 8 610 | h = 8 611 | # Confirm coordinates in boundary 612 | if self.is_off_grid(x, y, x + 7, y + 7): 613 | return 614 | # Rearrange color 615 | r = (color & 0xF800) >> 8 616 | g = (color & 0x07E0) >> 3 617 | b = (color & 0x1F) << 3 618 | buf = bytearray(w * 16) 619 | fbuf = FrameBuffer(buf, w, h, RGB565) 620 | if background != 0: 621 | bg_r = (background & 0xF800) >> 8 622 | bg_g = (background & 0x07E0) >> 3 623 | bg_b = (background & 0x1F) << 3 624 | fbuf.fill(color565(bg_b, bg_r, bg_g)) 625 | fbuf.text(text, 0, 0, color565(b, r, g)) 626 | if rotate == 0: 627 | self.block(x, y, x + w - 1, y + (h - 1), buf) 628 | elif rotate == 90: 629 | buf2 = bytearray(w * 16) 630 | fbuf2 = FrameBuffer(buf2, h, w, RGB565) 631 | for y1 in range(h): 632 | for x1 in range(w): 633 | fbuf2.pixel(y1, x1, 634 | fbuf.pixel(x1, (h - 1) - y1)) 635 | self.block(x, y, x + (h - 1), y + w - 1, buf2) 636 | elif rotate == 180: 637 | buf2 = bytearray(w * 16) 638 | fbuf2 = FrameBuffer(buf2, w, h, RGB565) 639 | for y1 in range(h): 640 | for x1 in range(w): 641 | fbuf2.pixel(x1, y1, 642 | fbuf.pixel((w - 1) - x1, (h - 1) - y1)) 643 | self.block(x, y, x + w - 1, y + (h - 1), buf2) 644 | elif rotate == 270: 645 | buf2 = bytearray(w * 16) 646 | fbuf2 = FrameBuffer(buf2, h, w, RGB565) 647 | for y1 in range(h): 648 | for x1 in range(w): 649 | fbuf2.pixel(y1, x1, 650 | fbuf.pixel((w - 1) - x1, y1)) 651 | self.block(x, y, x + (h - 1), y + w - 1, buf2) 652 | 653 | def draw_vline(self, x, y, h, color): 654 | """Draw a vertical line. 655 | 656 | Args: 657 | x (int): Starting X position. 658 | y (int): Starting Y position. 659 | h (int): Height of line. 660 | color (int): RGB565 color value. 661 | """ 662 | # Confirm coordinates in boundary 663 | if self.is_off_grid(x, y, x, y + h - 1): 664 | return 665 | line = color.to_bytes(2, 'big') * h 666 | self.block(x, y, x, y + h - 1, line) 667 | 668 | def fill_circle(self, x0, y0, r, color): 669 | """Draw a filled circle. 670 | 671 | Args: 672 | x0 (int): X coordinate of center point. 673 | y0 (int): Y coordinate of center point. 674 | r (int): Radius. 675 | color (int): RGB565 color value. 676 | """ 677 | f = 1 - r 678 | dx = 1 679 | dy = -r - r 680 | x = 0 681 | y = r 682 | self.draw_vline(x0, y0 - r, 2 * r + 1, color) 683 | while x < y: 684 | if f >= 0: 685 | y -= 1 686 | dy += 2 687 | f += dy 688 | x += 1 689 | dx += 2 690 | f += dx 691 | self.draw_vline(x0 + x, y0 - y, 2 * y + 1, color) 692 | self.draw_vline(x0 - x, y0 - y, 2 * y + 1, color) 693 | self.draw_vline(x0 - y, y0 - x, 2 * x + 1, color) 694 | self.draw_vline(x0 + y, y0 - x, 2 * x + 1, color) 695 | 696 | def fill_ellipse(self, x0, y0, a, b, color): 697 | """Draw a filled ellipse. 698 | 699 | Args: 700 | x0, y0 (int): Coordinates of center point. 701 | a (int): Semi axis horizontal. 702 | b (int): Semi axis vertical. 703 | color (int): RGB565 color value. 704 | Note: 705 | The center point is the center of the x0,y0 pixel. 706 | Since pixels are not divisible, the axes are integer rounded 707 | up to complete on a full pixel. Therefore the major and 708 | minor axes are increased by 1. 709 | """ 710 | a2 = a * a 711 | b2 = b * b 712 | twoa2 = a2 + a2 713 | twob2 = b2 + b2 714 | x = 0 715 | y = b 716 | px = 0 717 | py = twoa2 * y 718 | # Plot initial points 719 | self.draw_line(x0, y0 - y, x0, y0 + y, color) 720 | # Region 1 721 | p = round(b2 - (a2 * b) + (0.25 * a2)) 722 | while px < py: 723 | x += 1 724 | px += twob2 725 | if p < 0: 726 | p += b2 + px 727 | else: 728 | y -= 1 729 | py -= twoa2 730 | p += b2 + px - py 731 | self.draw_line(x0 + x, y0 - y, x0 + x, y0 + y, color) 732 | self.draw_line(x0 - x, y0 - y, x0 - x, y0 + y, color) 733 | # Region 2 734 | p = round(b2 * (x + 0.5) * (x + 0.5) + 735 | a2 * (y - 1) * (y - 1) - a2 * b2) 736 | while y > 0: 737 | y -= 1 738 | py -= twoa2 739 | if p > 0: 740 | p += a2 - py 741 | else: 742 | x += 1 743 | px += twob2 744 | p += a2 - py + px 745 | self.draw_line(x0 + x, y0 - y, x0 + x, y0 + y, color) 746 | self.draw_line(x0 - x, y0 - y, x0 - x, y0 + y, color) 747 | 748 | def fill_hrect(self, x, y, w, h, color): 749 | """Draw a filled rectangle (optimized for horizontal drawing). 750 | 751 | Args: 752 | x (int): Starting X position. 753 | y (int): Starting Y position. 754 | w (int): Width of rectangle. 755 | h (int): Height of rectangle. 756 | color (int): RGB565 color value. 757 | """ 758 | if self.is_off_grid(x, y, x + w - 1, y + h - 1): 759 | return 760 | chunk_height = 1024 // w 761 | chunk_count, remainder = divmod(h, chunk_height) 762 | chunk_size = chunk_height * w 763 | chunk_y = y 764 | if chunk_count: 765 | buf = color.to_bytes(2, 'big') * chunk_size 766 | for c in range(0, chunk_count): 767 | self.block(x, chunk_y, 768 | x + w - 1, chunk_y + chunk_height - 1, 769 | buf) 770 | chunk_y += chunk_height 771 | 772 | if remainder: 773 | buf = color.to_bytes(2, 'big') * remainder * w 774 | self.block(x, chunk_y, 775 | x + w - 1, chunk_y + remainder - 1, 776 | buf) 777 | 778 | def fill_rectangle(self, x, y, w, h, color): 779 | """Draw a filled rectangle. 780 | 781 | Args: 782 | x (int): Starting X position. 783 | y (int): Starting Y position. 784 | w (int): Width of rectangle. 785 | h (int): Height of rectangle. 786 | color (int): RGB565 color value. 787 | """ 788 | if self.is_off_grid(x, y, x + w - 1, y + h - 1): 789 | return 790 | if w > h: 791 | self.fill_hrect(x, y, w, h, color) 792 | else: 793 | self.fill_vrect(x, y, w, h, color) 794 | 795 | def fill_polygon(self, sides, x0, y0, r, color, rotate=0): 796 | """Draw a filled n-sided regular polygon. 797 | 798 | Args: 799 | sides (int): Number of polygon sides. 800 | x0, y0 (int): Coordinates of center point. 801 | r (int): Radius. 802 | color (int): RGB565 color value. 803 | rotate (Optional float): Rotation in degrees relative to origin. 804 | Note: 805 | The center point is the center of the x0,y0 pixel. 806 | Since pixels are not divisible, the radius is integer rounded 807 | up to complete on a full pixel. Therefore diameter = 2 x r + 1. 808 | """ 809 | # Determine side coordinates 810 | coords = [] 811 | theta = radians(rotate) 812 | n = sides + 1 813 | for s in range(n): 814 | t = 2.0 * pi * s / sides + theta 815 | coords.append([int(r * cos(t) + x0), int(r * sin(t) + y0)]) 816 | # Starting point 817 | x1, y1 = coords[0] 818 | # Minimum Maximum X dict 819 | xdict = {y1: [x1, x1]} 820 | # Iterate through coordinates 821 | for row in coords[1:]: 822 | x2, y2 = row 823 | xprev, yprev = x2, y2 824 | # Calculate perimeter 825 | # Check for horizontal side 826 | if y1 == y2: 827 | if x1 > x2: 828 | x1, x2 = x2, x1 829 | if y1 in xdict: 830 | xdict[y1] = [min(x1, xdict[y1][0]), max(x2, xdict[y1][1])] 831 | else: 832 | xdict[y1] = [x1, x2] 833 | x1, y1 = xprev, yprev 834 | continue 835 | # Non horizontal side 836 | # Changes in x, y 837 | dx = x2 - x1 838 | dy = y2 - y1 839 | # Determine how steep the line is 840 | is_steep = abs(dy) > abs(dx) 841 | # Rotate line 842 | if is_steep: 843 | x1, y1 = y1, x1 844 | x2, y2 = y2, x2 845 | # Swap start and end points if necessary 846 | if x1 > x2: 847 | x1, x2 = x2, x1 848 | y1, y2 = y2, y1 849 | # Recalculate differentials 850 | dx = x2 - x1 851 | dy = y2 - y1 852 | # Calculate error 853 | error = dx >> 1 854 | ystep = 1 if y1 < y2 else -1 855 | y = y1 856 | # Calcualte minimum and maximum x values 857 | for x in range(x1, x2 + 1): 858 | if is_steep: 859 | if x in xdict: 860 | xdict[x] = [min(y, xdict[x][0]), max(y, xdict[x][1])] 861 | else: 862 | xdict[x] = [y, y] 863 | else: 864 | if y in xdict: 865 | xdict[y] = [min(x, xdict[y][0]), max(x, xdict[y][1])] 866 | else: 867 | xdict[y] = [x, x] 868 | error -= abs(dy) 869 | if error < 0: 870 | y += ystep 871 | error += dx 872 | x1, y1 = xprev, yprev 873 | # Fill polygon 874 | for y, x in xdict.items(): 875 | self.draw_hline(x[0], y, x[1] - x[0] + 2, color) 876 | 877 | def fill_vrect(self, x, y, w, h, color): 878 | """Draw a filled rectangle (optimized for vertical drawing). 879 | 880 | Args: 881 | x (int): Starting X position. 882 | y (int): Starting Y position. 883 | w (int): Width of rectangle. 884 | h (int): Height of rectangle. 885 | color (int): RGB565 color value. 886 | """ 887 | if self.is_off_grid(x, y, x + w - 1, y + h - 1): 888 | return 889 | chunk_width = 1024 // h 890 | chunk_count, remainder = divmod(w, chunk_width) 891 | chunk_size = chunk_width * h 892 | chunk_x = x 893 | if chunk_count: 894 | buf = color.to_bytes(2, 'big') * chunk_size 895 | for c in range(0, chunk_count): 896 | self.block(chunk_x, y, 897 | chunk_x + chunk_width - 1, y + h - 1, 898 | buf) 899 | chunk_x += chunk_width 900 | 901 | if remainder: 902 | buf = color.to_bytes(2, 'big') * remainder * h 903 | self.block(chunk_x, y, 904 | chunk_x + remainder - 1, y + h - 1, 905 | buf) 906 | 907 | def is_off_grid(self, xmin, ymin, xmax, ymax): 908 | """Check if coordinates extend past display boundaries. 909 | 910 | Args: 911 | xmin (int): Minimum horizontal pixel. 912 | ymin (int): Minimum vertical pixel. 913 | xmax (int): Maximum horizontal pixel. 914 | ymax (int): Maximum vertical pixel. 915 | Returns: 916 | boolean: False = Coordinates OK, True = Error. 917 | """ 918 | if xmin < 0: 919 | print('x-coordinate: {0} below minimum of 0.'.format(xmin)) 920 | return True 921 | if ymin < 0: 922 | print('y-coordinate: {0} below minimum of 0.'.format(ymin)) 923 | return True 924 | if xmax >= self.width: 925 | print('x-coordinate: {0} above maximum of {1}.'.format( 926 | xmax, self.width - 1)) 927 | return True 928 | if ymax >= self.height: 929 | print('y-coordinate: {0} above maximum of {1}.'.format( 930 | ymax, self.height - 1)) 931 | return True 932 | return False 933 | 934 | def load_sprite(self, path, w, h): 935 | """Load sprite image. 936 | 937 | Args: 938 | path (string): Image file path. 939 | w (int): Width of image. 940 | h (int): Height of image. 941 | Notes: 942 | w x h cannot exceed 2048 943 | """ 944 | buf_size = w * h * 2 945 | with open(path, "rb") as f: 946 | return f.read(buf_size) 947 | 948 | def reset_cpy(self): 949 | """Perform reset: Low=initialization, High=normal operation. 950 | 951 | Notes: CircuitPython implemntation 952 | """ 953 | self.rst.value = False 954 | sleep(.05) 955 | self.rst.value = True 956 | sleep(.05) 957 | 958 | def reset_mpy(self): 959 | """Perform reset: Low=initialization, High=normal operation. 960 | 961 | Notes: MicroPython implemntation 962 | """ 963 | self.rst(0) 964 | sleep(.05) 965 | self.rst(1) 966 | sleep(.05) 967 | 968 | def scroll(self, y): 969 | """Scroll display vertically. 970 | 971 | Args: 972 | y (int): Number of pixels to scroll display. 973 | """ 974 | self.write_cmd(self.VSCRSADD, y >> 8, y & 0xFF) 975 | 976 | def set_scroll(self, top, bottom): 977 | """Set the height of the top and bottom scroll margins. 978 | 979 | Args: 980 | top (int): Height of top scroll margin 981 | bottom (int): Height of bottom scroll margin 982 | """ 983 | if top + bottom <= self.height: 984 | middle = self.height - (top + bottom) 985 | (top, middle, bottom) 986 | self.write_cmd(self.VSCRDEF, 987 | top >> 8, 988 | top & 0xFF, 989 | middle >> 8, 990 | middle & 0xFF, 991 | bottom >> 8, 992 | bottom & 0xFF) 993 | 994 | def sleep(self, enable=True): 995 | """Enters or exits sleep mode. 996 | 997 | Args: 998 | enable (bool): True (default)=Enter sleep mode, False=Exit sleep 999 | """ 1000 | if enable: 1001 | self.write_cmd(self.SLPIN) 1002 | else: 1003 | self.write_cmd(self.SLPOUT) 1004 | 1005 | def write_cmd_mpy(self, command, *args): 1006 | """Write command to OLED (MicroPython). 1007 | 1008 | Args: 1009 | command (byte): ILI9341 command code. 1010 | *args (optional bytes): Data to transmit. 1011 | """ 1012 | self.dc(0) 1013 | self.cs(0) 1014 | self.spi.write(bytearray([command])) 1015 | self.cs(1) 1016 | # Handle any passed data 1017 | if len(args) > 0: 1018 | self.write_data(bytearray(args)) 1019 | 1020 | def write_cmd_cpy(self, command, *args): 1021 | """Write command to OLED (CircuitPython). 1022 | 1023 | Args: 1024 | command (byte): ILI9341 command code. 1025 | *args (optional bytes): Data to transmit. 1026 | """ 1027 | self.dc.value = False 1028 | self.cs.value = False 1029 | # Confirm SPI locked before writing 1030 | while not self.spi.try_lock(): 1031 | pass 1032 | self.spi.write(bytearray([command])) 1033 | self.spi.unlock() 1034 | self.cs.value = True 1035 | # Handle any passed data 1036 | if len(args) > 0: 1037 | self.write_data(bytearray(args)) 1038 | 1039 | def write_data_mpy(self, data): 1040 | """Write data to OLED (MicroPython). 1041 | 1042 | Args: 1043 | data (bytes): Data to transmit. 1044 | """ 1045 | self.dc(1) 1046 | self.cs(0) 1047 | self.spi.write(data) 1048 | self.cs(1) 1049 | 1050 | def write_data_cpy(self, data): 1051 | """Write data to OLED (CircuitPython). 1052 | 1053 | Args: 1054 | data (bytes): Data to transmit. 1055 | """ 1056 | self.dc.value = True 1057 | self.cs.value = False 1058 | # Confirm SPI locked before writing 1059 | while not self.spi.try_lock(): 1060 | pass 1061 | self.spi.write(data) 1062 | self.spi.unlock() 1063 | self.cs.value = True 1064 | -------------------------------------------------------------------------------- /resources/xpt2046.py: -------------------------------------------------------------------------------- 1 | # File: xpt2046.py 2 | # Repository: micropython-ili9341 3 | # Retrieved: Dec. 2, 2023 4 | # Author(s): rdagger 5 | # License: MIT 6 | # https://github.com/rdagger/micropython-ili9341/ 7 | 8 | """XPT2046 Touch module.""" 9 | from time import sleep 10 | 11 | 12 | class Touch(object): 13 | """Serial interface for XPT2046 Touch Screen Controller.""" 14 | 15 | # Command constants from ILI9341 datasheet 16 | GET_X = const(0b11010000) # X position 17 | GET_Y = const(0b10010000) # Y position 18 | GET_Z1 = const(0b10110000) # Z1 position 19 | GET_Z2 = const(0b11000000) # Z2 position 20 | GET_TEMP0 = const(0b10000000) # Temperature 0 21 | GET_TEMP1 = const(0b11110000) # Temperature 1 22 | GET_BATTERY = const(0b10100000) # Battery monitor 23 | GET_AUX = const(0b11100000) # Auxiliary input to ADC 24 | 25 | def __init__(self, spi, cs, int_pin=None, int_handler=None, 26 | width=240, height=320, 27 | x_min=100, x_max=1962, y_min=100, y_max=1900): 28 | """Initialize touch screen controller. 29 | 30 | Args: 31 | spi (Class Spi): SPI interface for OLED 32 | cs (Class Pin): Chip select pin 33 | int_pin (Class Pin): Touch controller interrupt pin 34 | int_handler (function): Handler for screen interrupt 35 | width (int): Width of LCD screen 36 | height (int): Height of LCD screen 37 | x_min (int): Minimum x coordinate 38 | x_max (int): Maximum x coordinate 39 | y_min (int): Minimum Y coordinate 40 | y_max (int): Maximum Y coordinate 41 | """ 42 | self.spi = spi 43 | self.cs = cs 44 | self.cs.init(self.cs.OUT, value=1) 45 | self.rx_buf = bytearray(3) # Receive buffer 46 | self.tx_buf = bytearray(3) # Transmit buffer 47 | self.width = width 48 | self.height = height 49 | # Set calibration 50 | self.x_min = x_min 51 | self.x_max = x_max 52 | self.y_min = y_min 53 | self.y_max = y_max 54 | self.x_multiplier = width / (x_max - x_min) 55 | self.x_add = x_min * -self.x_multiplier 56 | self.y_multiplier = height / (y_max - y_min) 57 | self.y_add = y_min * -self.y_multiplier 58 | 59 | if int_pin is not None: 60 | self.int_pin = int_pin 61 | self.int_pin.init(int_pin.IN) 62 | self.int_handler = int_handler 63 | self.int_locked = False 64 | int_pin.irq(trigger=int_pin.IRQ_FALLING | int_pin.IRQ_RISING, 65 | handler=self.int_press) 66 | 67 | def get_touch(self): 68 | """Take multiple samples to get accurate touch reading.""" 69 | timeout = 2 # set timeout to 2 seconds 70 | confidence = 5 71 | buff = [[0, 0] for x in range(confidence)] 72 | buf_length = confidence # Require a confidence of 5 good samples 73 | buffptr = 0 # Track current buffer position 74 | nsamples = 0 # Count samples 75 | while timeout > 0: 76 | if nsamples == buf_length: 77 | meanx = sum([c[0] for c in buff]) // buf_length 78 | meany = sum([c[1] for c in buff]) // buf_length 79 | dev = sum([(c[0] - meanx)**2 + 80 | (c[1] - meany)**2 for c in buff]) / buf_length 81 | if dev <= 50: # Deviation should be under margin of 50 82 | return self.normalize(meanx, meany) 83 | # get a new value 84 | sample = self.raw_touch() # get a touch 85 | if sample is None: 86 | nsamples = 0 # Invalidate buff 87 | else: 88 | buff[buffptr] = sample # put in buff 89 | buffptr = (buffptr + 1) % buf_length # Incr, until rollover 90 | nsamples = min(nsamples + 1, buf_length) # Incr. until max 91 | 92 | sleep(.05) 93 | timeout -= .05 94 | return None 95 | 96 | def int_press(self, pin): 97 | """Send X,Y values to passed interrupt handler.""" 98 | if not pin.value() and not self.int_locked: 99 | self.int_locked = True # Lock Interrupt 100 | buff = self.raw_touch() 101 | 102 | if buff is not None: 103 | x, y = self.normalize(*buff) 104 | self.int_handler(x, y) 105 | sleep(.1) # Debounce falling edge 106 | elif pin.value() and self.int_locked: 107 | sleep(.1) # Debounce rising edge 108 | self.int_locked = False # Unlock interrupt 109 | 110 | def normalize(self, x, y): 111 | """Normalize mean X,Y values to match LCD screen.""" 112 | x = int(self.x_multiplier * x + self.x_add) 113 | y = int(self.y_multiplier * y + self.y_add) 114 | return x, y 115 | 116 | def raw_touch(self): 117 | """Read raw X,Y touch values. 118 | 119 | Returns: 120 | tuple(int, int): X, Y 121 | """ 122 | x = self.send_command(self.GET_X) 123 | y = self.send_command(self.GET_Y) 124 | if self.x_min <= x <= self.x_max and self.y_min <= y <= self.y_max: 125 | return (x, y) 126 | else: 127 | return None 128 | 129 | def send_command(self, command): 130 | """Write command to XT2046 (MicroPython). 131 | 132 | Args: 133 | command (byte): XT2046 command code. 134 | Returns: 135 | int: 12 bit response 136 | """ 137 | self.tx_buf[0] = command 138 | self.cs(0) 139 | self.spi.write_readinto(self.tx_buf, self.rx_buf) 140 | self.cs(1) 141 | 142 | return (self.rx_buf[1] << 4) | (self.rx_buf[2] >> 4) 143 | --------------------------------------------------------------------------------