ESP32 Camera MicroPython IoT Device for Trading BOT Automation and Analysis

ESP32 Camera MicroPython IoT Device for Trading BOT Automation and Analysis

ESP32 Camera USB COM Connection, Putty Configuration and Running MicroPython Programme:

For Instructions Watch The Video Here:

Programmes Contained in the ESP32 Camera Board:

boot.py

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()

main.py

from machine import Pin
from neopixel import NeoPixel
import time

pin = Pin(48, Pin.OUT)
np = NeoPixel(pin, 1)
np[0] = (10,0,0)
np.write()
r, g, b = np[0]

print("RGB Demo")

while True:
    print("50%R")
    np[0] = (127, 0, 0)
    np.write()
    time.sleep_ms(1000)

    print("50%G")
    np[0] = (0, 127, 0)
    np.write()
    time.sleep_ms(1000)

    print("50%B")
    np[0] = (0, 0, 127)
    np.write()
    time.sleep_ms(1000)

Blinking RGB LED Output:

Open CMD and Type this to Erase Flash:

C:\Users\VIKASH\Desktop\arduino\esp32_camera> python -m esptool --port COM7 erase-flash

Download Firmware:

Download Firmware such as firmware.bin from this link as per ESP32 Camera Board: micropython-camera-API Releases

Open CMD and Type this to Write Flash and upload Firmware in ESP32 S3 Camera Board:

C:\Users\VIKASH\Desktop\arduino\esp32_camera> python -m esptool --port COM7 --baud 460800 write-flash -z 0x0 firmware.bin

For Instructions Watch The Video Here:

Camera Capture Python Programme:

import os, time, struct, gc
import micropython
from machine import Pin
from camera import Camera, PixelFormat, FrameSize

W, H = 320, 240
SWAP = False    # byte order: if colors are noisy/wrong, flip this to True
VFLIP = True    # flip image upside-down
HMIRROR = False # set True to mirror left/right

try:
    import neopixel
    led = neopixel.NeoPixel(Pin(48), 1)
except Exception:
    led = None

def flash(color, ms=300):
    if led:
        led[0] = color
        led.write()
        time.sleep_ms(ms)
        led[0] = (0, 0, 0)
        led.write()

def open_camera():
    # try a few clock speeds; some boards/sensors only work at one of them
    for xclk in (20000000, 30000000, 10000000):
        try:
            gc.collect()
            cam = Camera(
                data_pins=[11, 9, 8, 10, 12, 18, 17, 16],
                vsync_pin=6, href_pin=7, pclk_pin=13,
                xclk_pin=15, sda_pin=4, scl_pin=5,
                powerdown_pin=-1, reset_pin=-1,
                xclk_freq=xclk,
                pixel_format=PixelFormat.RGB565,
                frame_size=FrameSize.QVGA,
                fb_count=1,
            )
            print("Camera OK at", xclk // 1000000, "MHz")
            return cam
        except OSError as e:
            print("Failed at", xclk // 1000000, "MHz:", e)
    raise OSError("Camera would not start - check wiring/pins")

@micropython.viper
def convert(src: ptr8, dst: ptr8, n: int, swap: int):
    j = 0
    for i in range(0, n * 2, 2):
        if swap:
            v = (int(src[i + 1]) << 8) | int(src[i])
        else:
            v = (int(src[i]) << 8) | int(src[i + 1])
        b = v & 0x1F
        g = (v >> 5) & 0x3F
        r = (v >> 11) & 0x1F
        dst[j] = (b << 3) | (b >> 2)
        dst[j + 1] = (g << 2) | (g >> 4)
        dst[j + 2] = (r << 3) | (r >> 2)
        j += 3

def next_name():
    files = os.listdir()
    n = 1
    while "selfie_%d.bmp" % n in files:
        n += 1
    return "selfie_%d.bmp" % n

def save_bmp(buf, path):
    out = bytearray(W * H * 3)
    convert(buf, out, W * H, 1 if SWAP else 0)
    header = struct.pack('<2sIHHI', b'BM', 54 + len(out), 0, 0, 54)
    header += struct.pack('<IiiHHIIiiII', 40, W, -H, 1, 24, 0, len(out), 2835, 2835, 0, 0)
    with open(path, "wb") as f:
        f.write(header)
        f.write(out)

cam = open_camera()
cam.set_vflip(1 if VFLIP else 0)
cam.set_hmirror(1 if HMIRROR else 0)

try:
    flash((40, 40, 0), 200)          # yellow blink = get ready
    for _ in range(15):              # let auto-exposure settle
        cam.capture()
        time.sleep_ms(100)
    cam.capture()                    # throw away a stale frame
    buf = cam.capture()
    name = next_name()
    save_bmp(buf, name)
    print("Saved", name)
    flash((0, 40, 0))                # green blink = saved
finally:
    cam.deinit()

Raspberry Pi Pico MicroPython IoT Device for Trading BOT Automation and Analysis

Raspberry Pi Pico MicroPython IoT Device Microcontroller Fix Broken BOOTSEL Issues:


It has dedicated test point pads (TP1–TP6) right in the middle of the board (you can see them in photo, between the two rows of pins, above where GP0/GP1 are labeled). One of those, TP6, is literally the BOOTSEL signal, and one of the others (TP1) is GND — exactly what the button normally shorts together.
Steps:
Unplug the USB cable from the Pico for a moment
Take one of your jumper wires (or just touch the two pads with a single wire/tweezers) and bridge TP6 to a GND pad
Looking at photo, TP6 is the topmost of that middle block of small square pads, and TP1 (or any of the GND-labeled pads nearby, e.g. "GND" next to GP1) works as ground
While holding that short, plug the USB cable into your laptop
Keep holding the bridge for about 2 seconds after plugging in, then release
The Pico should now show up on your computer as a USB drive called RPI-RP2
Tips:
Make sure you're bridging TP6 to GND(TP1), not accidentally two GPIO pads — a wrong short won't hurt anything (these are just logic-level pins) but won't trigger bootloader either
If it doesn't enumerate, try again — timing matters a little (some people find it easier to hold the short first, then plug in USB while still touching)
Once it's in RPI-RP2 mode, drag your .uf2 firmware file onto it like normal

OS is detecting the Pico as a USB mass storage device and setting it up
The bootloader shorting worked
What to do now:
Wait a few seconds for it to finish setting up
Open File Explorer (Windows) or Finder (Mac) — you should see a new drive appear named RPI-RP2
If it appears, you're in bootloader mode. Now you just need to flash firmware:
Download a .uf2 file — either:
MicroPython: https://micropython.org/download/RPI_PICO/ (or RPI_PICO2 if this is a Pico 2)
Or whatever firmware/project you were trying to flash originally
Drag and drop the .uf2 file onto the RPI-RP2 drive
The Pico will automatically reboot and run the new firmware once the copy finishes (the drive will disappear — that's normal)

Raspberry Pi Pico - MicroPython - Simulated Candlestick Data Generator:


For Instructions Watch The Video Here:


Upload the Below Code to Arduino Mega through Arduino IDE:


// Arduino Mega - MCUFRIEND TFT Candlestick Chart Display
// -------------------------------------------------------
// Receives simulated candle data from a Raspberry Pi Pico over
// hardware UART (Serial1: TX1=pin18, RX1=pin19) and draws a real,
// scrolling candlestick chart (wicks + coloured bodies), instead of
// just printing text like the original sketch.
//
// Expected line format from the Pico, one per finished candle:
//   SYMBOL,OPEN,HIGH,LOW,CLOSE\n
// e.g.
//   SIM,100.23,101.10,99.87,100.75\n

#include 
#include 
MCUFRIEND_kbv tft;

#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
#define LCD_RESET A4

#define BLACK 0x0000
#define WHITE 0xFFFF
#define RED   0xF800
#define GREEN 0x07E0
#define GRAY  0x8410

const int CHART_X = 10;
const int CHART_Y = 40;
const int CHART_W = 300;     // adjust to fit your TFT's resolution
const int CHART_H = 200;
const int CANDLE_W = 8;      // pixel width allotted per candle
const int MAX_CANDLES = CHART_W / CANDLE_W;

struct Candle { float o, h, l, c; };
Candle candles[MAX_CANDLES];
int candleCount = 0;

float chartMin = 0, chartMax = 100;

void setup() {
  Serial.begin(9600);    // USB - optional, for debugging via laptop
  Serial1.begin(9600);   // pins 18(TX1)/19(RX1) - talks to the Pico

  uint16_t ID = tft.readID();
  if (ID == 0xD3D3) ID = 0x9481;
  tft.begin(ID);

  tft.setRotation(1);
  tft.fillScreen(BLACK);
  tft.setTextColor(WHITE, BLACK);
  tft.setTextSize(2);
  tft.setCursor(0, 0);
  tft.println("Waiting for candles...");
}

void loop() {
  if (Serial1.available()) {
    String msg = Serial1.readStringUntil('\n');
    msg.trim();
    if (msg.length() > 0 && addCandle(msg)) {
      drawChart();
      Serial.println("OK: " + msg);   // debug echo to laptop, if connected
    }
  }
}

bool addCandle(String msg) {
  int p1 = msg.indexOf(',');
  int p2 = msg.indexOf(',', p1 + 1);
  int p3 = msg.indexOf(',', p2 + 1);
  int p4 = msg.indexOf(',', p3 + 1);
  if (p1 < 0 || p2 < 0 || p3 < 0 || p4 < 0) return false;

  float o = msg.substring(p1 + 1, p2).toFloat();
  float h = msg.substring(p2 + 1, p3).toFloat();
  float l = msg.substring(p3 + 1, p4).toFloat();
  float c = msg.substring(p4 + 1).toFloat();

  if (candleCount < MAX_CANDLES) {
    candles[candleCount++] = { o, h, l, c };
  } else {
    // full - scroll left, drop the oldest candle
    for (int i = 1; i < MAX_CANDLES; i++) candles[i - 1] = candles[i];
    candles[MAX_CANDLES - 1] = { o, h, l, c };
  }

  // rescale the chart to fit everything currently on screen
  chartMin = candles[0].l;
  chartMax = candles[0].h;
  for (int i = 0; i < candleCount; i++) {
    if (candles[i].l < chartMin) chartMin = candles[i].l;
    if (candles[i].h > chartMax) chartMax = candles[i].h;
  }
  float pad = (chartMax - chartMin) * 0.1;
  if (pad < 0.01) pad = 1;
  chartMin -= pad;
  chartMax += pad;

  return true;
}

int priceToY(float price) {
  float ratio = (price - chartMin) / (chartMax - chartMin);
  return CHART_Y + CHART_H - (int)(ratio * CHART_H);
}

void drawChart() {
  // header
  tft.fillRect(0, 0, tft.width(), CHART_Y - 5, BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(WHITE, BLACK);
  tft.setTextSize(2);
  tft.print("Candles: ");
  tft.println(candleCount);

  // chart background + border
  tft.fillRect(CHART_X, CHART_Y, CHART_W, CHART_H, BLACK);
  tft.drawRect(CHART_X, CHART_Y, CHART_W, CHART_H, GRAY);

  for (int i = 0; i < candleCount; i++) {
    int x = CHART_X + i * CANDLE_W + CANDLE_W / 2;
    Candle &cd = candles[i];
    bool bullish = cd.c >= cd.o;
    uint16_t color = bullish ? GREEN : RED;

    int yHigh  = priceToY(cd.h);
    int yLow   = priceToY(cd.l);
    int yOpen  = priceToY(cd.o);
    int yClose = priceToY(cd.c);

    // wick
    tft.drawLine(x, yHigh, x, yLow, color);

    // body
    int bodyTop = min(yOpen, yClose);
    int bodyBot = max(yOpen, yClose);
    if (bodyBot == bodyTop) bodyBot = bodyTop + 1;  // keep doji visible
    tft.fillRect(x - CANDLE_W / 2 + 1, bodyTop, CANDLE_W - 2, bodyBot - bodyTop, color);
  }
}


Run the Below Code from Pico through Thonny IDE:


"""
Raspberry Pi Pico - MicroPython - Simulated Candlestick Data Generator
-----------------------------------------------------------------------
No Wi-Fi, no price feed - this purely SIMULATES a random-walk OHLC
candle every few seconds and streams it over UART to an Arduino Mega
running arduino_mega_candlestick_tft.ino, which draws an actual
scrolling candlestick chart on its TFT shield.

WIRING:
    Pico GP0 (UART0 TX) -> Arduino Mega RX1 (pin 19)
    Pico GP1 (UART0 RX) -> Arduino Mega TX1 (pin 18)   (optional, only
                                                         needed for ACKs)
    Pico GND            -> Arduino Mega GND            (required)

    NOTE: Arduino Mega logic is 5V, Pico GPIO is 3.3V-only. Put a
    voltage divider or logic-level shifter on the Mega TX1 -> Pico
    RX (GP1) line if you wire that direction too.

PROTOCOL (one line per finished candle):
    SYMBOL,OPEN,HIGH,LOW,CLOSE\n
e.g.
    SIM,100.23,101.10,99.87,100.75\n
"""

from machine import UART, Pin
import time

try:
    import urandom as random
except ImportError:
    import random


def rand_float(a, b):
    return a + (b - a) * (random.getrandbits(16) / 65535)


uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))

SYMBOL = "SIM"
price = 100.0        # starting price
TICKS_PER_CANDLE = 8  # intra-candle random steps (shapes the wick/body)
STEP_RANGE = 0.6       # max +/- move per tick
CANDLE_SECONDS = 3     # how often a new candle is emitted


while True:
    open_p = price
    high_p = open_p
    low_p = open_p
    close_p = open_p

    for _ in range(TICKS_PER_CANDLE):
        close_p += rand_float(-STEP_RANGE, STEP_RANGE)
        high_p = max(high_p, close_p)
        low_p = min(low_p, close_p)

    price = close_p  # next candle opens where this one closed

    line = "{},{:.2f},{:.2f},{:.2f},{:.2f}\n".format(
        SYMBOL, open_p, high_p, low_p, close_p
    )
    uart.write(line)
    print("Sent:", line.strip())  # optional debug, goes out over USB REPL

    time.sleep(CANDLE_SECONDS)


Raspberry Pi Pico MicroPython IoT Device Microcontroller:


For Instructions Watch The Video Here:



from machine import Pin
import time

led = Pin(25, Pin.OUT)

while True:
    led.on()
    time.sleep(1)
    led.off()
    time.sleep(1)

MicroPython Pico Driving an Arduino Mega TFT Shield:


For Instructions Watch The Video Here:


Upload the Below Code to Arduino Mega through Arduino IDE:


#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
#define LCD_RESET A4

#include 
#include 
MCUFRIEND_kbv tft;

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

void setup(void) {
    Serial.begin(9600);     // USB - keep for debugging via laptop if connected
    Serial1.begin(9600);    // <-- pins 18(TX1)/19(RX1), talks to Pico

    uint16_t ID = tft.readID();
    if (ID == 0xD3D3) ID = 0x9481;
    tft.begin(ID);

    tft.setRotation(0);
    tft.fillScreen(BLACK);
    tft.setTextColor(WHITE, BLACK);
    tft.setTextSize(2);
    tft.setCursor(0, 0);
    tft.println("Waiting for Pico...");
}

void loop(void) {
    if (Serial1.available()) {           // <-- changed from Serial
        String msg = Serial1.readStringUntil('\n');
        msg.trim();

        tft.fillScreen(BLACK);
        tft.setCursor(0, 0);
        tft.setTextColor(WHITE, BLACK);
        tft.setTextSize(2);
        tft.println(msg);

        Serial.println("OK: " + msg);    // this still goes to laptop if USB connected, for debugging
    }
}1)


Run the Below Code from Pico through Thonny IDE:


from machine import UART, Pin
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
uart.write('Hello from Pico\n')