Categories
CircuitPython Microcontroller Software Development

PyPortal Event Countdown Clock Mods III

Some big updates to the software for the modified PyPortal Event Countdown Clock. The UI was changed and several features added. It also seems to be more stable as it does not lock-up randomly. Let’s get into the changes.

  • Header and Footer status bars display information
    • Header
      • Temperature
        • Touch to change between Fahrenheit and Celsius
      • Time
        • Touch to change between 24 hour and 12 hour formats
      • Network Strength
    • Footer
      • Brightness
        • Touching the left side of the footer, dims the display backlight
        • Touching the right side of the footer, increases the brightness of the display backlight
        • Touching the middle of the footer, returns to auto brightness of the display backlight
      • Event of the number of events
  • Change the event displayed by touching the left of the display to show previous event or the right side to advance to the next event.
  • If an event has passed more than a day ago, they will be removed from the list of events and no longer displayed
  • The events do not need to be in order in the JSON file. They are sorted when they are loaded from the SD Card with the soonest event being displayed first.
Demo of the PyPortal Event Countdown Clock Mods

Noticed that the temperature was several degrees too high. This was due to the ADT7410 being too close to devices generating heat. I removed the ADT7410 and placed it on a small board and added a PH2 JST connector so it may be plugged into the I2C socket. This resulted in much more usable temperature reading.

PyPortal Event Countdown with temperature sensor moved off the PyPortal
ADT7410 Temperature Sensor moved to a separate board.

Adafruit PyPortal Titano

I just purchased an Adafruit PyPortal Titano, Product ID: 4444, to test out the software and see about allowing the software to be used on different sized screens. The Titano, has a 480×320 screen verses 320×240 of the PyPortal, Product ID: 4116.

The PyPortal Titano that I received had CircuitPython 5 installed, so the first order of business was to install CircuitPython 8. I started by going to the PyPortal CircuitPython Guide on Learn.Adafruit.

  1. Download the latest version of CircuitPython for the PyPortal Titano board by going to https://circuitpython.org/board/pyportal_titano/
  2. Download the UF2 file for CircuitPython 8.0.5
  3. Double click the reset button on the back of the Titano board and make certain the RGB LED turns green. If is is not green, try again.
  4. Copy the file to the PORTALBOOT drive that shows on your PC
    NOTE: Do not be concerned that the preinstalled demo no longer works. The library files are different for different versions.
  5. Download the CircuitPython 8 library files from https://circuitpython.org/libraries
    NOTE: This step is optional as the required libraries are in the GitHub project files
  6. Go to GitHub and download the project files from https://github.com/richteel/PyPortal_Events
  7. Delete the files on the PyPortal Titano
  8. Unzip the files and copy the files in the PyPortal folder to the PyPortal Titano
  9. The PyPortal Titano will restart and the images will change between “Connecting to the Internet” and “Failed to Connect”. The images will not take up the full screen due to the difference in resolution. (Until the code is modified.) The reason it is not connecting is we need add files to an SD Card and put that into the PyPortal Titano.
  10. Copy the files in the SD_Card folder, from GitHub, and paste them into the root of a micro SD Card.
  11. While the SD Card is still in you PC, double click on the index.html file to open the configuration utility.
  12. You may choose to load the config.json file on the card or start creating a new file from scratch by adding new events.
  13. Once you are satisfied with the events, click on the “Secrets” tab and enter your Wi-Fi settings, Timezone, and Adafruit IO Account information.
  14. Once done, click the “Save JSON File” button and save it to the SD Card as config.json.
  15. Remove the card from the PC and insert it into the PyPortal Titano.
  16. Click the reset button on the back of the PyPortal Titano.
  17. If everything was done correctly, you can anticipate that the events will be displayed on the screen
PyPortal Event Countdown running on the PyPortal Titano
The application is in the upper left corner of the screen with space to the right and bottom.

You may notice from the image of the PyPortal Titano screen, the temperature is not displayed as the PyPortal Titano does not have the ADT7410 Temperature Sensor.

The next step will be to see how to detect the screen size or make it a setting in the config.json file.

Categories
CircuitPython Microcontroller

PyPortal Event Countdown Clock Mods

I recently purchased an Adafruit PyPortal and looked at using John Park’s project PyPortal Event Countdown Clock project. It was fairly easy to get it up an running but switching from CircuitPython 4 to 8, proved to cause a bit of a challenge, not with the code, but with the libraries. Some were moved from one file to multiple files in one folder but eventually, I got it all sorted out.

I plan to use the PyPortal on an upcoming cruise, which lead me to some ideas of how to change the code to make it a bit more useful and easier to change events. Below is a list of some of the ideas to be implemented.

  • (Implemented) Allow for multiple events to be tracked
  • (Implemented) Use touch to change which event is being displayed
  • (Implemented) Add title and subtitle to the display
  • Load the events and event images from an SD Card
    • Use a JSON file
    • Create a webpage to easily modify the JSON
  • If possible, add the WiFi information to the config file
  • Add a clock option and easily switch between countdown and clock
  • Dim or turn off the backlight if the room is dark
  • Ignore events that have passed (Date is not today but in the past)

The first step was to add multiple events and add touch capability to allow moving back and forth through the events. Adding multiple events was not difficult. A new class files was added for event objects and a list was created to hold them. Next was to add touch and split the screen in half with a 20 pixel dead zone in the middle so that touching the left side would take you to the previous event and touching the right side would move to the next event. It was also necessary to add a variable to track the last index so we would know when to load the selected event.

Touch Zones for event change
Touch zones on PyPortal 320×240 screen

event.py

import time


class event:
    def __init__(self, title, subtitle, year, month, day, hour, minute, imageCountDown, imageEventDay, forecolor=0xF0C810):
        self.title = title
        self.subtitle = subtitle
        self.forecolor = forecolor
        self.year = year
        self.month = month
        self.day = day
        self.hour = hour
        self.minute = minute
        self.date = time.struct_time((year, month, day,
                                      hour, minute, 0,  # we don't track seconds
                                      -1, -1, False))  # we dont know day of week/year or DST
        self.imageCountDown = imageCountDown
        self.imageEventDay = imageEventDay

code.py

# SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
This example will figure out the current local time using the internet, and
then draw out a countdown clock until an event occurs!
Once the event is happening, a new graphic is shown
"""
import time
import board
import busio
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label
from analogio import AnalogIn
import adafruit_adt7410
import adafruit_touchscreen
from event import event

events = []

events.append(event("Day 1", "Barcelona, Spain",
              2023, 5, 29, 00, 00,
              "barcelona_background.bmp", "barcelona_event.bmp"))
events.append(event("Day 2", "Fun Day At Sea",
              2023, 5, 30, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 3", "Málaga, Spain",
              2023, 5, 31, 00, 00,
              "countdown_background.bmp", "countdown_event.bmp"))
events.append(event("Day 4", "Gibraltar (UK)",
              2023, 6, 1, 00, 00,
              "countdown_background.bmp", "countdown_event.bmp"))
events.append(event("Day 5", "Lisbon, Portugal",
              2023, 6, 2, 00, 00,
              "countdown_background.bmp", "countdown_event.bmp"))
events.append(event("Day 6", "Fun Day At Sea",
              2023, 6, 3, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 7", "Fun Day At Sea",
              2023, 6, 4, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 8", "Fun Day At Sea",
              2023, 6, 5, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 9", "Fun Day At Sea",
              2023, 6, 6, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 10", "Fun Day At Sea",
              2023, 6, 7, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 11", "Fun Day At Sea",
              2023, 6, 8, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 12", "Fun Day At Sea",
              2023, 6, 9, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 13", "Fun Day At Sea",
              2023, 6, 10, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 14", "Fun Day At Sea",
              2023, 6, 11, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 15", "Fun Day At Sea",
              2023, 6, 12, 00, 00,
              "funday_background.bmp", "funday_event.bmp"))
events.append(event("Day 16", "New York, New York",
              2023, 6, 13, 00, 00,
              "nyc_background.bmp", "nyc_event.bmp"))


# determine the current working directory
# needed so we know where to find files
cwd = ("/"+__file__).rsplit('/', 1)[0]
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/coming_soon.bmp")

big_font = bitmap_font.load_font(cwd+"/fonts/Helvetica-Bold-36.bdf")
big_font.load_glyphs(b'0123456789')  # pre-load glyphs for fast printing
title_font = bitmap_font.load_font(cwd+"/fonts/Arial-36.bdf")
subtitle_font = bitmap_font.load_font(cwd+"/fonts/Arial-20.bdf")

text_color = 0xFFFFFF
days_position = (big_font, 8, 207)
hours_position = (big_font, 110, 207)
minutes_position = (big_font, 220, 207)
title_position = (title_font, 8, 140)
subtitle_position = (subtitle_font, 8, 175)

text_areas = []
for pos in (days_position, hours_position, minutes_position, title_position, subtitle_position):
    textarea = Label(pos[0])
    textarea.x = pos[1]
    textarea.y = pos[2]
    textarea.color = text_color
    pyportal.splash.append(textarea)
    text_areas.append(textarea)

refresh_time = None

# Touchscreen setup
# ------Rotate 270:
screen_width = 240
screen_height = 320
ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR,
                                      board.TOUCH_YD, board.TOUCH_YU,
                                      calibration=(
                                          (5200, 59000), (5800, 57000)),
                                      size=(screen_width, screen_height))

# ------------- Inputs and Outputs Setup ------------- #
light_sensor = AnalogIn(board.LIGHT)
try:
    # attempt to init. the temperature sensor
    i2c_bus = busio.I2C(board.SCL, board.SDA)
    adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48)
    adt.high_resolution = True
except ValueError:
    # Did not find ADT7410. Probably running on Titano or Pynt
    adt = None

event_index = 0
last_event_index = -1

while True:
    touch = ts.touch_point
    light = light_sensor.value

    if touch:
        # print(f"Touched x={ts.touch_point[0]}, y={ts.touch_point[1]}")
        if touch[0] < 150:
            event_index = event_index - 1
            if event_index < 0:
                event_index = len(events) - 1
        elif touch[0] > 170:
            event_index = event_index + 1
            if event_index > len(events) - 1:
                event_index = 0

    if event_index != last_event_index:
        pyportal.set_background(cwd + "/" + events[event_index].imageCountDown)
        text_areas[3].color = events[event_index].forecolor
        text_areas[3].text = events[event_index].title
        text_areas[4].color = events[event_index].forecolor
        text_areas[4].text = events[event_index].subtitle
        last_event_index = event_index

    # only query the online time once per hour (and on first run)
    if (not refresh_time) or (time.monotonic() - refresh_time) > 3600:
        try:
            print("Getting time from internet!")
            pyportal.get_local_time(False)
            refresh_time = time.monotonic()
        except RuntimeError as e:
            print("Some error occured, retrying! -", e)
            continue

    now = time.localtime()
    print("Current time:", now)
    remaining = time.mktime(events[event_index].date) - time.mktime(now)
    print("Time remaining (s):", remaining)
    if remaining < 0:
        # oh, its event time!
        pyportal.set_background(cwd + "/" + events[event_index].imageEventDay)
        while True:  # that's all folks
            pass
    secs_remaining = remaining % 60
    remaining //= 60
    mins_remaining = remaining % 60
    remaining //= 60
    hours_remaining = remaining % 24
    remaining //= 24
    days_remaining = remaining
    print("%d days, %d hours, %d minutes and %s seconds" %
          (days_remaining, hours_remaining, mins_remaining, secs_remaining))
    text_areas[0].text = '{:>2}'.format(days_remaining)  # set days textarea
    text_areas[1].text = '{:>2}'.format(hours_remaining)  # set hours textarea
    text_areas[2].text = '{:>2}'.format(mins_remaining)  # set minutes textarea

    # update every 10 seconds
    # time.sleep(10)

Short Demo of implementing multiple events

Categories
Android Arduino Meshtastic Microcontroller Raspberry Pi Pico Uncategorized

Meshtastic Serial

I wanted to see about connecting a Raspberry Pi Pico to a LillyGo TTGO T-Beam v1.1 device. I noticed that Meshtastic supports serial communications, so I decided to give it a go to see how it worked.

There are several serial modes but the ones that seem the most useful are TXTMSG and PROTO. First attempt will be with the TXTMSG Mode as that seems straight forward. Once the TXTMSG Mode is working, I will look into how to use the PROTO Mode.

Wiring

We need to connect the grounds between the two devices, then connect the transmit (TX) from one to the receive (RX) of the other device. Below is a table showing the connections used in my setup.

T-BeamPico
RX pin 13TX pin 1 (GP0)
TX pin 14RX pin 2 (GP1)
GNDGND
T-Beam and Pico wiring
Wiring between T-Beam and Raspberry Pi Pico

Meshtastic Setup

Meshtastic firmware was installed using the Web Installer at https://flasher.meshtastic.org/. The T-Beam came with Meshtastic preinstalled. You may need to use another method to install the firmware if the Web Installer does not work.

Meshtastic Web Installer
Meshtastic Web Installer

T-Beam TEXTMSG Mode

Once Meshtastic has been installed on the T-Beam device and connected to the Android or Apple application, go to the Module Settings to setup the serial connection on the T-Beam device. The Module Settings is accessed by clicking on the kebab menu (aka three vertical dots menu) and selecting “Module Settings”.

kebab menu
Kebab Menu
Module Settings menu item
Module Settings menu item

Once the Module settings are displayed, scroll down to the “Serial Config” section and set the following items.

  • Serial enabled: turn on
  • RX: Set it to the T-Beam pin number for receive, which is 13 in my setup.
  • TX: Set it to the T-Beam pin number for transmit, which is 14 in my setup.
  • Serial baud rate: May leave it at the default setting or set it to “BAUD_38400”. I think it is best to set it as the default baud rate may change in other versions. I believe I read that it did change in the past.
  • Serial mode: Set it to TEXTMSG
  • Once everything is set, click the “Send” button.
Serial Configuration
Serial Configuration

Pico Arduino Code

The Pico code is written in C++ using the Arduino IDE. It is necessary to configure use the Pico Board provided by Earle F. Philhower, III. First, add the URL, https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json, to the Additional Boards Manager URLs by going to File > Preferences in the menu.

Arduino Preferences Menu Item
Arduino Preferences Menu Item
Arduino IDE Preferences
Arduino IDE Preferences

Click the icon to the left of the “Additional boards manager URLs” entry. Add the URL to the a new line in the textbox and click the “OK” button.

Additional Boards Manager URLs
Additional Boards Manager URLs

Open the boards manager by clicking on the boards manager icon, type “Pico” in the search textbox, and install the board, Raspberry Pi Pico/RP2040 by Earle F. Philhower, III.

Boards Manager
Boards Manager

Once the board is installed, you may select it from the boards dropdown selection in the IDE, when the Pico is connected to the PC.

Pico selected in the boards drop-down list
Raspberry Pi Pico selected in the boards drop-down list
/*
  Sample code to allow the Pico to act as a serial bridge between the PC and the Meshtastic device.

  Data sent to the Pico using the Arduino Serial Monitor, PuTTY, or other terminal software is sent
  to the Meshtastic device over the Pico UART0/Serial1 connection. Any data received from the Meshtastic
  device to the Pico is relayed to the PC over the Pico's serial over USB connection.

  REFERENCES:
    - https://meshtastic.org/docs/settings/moduleconfig/serial
    - https://github.com/earlephilhower/arduino-pico/discussions/210
*/

void setup() {
  // PC to Pico
  Serial.begin(9600);
  // Pico to Meshtastic device
  Serial1.begin(38400);
  while (!Serial)
    ;  // Serial is via USB; wait for enumeration
}

void loop() {
  // If data is received from the Meshtastic device, send it to the PC over the USB connection
  if (Serial1.available()) {
    String receiveMessage = Serial1.readString();
    Serial.print("Message received on Serial1 is:  ");
    Serial.println(receiveMessage);  // Send to serial monitor
  }

  // If data is received from the PC, send it to the Meshtastic Device
  while (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

Upload the code to the Raspberry Pi Pico. Once the code is loaded, open the serial monitor and type some text and hit enter. The message will be received on the other node(s).

Sending message from PC
Sending message from PC
Message received on other node
Message received on other node

Sending a message from another node, will be received and shown in the serial terminal.

Sending message from another node
Sending message from another node
Receiving message on PC
Receiving message on PC

Now the simple TEXTMSG is working, we can try to get the PROTO working. The PROTO mode is interesting as it may be possible to configure the Meshtastic device, and query it for additional information. I will look into the PROTO Mode in the near future.

Categories
Android Microcontroller

ATtiny85

I’m once again revisiting the ATtiny85 and wanted to see how to load sketches through USB in addition to the ICSP connection. I ran into quite a few stumbling blocks so I want to capture what I found in hopes that it will help others.

 

Categories
Arduino Microcontroller

Setting up ESP32 with Arduino IDE

I purchased a few things on eBay recently, including some ESP32s for $7.99 each from eBay seller, miniduino. I have not worked with the ESP32 but I know that it can work with the Arduino IDE and can run CircuitPython. I am familiar with the Arduino IDE so I wanted to get the ESP32 to work with the Arduino IDE so I can test them out and make certain that they work fine.

Doing a Google search on ESP32 and Arduino IDE returned many results which helped to get me going. The process for getting the ESP32 up and running is nearly the same as with the Teensy boards. The exception is that the Teensy boards have one nice executable to get things setup. The high-level steps to get ESP32 working with Arduino are the following.

  1. Install the latest Arduino IDE if you do not already have it installed. (https://www.arduino.cc/)
  2. Depending on your operating system, you may need to install the driver. I am running Windows 10 so I needed to install the driver for the Silicon Labs CP2102 from https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers.
    BTW: The boards that I purchased have no markings on the CP2102 chip. I fear that the chips are counterfeit or a lower grade chip. The first one I tested works so I’ll keep my fingers crossed.
  3. Once the driver was installed, I needed install the Arduino libraries for the ESP32 by cloning the GitHub repository at https://github.com/espressif/arduino-esp32.
    NOTE: A better way it to follow the “Installation instructions using Arduino IDE Boards Manager” instructions on the GitHub page.
  4. Program the ESP32 with the blink example.
    1. Load the blink example in the Arduino IDE and modify the example to use pin 2 for the led.
/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
 
  This example code is in the public domain.
 */
 
// Pin 13 has an LED connected on most Arduino boards.
// Pin 11 has the LED on Teensy 2.0
// Pin 6  has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
// give it a name:
int led = 2;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}
  1. Pick the “ESP32 Dev Module” from the “Boards” menu option
  2. Select the COM port for your board
  3. Upload the program to the ESP32 by clicking the upload button then press and hold the boot button on the ESP32 board. You may release the button once the upload starts.