Tag Archives: arduino

Music Cover Art Display using ILI9431

Little Sunday afternoon project.

Two PHP scripts.

Install on your webserver (see previous post)

Resizes images and removes the onkyo header.
(See previous posts)

<?php
// onkyo.php
// write jpeg header
header('Content-type: image/jpg');

$lines = file_get_contents('http://IP-ONKYO-AMPLIFIER/album_art.cgi', false);
$lines = explode("\n", $lines);
// remove weird Onkyo header (3 lines)
$content = implode("\n", array_slice($lines, 3));
print $content;
?>

CoverArt from a squeezeboxserver

<?php    
// squeezebox.php
// leave playerid as is, for the default.
// change to MAC address of player to get coverart specific player
$img = file_get_contents('http://IP-LOGITECH_MEDIA_SERVER:9000/music/current/cover.jpg?player=<playerid>');
$im = imagecreatefromstring($img);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = '240';
$newheight = '240';
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//imagejpeg($thumb,'small.jpg'); //save image as jpg
header('Content-Type: image/jpeg');
imagejpeg($thumb);
imagedestroy($thumb); 
imagedestroy($im);
?>

Arduino install:

Start IDE
Install TJpg_Decoder library
Open examples>Tjpeg_decoder>SPIFFS>SPIFFS_web_spiffs
change wifi credentials
and the url to your php script.
  bool loaded_ok = getFile("https://myserver/onkyo.php", "/M81.jpg"); // Note name preceded with "/"

replace bottom part with

 // while(1) yield();
 delay(5000);
     SPIFFS.remove("/M81.jpg");

Arduino Tiny Machine Learning Kit

A while ago I bought a little machine learning kit.

I’ve been reading at listening to ML podcasts and websites.

One on Spotify I liked was:

Also, the following Coursera was interesting
https://www.coursera.org/learn/machine-learning

I’ve been testing using Python on my Laptop.
(see other posts)

And a camera with esp32 using face detection.

See here multiple posts about these experiments.

https://www.henriaanstoot.nl/tag/machinelearning/

Today the first experiments using this kit.

  • Arduino Nano 33 BLE Sense board
  • OV7675 Camera
  • Arduino Tiny Machine Learning Shield
  • USB A to Micro USB Cable
  • 9 axis inertial sensor: what makes this board ideal for wearable devices
  • humidity, and temperature sensor: to get highly accurate measurements of the environmental conditions
  • barometric sensor: you could make a simple weather station
  • microphone: to capture and analyse sound in real time
  • gesture, proximity, light color and light intensity sensor : estimate the room’s luminosity, but also whether someone is moving close to the board
  • Microcontroller nRF52840
  • Operating Voltage 3.3V
  • Input Voltage (limit) 21V
  • DC Current per I/O Pin 15 mA
  • Clock Speed 64MHz
  • CPU Flash Memory 1MB (nRF52840)
  • SRAM 256KB (nRF52840)
  • EEPROM none
  • Digital Input / Output Pins 14
  • PWM Pins all digital pins
  • UART 1
  • SPI 1
  • I2C 1
  • Analog Input Pins 8 (ADC 12 bit 200 ksamples)
  • Analog Output Pins Only through PWM (no DAC)
  • External Interrupts all digital pins
  • LED_BUILTIN 13
  • USB Native in the nRF52840 Processor
  • IMU LSM9DS1 (datasheet)
Gesture test ( yes on a windows surface tablet, but Vincent and I installed linux on it!)

I just started and will update this page, with other experiments.

Note: displaying Arduino output without installing the IDE

stty -F /dev/ttyACM0 raw 9600
cat /dev/ttyACM0
................................
................................
................................
................................
................................
................................
................................
................................
................................
................####............
...............##..#............
..............##...##...........
..............#.....#...........
..............###...#...........
..............##.....#..........
..............##.....#..........
...............#....##..........
...............######...........
................................
................................
................................
................................

Started working on C64Pico with Bigred

A week ago I got the last components delivered to my doorstep.

This project was made by Silvervest and it’s f*ckin awesome.

https://github.com/silvervest/c64pico

I was afraid to start this myself, SMD is on another level for me.
But my good friend Marco said … No problem!

So I ordered components online, which was not easy.
Selecting the correct parts, sizes and options.

These things are really really small

Using tweezers to place the components was even difficult.
The slippery tiny bastard got catapulted everywhere. (Or got stuck on fingers, soldering iron and alike)
Many small components got lost into the 7th dimension. Never to be found again.

Awesome to work on this together, but Marco said that I have to try it myself.
Welllll, I got 3/4 of the ATmega328PB-A perfectly soldered, then I notished that it was crooked.
Desoldering was a mess, and I heated the PCB TOO much with the heatgun.

My messed-up PCB, and f*cked-up IC. Leave it to the professionals.

Next step for me is soldering the 75 mini buttons!

Got a Trinitron display from him, I was looking for this for a long time.

Revisiting the Spotify Cube

In the past I posted about my genre selector for Spotify using a cube.

Most was done using NodeRed and a python script.

Now, I’ve moved it to Home Assistant using a single automation.
(Maybe the Arduino sketch can be made with Esphome also.
But I don’t have time for that)
It still uses the Arduino sketch as before, which uses Mqtt to post the RFID code to Mosquitto.

My new Home Assistant automation

alias: SpotifyCube
description: ""
trigger:
  - platform: mqtt
    topic: spotify/rfid/id
condition:
  - condition: template
    value_template: "{{ trigger.payload in playlistkeys.keys() }}"
action:
  - service: media_player.play_media
    target:
      entity_id: media_player.spotify_fash
    data:
      media_content_type: playlist
      media_content_id: spotify:user:spotify:playlist:{{ playlistkeys.get(trigger.payload) }}
variables:
  playlistkeys:
    "70539770": 2KeRLMmGMxI5UgzE7m0iCx
    "70277626": 37i9dQZF1EQmK1rjZuPGDx
    "69229050": 0SOay3RkjojjevrF5lHMOx
    "70015482": 37i9dQZF1DX9HwI3Crikcx
    "69753338": 0bJvpsn0TDZwIDUjz4d75x
    "69491194": 5f8w3UHlD9Ozz6Y4VHs6kx

Some notes about above script:

  • The MQTT topic is configured in the sketch below
  • The playlist keys are at the bottom
    “RFIDID”: playliststring as can be found in web spotify

Pasted link

Arduino Code

#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>

#define SS_PIN 15
#define RST_PIN 0

MFRC522 mfrc522(SS_PIN, RST_PIN);
unsigned long cardId = 0;

WiFiClient net;
PubSubClient client(net);
const char* mqtt_server = "IPMQTTBROKER";
const char* ssid = "MYSSID";
const char* password = "MYWIFIPASSWORD";

void setup() {

  Serial.begin(115200);
  SPI.begin();
  mfrc522.PCD_Init();
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  client.setServer(mqtt_server, 1883);
     delay(100);
    client.setCallback(callback);
      delay(100);
    client.subscribe("spotify/rfid/in/#");
}

void reconnect() {
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  }

  while (!client.connected()) {
    String clientId = "NodeMCUClient-";
    clientId += String(random(0xffff), HEX);

    if (!client.connect(clientId.c_str(), "rfidclient", "...")) {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      delay(5000);
    }

  }
  client.subscribe("spotify/rfid/in/#");
}

void callback(char* topic, byte* payload, unsigned int length) {
    String topicStr = topic;
      byte value = atoi((char*)payload);
}

void loop() {
    if (!client.connected()) {
    reconnect();
  }
  client.loop();

  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  cardId = getCardId();
  char buffer[10];
  sprintf(buffer, "%lu", cardId);
  client.publish("spotify/rfid/id", buffer);

  uint8_t control = 0x00;
  do {
    control = 0;
    for (int i = 0; i < 3; i++) {
      if (!mfrc522.PICC_IsNewCardPresent()) {
        if (mfrc522.PICC_ReadCardSerial()) {
          control |= 0x16;
        }
        if (mfrc522.PICC_ReadCardSerial()) {
          control |= 0x16;
        }
        control += 0x1;
      }
      control += 0x4;
    }

    delay(0);
  } while (control == 13 || control == 14);

  reconnect();
  client.publish("spotify/rfid/id", "0");
  delay(500);

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

unsigned long getCardId() {
  byte readCard[4];
  for (int i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
  }

  return (unsigned long)readCard[0] << 24
    | (unsigned long)readCard[1] << 16
    | (unsigned long)readCard[2] << 8
    | (unsigned long)readCard[3];
}

Adding a VGA terminal to my 6502

Using a LilyGo TTGO ESP32 VGA32, I’m connecting my breadboard 6502 to a serial vga terminal with its own keyboard.

Due to a lot of moving around, new places, new homes I dumped a lot of terminal hardware.
Also are those old terminals too big and use too much power.

I’m going to use this DIY screen.
https://www.henriaanstoot.nl/2021/03/24/broken-or-slow-laptop-screen-still-works/

Using the Libraries from Fabrizio Di Vittorio, named FabGL, you can transform this device into a dumb terminal, game device, VIC-20, a 8086 pc and more.
There are even some projects to turn this into a C64.

But the main thing I want to do: A simple terminal.
(I probably revisit the other options again at a later stage)

My Wozmon bios has bare minimum support for serial communication, so i have to do some bitbanging.
(6502 is using a 6551 ACIA)

Sound from the ESP32 VGA board.

  • Chipset: TTGO Micro32 (ESP32 240Mhz dual core processor)
  • Flash memory: 4MB
  • SRAM: 520KB
  • Built-in Bluetooth
  • Built-in Wi-Fi
  • Supply voltage: 3.3V DC or 5V DC
  • GPIO voltage: 3.3V*
  • USB to serial converter: CP2102 or CH9102F (drivers)
  • VGA connection
  • PS/2: keyboard connection
  • PS/2: mouse connection
  • Built-in Li-ion/Li-Po battery charging circuit: TP4054 chip can charge up to 500mA

Three channel mixer for ay-3-8910 is almost done.

At the back the 8 pin single channel lm368 amplifier.
At the front the 3 channel setup.
I still have to tweak the resistors, and potmeters.
Then I can make a permanent PCB, and figure out the connections to the 6502.

At the moment, the Arduino Nano is playing some real sound samples by using the registers of the sound chip.
The music is being played by sending the register dumps directly to the chip.

Much like i’ve been using SID register dumps to play songs in another project.

This is version 0.1 .. do not use.
If its wrong, or can do better please mail me.
Oh it needs a 1k resistor from the 20K’s to ground I think.

Last week’s stuff

Update: https://www.henriaanstoot.nl/2024/01/14/hlk-ld2410b-with-a-wemos-mini-d1-v4-connected-to-home-assistant-using-esphome/

Case for presence detector

Update: BBQ watch

Not posted in the past, new version using ESPHOME and a m5stickc

Previous version using a ESP12
A “watch” with core and environment temperature of my smoker with a alarm, and button for timers.

ESP32 dac’s drawing on oscilloscope ( no additional components)

ESP32 in front of scope, two clips for x and y

For above i used sin/cos functions 2:3, which creates Lissajous figures.
See: https://www.henriaanstoot.nl/1992/01/01/oscilloscope-graphics-using-a-amiga-bonus-vectrex/

3 battery operated buttons (no wires needed) to control my shelly dimmer at the dinner table.

left button on, middle steps per 20% and 3rd button off.
(This cheapass button only sends ON commands)

Node red code

[
    {
        "id": "8190a851.8d02b8",
        "type": "mqtt in",
        "z": "44d7a4fb.e41a5c",
        "name": "domoticz-out",
        "topic": "domoticz/out",
        "qos": "0",
        "broker": "8c74c5f6.9a7a48",
        "inputs": 0,
        "x": 190,
        "y": 600,
        "wires": [
            [
                "543a2fa3.af27c",
                "c70d463.da52ab8",
                "ffa2f6be.afe618"
            ]
        ]
    },
    {
        "id": "543a2fa3.af27c",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2473)\n{\nmsg.payload = {};\nmsg.payload.turn = \"on\";\nmsg.payload.brightness = 50;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 600,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "c70d463.da52ab8",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2474)\n{\nmsg.payload = {};\nmsg.payload.turn = \"on\";\nvar count = context.get(\"counter\") || 0;\ncount = (count+1) % 6;\ncontext.set(\"counter\", count);\ncount = count * 20; \nmsg.payload.brightness = count;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 680,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "ffa2f6be.afe618",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2475)\n{\nmsg.payload = {};\nmsg.payload.turn = \"off\";\n//msg.payload.brightness = 0;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 760,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "35f35737.b4f2c8",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "Living Dinner Table Shelly 2024",
        "info": "",
        "x": 250,
        "y": 560,
        "wires": []
    },
    {
        "id": "b080c84e.2c3968",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt1 on / (butt2 off)",
        "info": "",
        "x": 510,
        "y": 560,
        "wires": []
    },
    {
        "id": "ac892b87.1c7358",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt3 toggle",
        "info": "",
        "x": 390,
        "y": 720,
        "wires": []
    },
    {
        "id": "b5bdbd65.c4e1c",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt 2 step dimmer",
        "info": "",
        "x": 410,
        "y": 640,
        "wires": []
    },
    {
        "id": "d7b0f308db912817",
        "type": "mqtt out",
        "z": "44d7a4fb.e41a5c",
        "name": "",
        "topic": "shellies/shellydimmer-D0DF15/light/0/set",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 860,
        "y": 600,
        "wires": []
    },
    {
        "id": "8c74c5f6.9a7a48",
        "type": "mqtt-broker",
        "name": "MQTTSERVER",
        "broker": "MQTTSERVER",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "closeTopic": "",
        "closePayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    }
]

Vector graphics on my demo arduino nano.

Adding a rotary encoder to Home Assistant to control dimmers using EspHome

Config for mqtt-433 and home assistant entities.
Maybe I’ll add a display to select which dimmer to change.

ESPHome Config for direct communication to a MQTT enabled 443mhz dimmer.

When using GND to the rotary you have to use a pullup entry in your yaml

esphome:
  name: rotarywhite
  friendly_name: RotaryWhite

esp8266:
  board: esp01_1m

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="

ota:
  password: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Rotarywhite Fallback Hotspot"
    password: "xxxxxxxxxxxxxxxxxxx"

captive_portal:
    
sensor:
  - platform: rotary_encoder
    name: "WhiteRotaryEncoder"
    id: rotvalue
    min_value: 0
    max_value: 50
    resolution: 1
    pin_a:
      number: GPIO0
      inverted: true
      mode:
        input: true
        pullup: true
    pin_b:
      number: GPIO2
      inverted: true
      mode:
        input: true
        pullup: true
    on_value:    
      - mqtt.publish:
          topic: "ha433/Living5Spots/brightcontrol"
          payload: !lambda |-
              return to_string(id(rotvalue).state);
mqtt:
  discovery: false
  broker: 192.168.1.1
  port: 1883
  discovery_prefix: homeassistant

Config part to change Home Assistant entities.
WARNING YOU HAVE TO CHANGE RIGHTS!

Settings > Addons > EspHome > Configuration
(press configure to change service calls)

sensor:
  - platform: rotary_encoder
    name: "WhiteRotaryEncoder"
    id: rotvalue
    min_value: 0
    max_value: 50
    resolution: 1
    pin_a:
      number: GPIO0
      inverted: true
      mode:
        input: true
        pullup: true
    pin_b:
      number: GPIO2
      inverted: true
      mode:
        input: true
        pullup: true
    on_value:    
      - homeassistant.service:
          service: light.turn_on
          data_template:
                entity_id: light.bedroomdimmer  
                brightness: "{{ brightness_1 | int }}"    
          variables:
              brightness_1: !lambda 'return id(rotvalue).state * 4;'

Home Assistant ESPHome with toggle for interval

Posted because I could not find a good example on the interwebs.

Below creates a virtual HA button which toggles a blinking led.
(button and variables are called eprint for another function, change to something meaningful. )

Home Assistant virtual mqtt switch (configuration.yml)

See switch part

mqtt:
 light:    
  - name: "KitchenOutside"
    payload_on: "99"
    payload_off: "0"
    unique_id: "KitchenOutside"
    brightness_scale: "99"
    brightness_state_topic: ha433/kitchenoutside/brightcontrol
    brightness_command_topic: ha433/kitchenoutside/brightcontrol
    state_topic: ha433/kitchenoutside/brightcontrol
    command_topic: ha433/kitchenoutside/control
    optimistic: false
    on_command_type: brightness
#-----8<-------------snip ########### EXAMPLES light and sensor
 sensor:
  - name: "LivingTemperature"
    state_topic: "home/8461/payload"
    unit_of_measurement: "°C"
    value_template: "{{ value_json.svalue1 }}"
  - name: "LivingHumidity"
    state_topic: "home/8461/payload"
    unit_of_measurement: "%"
    value_template: "{{ value_json.svalue2 }}"
#--------8<--- snip ################################ ONLY PART BELOW NEEDED 
 switch:
    unique_id: esphome_switch
    name: "Esp Home Switch"
    state_topic: "esphome/eprint/tmpstate"
    command_topic: "esphome/eprint/state"
    payload_on: "ON"
    payload_off: "OFF"
    state_on: "ON"
    state_off: "OFF"
    optimistic: false
    qos: 0
    retain: true

ESP Home config for a ESP32

esphome:
  name: lolin32litemqttled
  friendly_name: lolin32litemqttled

esp32:
  board: esp32dev
  framework:
    type: arduino

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="

ota:
  password: "xxxxxxxxxxxxxxxxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Lolin32Litemqttled"
    password: "xxxxxxxxxxxxxxxxxxx"

captive_portal:
    
switch:
  - platform: gpio
    pin:
      number: 22
      mode: output
    id: blueLED
  - platform: template
    name: "eprint"
    id: eprint_enable
    optimistic: on

interval:
  - interval: 1000ms
    then:
      if:
        condition:
          switch.is_on: eprint_enable
        then:
          - switch.toggle: blueLED

mqtt:
  broker: 192.168.1.2
  on_message:
  - topic: esphome/eprint/state
    qos: 0
    payload: "OFF"
    then:
      - switch.turn_off: eprint_enable
  - topic: esphome/eprint/state
    qos: 0
    payload: "ON"
    then:
      - switch.turn_off: eprint_enable

A “new” sound chip for 6502

UPDATE: 20240225

I’ve written about General Instrument AY-3-8910 before, here is some work I did today.

This sound chip i wanted to implement in my amiga, and now it’s a alternative for my 6502 computer. ( As an alternative setup for the SID chip. )
Btw this is the same kind of chip used in the Atari ST.

A clean setup … I’ve got the sound chip and a Amplifier chip.

Above a Kicad drawing I made today, a little different from my design from the 90’s.

Below a movie clip I recorded today. Running a test setup using an Arduino nano and a sdcard reader.
The sound is bad, this is due to clipping and the absence of multiple resistors and capacitors.
Music is a register dump from a YM music file.
Amplifier is a bare LM386.

UPDATE: 20240225

I don’t like tying those three outputs together, and amplifying those.

So I’m going to use a LM324 i’ve got left from my 8085 interface, and make a 3-channel amplifier.

Something like this