# ALIN-TECH MACROPAD

**Programmable Macro Pad for Windows — USB HID / BLE**

[English](#english) | [Português](#português)

---

# English

## Overview

**ALIN-TECH MACROPAD** is a programmable and customizable macro pad for Windows.

The project is built around two separate layers:

1. **Hardware / firmware**
   - Reads the physical buttons.
   - Identifies the logical button number.
   - Sends button events to Windows through the supported communication interface.

2. **Windows application**
   - Detects the MACROPAD.
   - Receives the button events.
   - Loads the user configuration.
   - Executes the configured action.
   - Applies the active BASIC or PRO software license.

The hardware platform and the software license tier are independent.

---

## Important: Hardware Is Not BASIC or PRO

The microcontroller does **not** define whether the product is BASIC or PRO.

**BASIC and PRO are software license tiers inside the Windows application.**

The same ALIN-TECH MACROPAD Windows executable is used with the supported hardware targets.

This means:

- **RP2040-Zero can be used with BASIC or PRO.**
- **XIAO ESP32S3 can be used with BASIC or PRO.**
- Changing from BASIC to PRO does not require replacing the microcontroller.
- Changing from BASIC to PRO does not require installing a different Windows executable.
- Firmware must be selected by **hardware target**, not by software license tier.

```text
                    ALIN-TECH MACROPAD.exe
                             │
                    ┌────────┴────────┐
                    │                 │
                  BASIC              PRO
            software features   software features
                    │                 │
                    └────────┬────────┘
                             │
               same hardware compatibility
                             │
          ┌──────────────────┴──────────────────┐
          │                                     │
          ↓                                     ↓
    RP2040-Zero                         XIAO ESP32S3
```

---

## Software License Tiers

### BASIC

BASIC provides the core ALIN-TECH MACROPAD software functionality.

### PRO

PRO unlocks additional software features inside the same Windows application.

The license tier is handled by the Windows application and licensing system.

It is **not** encoded as a hardware model.

It is **not** determined by the microcontroller.

---

## Current Hardware Targets

Firmware is organized by microcontroller / hardware target. Each supported target uses one firmware file for both 6-button and 9-button operation.

| Hardware target  | 6 buttons | 9 buttons | USB HID | BLE HID | Windows BASIC | Windows PRO |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| **RP2040-Zero**  | Yes       | Yes       | Yes     | No      | Yes           | Yes         |
| **XIAO ESP32S3** | Yes       | Yes       | Yes     | Yes     | Yes           | Yes         |

---

## Firmware Organization

Firmware downloads are organized by hardware target only.

There is **one firmware file per supported microcontroller target**:

```text
Firmware/
│
├── RP2040-Zero/
│   └── ALIN-TECH_RP2040-Zero.uf2
│
└── XIAO-ESP32S3/
    └── ALIN-TECH_XIAO-ESP32S3.bin
```

There are **not separate 6-key and 9-key firmware files**.

The firmware reports the full 9-button logical layout. When the Windows application is configured for a 6-button MACROPAD, it only uses logical Buttons 1–6 and ignores Buttons 7–9.

```text
9-button firmware
      ↓
Buttons 1–9 available
      ↓
ALIN-TECH MACROPAD.exe
      ↓
6-button mode  → uses Buttons 1–6 only
9-button mode  → uses Buttons 1–9
```

This means the same `.uf2` or `.bin` firmware can be used for both the 6-button and 9-button MACROPAD layouts.

Do **not** create separate firmware for BASIC and PRO.

Do **not** create separate firmware for 6-key and 9-key layouts.

The BASIC / PRO difference is handled only by the Windows application and license.

---

## Main Features

- Programmable physical buttons
- 6-button and 9-button layouts
- Application launching
- Application control
- Application icons
- Windows keyboard shortcuts
- ALT keyboard shortcuts
- CTRL keyboard shortcuts
- Windows Key shortcuts
- Custom macros
- Link / website launching
- Folder opening
- Microphone and audio controls
- Per-application controls
- OBS controls
- Profile switching
- Multi Action support
- Mouse controls
- Custom command execution
- Screenshot and screen recording controls
- USB HID support where supported
- BLE HID support where supported
- Multiple supported hardware targets
- Persistent configuration
- Save configuration
- Reset configuration
- Customizable interface
- Customizable themes
- Windows system tray operation
- Expandable architecture

---

## How It Works

The hardware detects which physical button was pressed and sends a logical button identifier to Windows.

The Windows application receives the identifier and executes the action configured for that button.

```text
Physical Button
      ↓
MACROPAD Hardware
      ↓
Microcontroller
      ↓
USB HID / BLE HID
      ↓
Windows
      ↓
ALIN-TECH MACROPAD.exe
      ↓
BASIC / PRO license layer
      ↓
Configured Action
```

The microcontroller does not need to know:

- Which application should be opened
- Where the application is installed
- Which keyboard shortcut is assigned
- Which macro should be executed
- Which Windows command should run
- Whether the Windows license is BASIC or PRO

Those responsibilities belong to the Windows application.

---

# Hardware

## Hardware Responsibilities

The hardware is responsible for:

- Reading physical buttons
- Debouncing button input
- Identifying logical button numbers
- Managing the supported communication interfaces
- Providing USB HID when supported
- Providing BLE HID when supported
- Managing power
- Managing battery operation where supported
- Reporting battery information where supported

---

## Button Configurations

### 6-Button Layout

```text
┌─────────┬─────────┬─────────┐
│ Button 1│ Button 2│ Button 3│
├─────────┼─────────┼─────────┤
│ Button 4│ Button 5│ Button 6│
└─────────┴─────────┴─────────┘
```

### 9-Button Layout

```text
┌─────────┬─────────┬─────────┐
│ Button 1│ Button 2│ Button 3│
├─────────┼─────────┼─────────┤
│ Button 4│ Button 5│ Button 6│
├─────────┼─────────┼─────────┤
│ Button 7│ Button 8│ Button 9│
└─────────┴─────────┴─────────┘
```

The 9-button layout extends the 6-button layout by adding Buttons 7–9.

---

## Logical Button Numbering

The logical button numbering remains consistent across hardware targets:

```text
Button 1
Button 2
Button 3
Button 4
Button 5
Button 6
Button 7
Button 8
Button 9
```

Only the physical GPIO changes between microcontroller implementations.

---

# RP2040-Zero

## Communication

**USB HID**

**USB identity:**

```text
ALIN-TECH_USB-MACROPAD
```

The RP2040-Zero is a supported hardware target for the same ALIN-TECH MACROPAD Windows application.

It uses a single `.uf2` firmware file for both 6-button and 9-button layouts. In 6-button mode, the Windows application only reads logical Buttons 1–6.

It can be used with either a BASIC or PRO software license.

### Button Wiring / Pull-Down

The RP2040-Zero firmware uses the GPIO inputs with an **internal pull-down**.

Each button must connect its assigned GPIO to **3.3V when pressed**:

```text
3.3V ── Button ── GPIO
                  │
                  └── Internal Pull-Down ── GND
```

Firmware input mode:

```text
INPUT_PULLDOWN
```

Button state:

```text
LOW  = Button released
HIGH = Button pressed
```

The button should use **3.3V logic**, not 5V.

### 6 Buttons

| Button | GPIO |
|---|---:|
| Button 1 | GP0 |
| Button 2 | GP1 |
| Button 3 | GP2 |
| Button 4 | GP3 |
| Button 5 | GP4 |
| Button 6 | GP5 |

### 9 Buttons

| Button | GPIO |
|---|---:|
| Button 1 | GP0 |
| Button 2 | GP1 |
| Button 3 | GP2 |
| Button 4 | GP3 |
| Button 5 | GP4 |
| Button 6 | GP5 |
| Button 7 | GP6 |
| Button 8 | GP7 |
| Button 9 | GP8 |

---

# XIAO ESP32S3

## Communication

**USB HID + BLE HID (Bluetooth Low Energy)**

**USB identity:**

```text
ALIN-TECH_USB-MACROPAD
```

**BLE identity:**

```text
ALIN-TECH_BLE-MACROPAD
```

The XIAO ESP32S3 is a supported hardware target for the same ALIN-TECH MACROPAD Windows application.

It uses a single `.bin` firmware file for both 6-button and 9-button layouts. In 6-button mode, the Windows application only reads logical Buttons 1–6.

It can be used with either a BASIC or PRO software license.

### Button Wiring / Pull-Down

The XIAO ESP32S3 firmware uses the GPIO inputs with an **internal pull-down**.

Each button must connect its assigned GPIO to **3.3V when pressed**:

```text
3.3V ── Button ── GPIO
                  │
                  └── Internal Pull-Down ── GND
```

Firmware input mode:

```text
INPUT_PULLDOWN
```

Button state:

```text
LOW  = Button released
HIGH = Button pressed
```

The button should use **3.3V logic**, not 5V.

---

## Battery Monitoring

Battery monitoring input:

```text
D8
```

Voltage divider:

- 220 kΩ from BAT+ → D8
- 100 kΩ from BAT− → D8
- D8 is used as the battery-voltage ADC input.

### Charger / 5VIN Detection

The XIAO ESP32S3 uses **D10** to detect the presence of the charger / 5VIN supply.

The detection circuit uses a **100 kΩ / 100 kΩ voltage divider**:

```text
5VIN ── 100 kΩ ── D10 ── 100 kΩ ── GND
```

- 100 kΩ from **5VIN → D10**
- 100 kΩ from **D10 → GND**
- **D10** is used by the firmware to detect whether 5VIN / charger power is present.

With 5 V at 5VIN, the divider provides approximately **2.5 V at D10**.

---

## 6 Buttons

| Button | GPIO |
|---|---:|
| Button 1 | GPIO 0 |
| Button 2 | GPIO 1 |
| Button 3 | GPIO 2 |
| Button 4 | GPIO 3 |
| Button 5 | GPIO 4 |
| Button 6 | GPIO 5 |

## 9 Buttons

| Button | GPIO |
|---|---:|
| Button 1 | GPIO 0 |
| Button 2 | GPIO 1 |
| Button 3 | GPIO 2 |
| Button 4 | GPIO 3 |
| Button 5 | GPIO 4 |
| Button 6 | GPIO 5 |
| Button 7 | GPIO 6 |
| Button 8 | GPIO 7 |
| Button 9 | GPIO 9 |

---

# Recommended Button Wiring

A simple button can be wired as:

```text
3.3V
 │
 └──── Switch ──── GPIO
                    │
                    └──── Internal Pull-Down
```

Firmware input mode:

```text
INPUT_PULLDOWN
```

Button state:

```text
LOW  = Not pressed
HIGH = Pressed
```

The exact electrical implementation can vary between hardware revisions.

---

# Button Debouncing

Mechanical switches can produce multiple electrical transitions during one physical press.

The firmware should debounce the physical button input before sending the logical event.

```text
Button Press
     ↓
Detect Transition
     ↓
Debounce / Validate
     ↓
Confirm Button
     ↓
Send Logical Button Event
```

---

# HID Communication

The logical button protocol is independent of the physical GPIO.

For six buttons:

```text
1
2
3
4
5
6
```

For nine buttons:

```text
1
2
3
4
5
6
7
8
9
```

Example:

```text
Physical GPIO
      ↓
Logical Button Number
      ↓
HID Report
      ↓
Windows
      ↓
ALIN-TECH MACROPAD.exe
```

The Windows application only needs the logical button number.

---

# USB and BLE

## RP2040-Zero

- Native USB
- USB HID
- No integrated Bluetooth

## XIAO ESP32S3

- Native USB
- USB HID
- Bluetooth Low Energy
- BLE HID


---

# BLE / USB Priority

On hardware that supports both BLE and USB HID, connection handling can follow this logic:

```text
USB disconnected
      ↓
BLE active
      ↓
Wireless operation


USB connected for charging / power only
      ↓
BLE remains active
      ↓
Wireless operation while charging


USB connected to a computer as HID
      ↓
USB HID active
      ↓
BLE control disabled
      ↓
Wired operation
```

---

# Battery

Battery support is hardware dependent.

Supported implementations may include:

- LiPo battery
- JST connector
- Battery charging
- Battery voltage monitoring
- Battery percentage reporting
- Low-power operation

The Windows application can display battery information when the hardware and communication protocol provide it.

---

# Windows Application

The Windows application is the main configuration and action layer.

A single ALIN-TECH MACROPAD application is used across the supported microcontroller targets.

The application is responsible for:

- Detecting the device
- Receiving HID reports
- Identifying logical button numbers
- Loading configuration
- Executing configured actions
- Launching applications
- Executing keyboard shortcuts
- Executing macros
- Displaying icons
- Managing themes
- Saving configuration
- Resetting configuration
- Managing system tray operation
- Applying the BASIC or PRO software license
- Enabling or disabling software features according to the active license

---

# BASIC / PRO Software Model

```text
Supported Hardware
      ↓
ALIN-TECH MACROPAD.exe
      ↓
License Validation
      ↓
┌───────────────┬───────────────┐
│               │               │
BASIC           PRO
│               │
Core features   Core + additional PRO features
```

The same hardware can continue to be used if the software license changes.

No hardware replacement is required to move between BASIC and PRO.

---

# Application Launching

The hardware does not store application paths.

```text
Button
   ↓
Microcontroller
   ↓
Logical Button ID
   ↓
Windows Application
   ↓
Configuration
   ↓
Configured Application / Action
```

Changing an application assigned to a button does not require changing the microcontroller firmware.

---

# Configuration File

The Windows application stores its configuration in:

```text
%APPDATA%\ALIN-TECH MACROPAD\config.json
```

Typical location:

```text
C:\Users\<Username>\AppData\Roaming\ALIN-TECH MACROPAD\config.json
```

The configuration can contain:

- Button assignments
- Application paths
- Application icons
- Macro definitions
- Theme settings
- Other application preferences

---

# Save and Reset

## Save

Stores the current configuration.

## Reset

Restores the default configuration.

---

# System Tray

When the main window is closed using the **X**, the application can remain running in the Windows system tray.

```text
Main Window
     ↓
Close
     ↓
Application remains active
     ↓
Windows System Tray
     ↓
MACROPAD continues working
```

---

# User Interface

The Windows application provides a visual representation of the physical MACROPAD.

The visual interface can support the available button layouts and hardware communication states.

---

# Themes

The application supports customizable theme colors.

Default accent example:

```text
#00AFFF
```

Theme settings can affect:

- Main interface
- Macro buttons
- Highlights
- Borders
- Background elements
- Accent elements

---

# Hardware Independence

The application architecture is intentionally independent from the microcontroller choice.

```text
                 RP2040-Zero
                     │
                     │ USB HID
                     ↓
                ┌───────────┐
                │           │
                │  Windows  │
                │           │
                └─────┬─────┘
                      │
             ALIN-TECH MACROPAD.exe
                      │
                 BASIC / PRO


                XIAO ESP32S3
                     │
                USB HID / BLE
                     ↓
                  Windows
                     ↓
             same application
                     ↓
                 BASIC / PRO
```

---

# Firmware Responsibilities

The firmware is responsible for:

1. Initializing GPIOs
2. Reading buttons
3. Debouncing switches
4. Detecting button presses
5. Mapping GPIOs to logical button numbers
6. Sending HID events
7. Managing BLE where supported
8. Managing USB where supported
9. Managing power
10. Providing battery information where supported

The firmware is **not** responsible for deciding whether the Windows application is BASIC or PRO.

---

# Windows Application Responsibilities

The Windows application is responsible for:

1. Detecting the device
2. Receiving button events
3. Identifying logical button numbers
4. Loading the user configuration
5. Executing configured actions
6. Launching applications
7. Executing keyboard macros
8. Displaying icons
9. Managing themes
10. Saving configuration
11. Resetting configuration
12. Managing system tray operation
13. Managing the BASIC / PRO software license
14. Enabling licensed software features

---

# Installation

Install the **ALIN-TECH MACROPAD** Windows application.

There is one Windows application for the supported hardware targets.

The installer should not present RP2040-Zero as BASIC hardware or XIAO ESP32S3 as PRO hardware.

Hardware selection and software licensing are separate concepts.

After installation:

1. Install the single firmware file for the selected microcontroller. The same firmware works with both 6-button and 9-button layouts.
2. Connect the MACROPAD.
3. Start ALIN-TECH MACROPAD.
4. Wait for the device to be detected.
5. Activate or validate the BASIC / PRO software license when required.
6. Configure the buttons.
7. Save the configuration.
8. Use the MACROPAD normally.

---

# Troubleshooting

## Device is not detected

Check:

- The MACROPAD is powered.
- The USB cable supports data when using USB.
- Bluetooth is enabled when using BLE.
- The selected firmware matches the microcontroller.
- Windows detects the required HID interface.
- The ALIN-TECH MACROPAD application is running.

## BLE is not detected

Check:

- Bluetooth is enabled.
- The hardware supports BLE.
- BLE firmware is running.
- The device is advertising correctly.
- Windows Bluetooth is working.

## USB is not detected

Check:

- The USB cable supports data.
- The board is powered.
- The hardware supports USB HID.
- Windows detects the device.
- The firmware is running correctly.

## A button does not work

Check:

- The switch is electrically connected.
- The GPIO number is correct.
- The GPIO is not reserved by another peripheral.
- The button mapping is correct.
- Pull-down configuration is correct.
- Debouncing is working.
- The HID report contains the correct logical button number.

## The wrong action is executed

Check:

```text
Physical GPIO
      ↓
Firmware Button Number
      ↓
HID Report
      ↓
Windows Button Number
      ↓
Configured Action
```

The logical button number must remain consistent across the entire system.

---

# Development Structure

```text
ALIN-TECH MACROPAD
│
├── Firmware
│   ├── RP2040-Zero
│   └── XIAO ESP32S3
│
├── Windows Application
│   ├── BASIC
│   └── PRO
│
├── Hardware
│   ├── 6 Buttons
│   └── 9 Buttons
│
├── Documentation
│
└── README.md
```

`BASIC` and `PRO` under the Windows application refer to licensed software functionality, not separate executables or separate microcontroller families.

---

# Design Goals

The project aims to provide:

- Simple hardware
- Reliable button input
- Modular firmware
- Multiple microcontroller options
- One Windows application across supported hardware
- BASIC / PRO licensing at software level
- BLE support where available
- USB HID support where available
- Easy Windows configuration
- Expandable button count
- Portable operation
- Customizable interface
- Persistent configuration
- Easy future hardware development

---

# Future Hardware

Possible future hardware extensions include:

- Additional button layouts
- Rotary encoder
- OLED display
- RGB lighting
- Individual button lighting

Any future hardware target should remain independent from the BASIC / PRO software license tier.

---

# License

This project is developed as **ALIN-TECH MACROPAD**.

ALIN-TECH MACROPAD software and firmware are proprietary and distributed in compiled form only.

Source code for proprietary ALIN-TECH MACROPAD components is not included with distributed binaries.

Third-party open-source components remain subject to their respective licenses.

The ALIN-TECH name, logo, product names and branding are not licensed for use without permission from ALIN-TECH.

---

# Português

## Visão Geral

**ALIN-TECH MACROPAD** é um macro pad programável e personalizável para Windows.

O projeto é composto por duas camadas separadas:

1. **Hardware / firmware**
   - Lê os botões físicos.
   - Identifica o número lógico do botão.
   - Envia os eventos dos botões para o Windows através da interface de comunicação suportada.

2. **Aplicação Windows**
   - Deteta o MACROPAD.
   - Recebe os eventos dos botões.
   - Carrega a configuração do utilizador.
   - Executa a ação configurada.
   - Aplica a licença de software BASIC ou PRO ativa.

A plataforma de hardware e o nível da licença do software são independentes.

---

## Importante: o Hardware Não É BASIC ou PRO

O microcontrolador **não** define se o produto é BASIC ou PRO.

**BASIC e PRO são níveis de licença do software dentro da aplicação Windows.**

O mesmo executável ALIN-TECH MACROPAD para Windows é utilizado com os diferentes hardwares suportados.

Isto significa:

- **RP2040-Zero pode ser utilizado com BASIC ou PRO.**
- **XIAO ESP32S3 pode ser utilizado com BASIC ou PRO.**
- Mudar de BASIC para PRO não exige trocar de microcontrolador.
- Mudar de BASIC para PRO não exige instalar outro executável Windows.
- O firmware deve ser escolhido pelo **hardware / microcontrolador**, e não pelo nível da licença do software.

```text
                    ALIN-TECH MACROPAD.exe
                             │
                    ┌────────┴────────┐
                    │                 │
                  BASIC              PRO
             funções software   funções software
                    │                 │
                    └────────┬────────┘
                             │
               mesma compatibilidade de hardware
                             │
          ┌──────────────────┴──────────────────┐
          │                                     │
          ↓                                     ↓
    RP2040-Zero                         XIAO ESP32S3
```

---

## Licenças do Software

### BASIC

BASIC disponibiliza as funcionalidades base do ALIN-TECH MACROPAD.

### PRO

PRO desbloqueia funcionalidades adicionais dentro da mesma aplicação Windows.

O nível da licença é gerido pela aplicação Windows e pelo sistema de licenciamento.

Não é um modelo de hardware.

Não é definido pelo microcontrolador.

---

## Hardwares Suportados

O firmware é organizado pelo microcontrolador / hardware. Cada hardware suportado utiliza um único firmware para os modos de 6 e 9 botões.

| Hardware | 6 botões | 9 botões | USB HID | BLE HID | Windows BASIC | Windows PRO |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| **RP2040-Zero** | Sim | Sim | Sim | Não | Sim | Sim |
| **XIAO ESP32S3** | Sim | Sim | Sim | Sim | Sim | Sim |

---

## Organização do Firmware

Os downloads de firmware são organizados apenas por hardware / microcontrolador.

Existe **um único ficheiro de firmware por microcontrolador suportado**:

```text
Firmware/
│
├── RP2040-Zero/
│   └── ALIN-TECH_RP2040-Zero.uf2
│
└── XIAO-ESP32S3/
    └── ALIN-TECH_XIAO-ESP32S3.bin
```

Não existem ficheiros de firmware separados para 6 teclas e 9 teclas.

O firmware disponibiliza o layout lógico completo de 9 botões. Quando a aplicação Windows está configurada para um MACROPAD de 6 botões, utiliza apenas os Botões lógicos 1–6 e ignora os Botões 7–9.

```text
Firmware de 9 botões
      ↓
Botões 1–9 disponíveis
      ↓
ALIN-TECH MACROPAD.exe
      ↓
Modo 6 botões  → utiliza apenas Botões 1–6
Modo 9 botões  → utiliza Botões 1–9
```

Isto significa que o mesmo firmware `.uf2` ou `.bin` pode ser utilizado tanto no layout de 6 botões como no layout de 9 botões.

Não devem existir firmwares separados para BASIC e PRO.

Não devem existir firmwares separados para 6 teclas e 9 teclas.

A diferença BASIC / PRO é gerida apenas pela aplicação Windows e pela licença.

---

## Principais Funcionalidades

- Botões físicos programáveis
- Layouts de 6 e 9 botões
- Abertura de aplicações
- Controlo de aplicações
- Ícones das aplicações
- Atalhos de teclado do Windows
- Atalhos de teclado com ALT
- Atalhos de teclado com CTRL
- Atalhos com a tecla Windows
- Macros personalizadas
- Abertura de links / websites
- Abertura de pastas
- Controlos de microfone e áudio
- Controlos por aplicação
- Controlos OBS
- Mudança de perfil
- Suporte para Multi Action
- Controlos do rato
- Execução de comandos personalizados
- Captura de ecrã e gravação do ecrã
- Suporte USB HID onde disponível
- Suporte BLE HID onde disponível
- Múltiplos hardwares suportados
- Configuração persistente
- Guardar configuração
- Repor configuração
- Interface personalizável
- Temas personalizáveis
- Funcionamento na área de notificação do Windows
- Arquitetura expansível

---

## Como Funciona

O hardware deteta qual botão físico foi pressionado e envia um identificador lógico para o Windows.

A aplicação Windows recebe esse identificador e executa a ação configurada para esse botão.

```text
Botão Físico
      ↓
Hardware do MACROPAD
      ↓
Microcontrolador
      ↓
USB HID / BLE HID
      ↓
Windows
      ↓
ALIN-TECH MACROPAD.exe
      ↓
Camada de licença BASIC / PRO
      ↓
Ação Configurada
```

O microcontrolador não precisa de saber:

- Qual aplicação deve ser aberta
- Onde a aplicação está instalada
- Qual atalho está atribuído
- Qual macro deve ser executada
- Qual comando do Windows deve correr
- Se a licença Windows é BASIC ou PRO

Essas responsabilidades pertencem à aplicação Windows.

---

# Hardware

## Responsabilidades do Hardware

O hardware é responsável por:

- Ler os botões físicos
- Fazer debounce das entradas
- Identificar os números lógicos dos botões
- Gerir as interfaces de comunicação suportadas
- Disponibilizar USB HID onde suportado
- Disponibilizar BLE HID onde suportado
- Gerir a alimentação
- Gerir o funcionamento por bateria onde suportado
- Disponibilizar informação da bateria onde suportado

---

## Configurações de Botões

### Layout de 6 Botões

```text
┌─────────┬─────────┬─────────┐
│ Botão 1 │ Botão 2 │ Botão 3 │
├─────────┼─────────┼─────────┤
│ Botão 4 │ Botão 5 │ Botão 6 │
└─────────┴─────────┴─────────┘
```

### Layout de 9 Botões

```text
┌─────────┬─────────┬─────────┐
│ Botão 1 │ Botão 2 │ Botão 3 │
├─────────┼─────────┼─────────┤
│ Botão 4 │ Botão 5 │ Botão 6 │
├─────────┼─────────┼─────────┤
│ Botão 7 │ Botão 8 │ Botão 9 │
└─────────┴─────────┴─────────┘
```

O layout de 9 botões expande o layout de 6 botões adicionando os Botões 7–9.

---

## Numeração Lógica dos Botões

A numeração lógica permanece igual em todos os hardwares:

```text
Botão 1
Botão 2
Botão 3
Botão 4
Botão 5
Botão 6
Botão 7
Botão 8
Botão 9
```

Apenas o GPIO físico muda entre as implementações.

---

# RP2040-Zero

## Comunicação

**USB HID**

**Identidade USB:**

```text
ALIN-TECH_USB-MACROPAD
```

O RP2040-Zero é um hardware suportado pela mesma aplicação ALIN-TECH MACROPAD para Windows.

Utiliza um único ficheiro `.uf2` para os layouts de 6 e 9 botões. No modo de 6 botões, a aplicação Windows lê apenas os Botões lógicos 1–6.

Pode ser utilizado com uma licença BASIC ou PRO.

### Ligação dos Botões / Pull-Down

O firmware do RP2040-Zero utiliza as entradas GPIO com **pull-down interno**.

Cada botão deve ligar o respetivo GPIO aos **3.3V quando é pressionado**:

```text
3.3V ── Botão ── GPIO
                 │
                 └── Pull-Down interno ── GND
```

Modo de entrada do firmware:

```text
INPUT_PULLDOWN
```

Estado do botão:

```text
LOW  = Botão solto
HIGH = Botão pressionado
```

Os botões devem utilizar **lógica de 3.3V**, não 5V.

### 6 Botões

| Botão | GPIO |
|---|---:|
| Botão 1 | GP0 |
| Botão 2 | GP1 |
| Botão 3 | GP2 |
| Botão 4 | GP3 |
| Botão 5 | GP4 |
| Botão 6 | GP5 |

### 9 Botões

| Botão | GPIO |
|---|---:|
| Botão 1 | GP0 |
| Botão 2 | GP1 |
| Botão 3 | GP2 |
| Botão 4 | GP3 |
| Botão 5 | GP4 |
| Botão 6 | GP5 |
| Botão 7 | GP6 |
| Botão 8 | GP7 |
| Botão 9 | GP8 |

---

# XIAO ESP32S3

## Comunicação

**USB HID + BLE HID (Bluetooth Low Energy)**

**Identidade USB:**

```text
ALIN-TECH_USB-MACROPAD
```

**Identidade BLE:**

```text
ALIN-TECH_BLE-MACROPAD
```

O XIAO ESP32S3 é um hardware suportado pela mesma aplicação ALIN-TECH MACROPAD para Windows.

Utiliza um único ficheiro `.bin` para os layouts de 6 e 9 botões. No modo de 6 botões, a aplicação Windows lê apenas os Botões lógicos 1–6.

Pode ser utilizado com uma licença BASIC ou PRO.

### Ligação dos Botões / Pull-Down

O firmware do XIAO ESP32S3 utiliza as entradas GPIO com **pull-down interno**.

Cada botão deve ligar o respetivo GPIO aos **3.3V quando é pressionado**:

```text
3.3V ── Botão ── GPIO
                 │
                 └── Pull-Down interno ── GND
```

Modo de entrada do firmware:

```text
INPUT_PULLDOWN
```

Estado do botão:

```text
LOW  = Botão solto
HIGH = Botão pressionado
```

Os botões devem utilizar **lógica de 3.3V**, não 5V.

---

## Monitorização da Bateria

Entrada de monitorização:

```text
D8
```

Divisor de tensão:

- 220 kΩ de BAT+ → D8
- 100 kΩ de BAT− → D8
- D8 é utilizado como entrada ADC para a tensão da bateria.

### Deteção do Carregador / 5VIN

O XIAO ESP32S3 utiliza o **D10** para detetar a presença do carregador / alimentação 5VIN.

O circuito de deteção utiliza um **divisor de tensão de 100 kΩ / 100 kΩ**:

```text
5VIN ── 100 kΩ ── D10 ── 100 kΩ ── GND
```

- 100 kΩ de **5VIN → D10**
- 100 kΩ de **D10 → GND**
- O **D10** é utilizado pelo firmware para detetar se existe alimentação 5VIN / carregador ligado.

Com 5 V em 5VIN, o divisor fornece aproximadamente **2,5 V no D10**.

---

## 6 Botões

| Botão | GPIO |
|---|---:|
| Botão 1 | GPIO 0 |
| Botão 2 | GPIO 1 |
| Botão 3 | GPIO 2 |
| Botão 4 | GPIO 3 |
| Botão 5 | GPIO 4 |
| Botão 6 | GPIO 5 |

## 9 Botões

| Botão | GPIO |
|---|---:|
| Botão 1 | GPIO 0 |
| Botão 2 | GPIO 1 |
| Botão 3 | GPIO 2 |
| Botão 4 | GPIO 3 |
| Botão 5 | GPIO 4 |
| Botão 6 | GPIO 5 |
| Botão 7 | GPIO 6 |
| Botão 8 | GPIO 7 |
| Botão 9 | GPIO 9 |

---

# Ligação Recomendada dos Botões

```text
3.3V
 │
 └──── Interruptor ──── GPIO
                        │
                        └──── Pull-Down interno
```

Modo de entrada do firmware:

```text
INPUT_PULLDOWN
```

Estado do botão:

```text
LOW  = Não pressionado
HIGH = Pressionado
```

A implementação elétrica pode variar entre revisões de hardware.

---

# Debounce dos Botões

Os interruptores mecânicos podem produzir várias transições elétricas durante uma única pressão.

O firmware deve fazer debounce antes de enviar o evento lógico.

```text
Pressão do Botão
     ↓
Detetar Transição
     ↓
Debounce / Validar
     ↓
Confirmar Botão
     ↓
Enviar Evento Lógico
```

---

# Comunicação HID

O protocolo lógico dos botões é independente do GPIO físico.

Para seis botões:

```text
1
2
3
4
5
6
```

Para nove botões:

```text
1
2
3
4
5
6
7
8
9
```

Exemplo:

```text
GPIO Físico
      ↓
Número Lógico do Botão
      ↓
Relatório HID
      ↓
Windows
      ↓
ALIN-TECH MACROPAD.exe
```

A aplicação Windows necessita apenas do número lógico do botão.

---

# USB e BLE

## RP2040-Zero

- USB nativo
- USB HID
- Sem Bluetooth integrado

## XIAO ESP32S3

- USB nativo
- USB HID
- Bluetooth Low Energy
- BLE HID


---

# Prioridade BLE / USB

Nos hardwares que suportam BLE e USB HID:

```text
USB desligado
      ↓
BLE ativo
      ↓
Funcionamento sem fios


USB ligado apenas para alimentação / carregamento
      ↓
BLE permanece ativo
      ↓
Funcionamento sem fios enquanto carrega


USB ligado ao computador como HID
      ↓
USB HID ativo
      ↓
Controlo BLE desativado
      ↓
Funcionamento por cabo
```

---

# Bateria

O suporte de bateria depende do hardware.

As implementações podem incluir:

- Bateria LiPo
- Conector JST
- Carregamento da bateria
- Monitorização da tensão
- Informação da percentagem
- Funcionamento de baixo consumo

A aplicação Windows pode apresentar a informação da bateria quando o hardware e o protocolo a disponibilizam.

---

# Aplicação Windows

A aplicação Windows é a principal camada de configuração e execução.

É utilizada uma única aplicação ALIN-TECH MACROPAD para os hardwares suportados.

A aplicação é responsável por:

- Detetar o dispositivo
- Receber relatórios HID
- Identificar os números lógicos dos botões
- Carregar a configuração
- Executar ações
- Abrir aplicações
- Executar atalhos de teclado
- Executar macros
- Apresentar ícones
- Gerir temas
- Guardar configuração
- Repor configuração
- Gerir a área de notificação
- Aplicar a licença BASIC ou PRO
- Ativar ou desativar funcionalidades de acordo com a licença

---

# Modelo de Software BASIC / PRO

```text
Hardware Suportado
      ↓
ALIN-TECH MACROPAD.exe
      ↓
Validação da Licença
      ↓
┌───────────────┬───────────────┐
│               │               │
BASIC           PRO
│               │
Funções base    Funções base + funcionalidades PRO
```

O mesmo hardware pode continuar a ser utilizado quando a licença de software muda.

Não é necessário trocar de microcontrolador para passar de BASIC para PRO.

---

# Execução de Aplicações

```text
Botão
   ↓
Microcontrolador
   ↓
ID Lógico do Botão
   ↓
Aplicação Windows
   ↓
Configuração
   ↓
Aplicação / Ação Configurada
```

Alterar a ação atribuída a um botão não exige alterar o firmware.

---

# Ficheiro de Configuração

```text
%APPDATA%\ALIN-TECH MACROPAD\config.json
```

Localização típica:

```text
C:\Users\<Username>\AppData\Roaming\ALIN-TECH MACROPAD\config.json
```

Pode conter:

- Atribuições de botões
- Caminhos de aplicações
- Ícones
- Macros
- Tema
- Outras preferências

---

# Guardar e Repor

## Guardar

Guarda a configuração atual.

## Repor

Restaura a configuração predefinida.

---

# Área de Notificação do Windows

```text
Janela Principal
     ↓
Fechar
     ↓
Aplicação permanece ativa
     ↓
Área de Notificação
     ↓
MACROPAD continua a funcionar
```

---

# Interface do Utilizador

A aplicação Windows apresenta uma representação visual do MACROPAD físico.

A interface pode adaptar-se aos layouts de botões e aos estados de comunicação suportados.

---

# Temas

Exemplo de cor de destaque predefinida:

```text
#00AFFF
```

Os temas podem afetar:

- Interface principal
- Botões
- Destaques
- Bordas
- Fundos
- Elementos de destaque

---

# Independência do Hardware

```text
                 RP2040-Zero
                     │
                  USB HID
                     ↓
                  Windows
                     ↓
             ALIN-TECH MACROPAD.exe
                     ↓
                 BASIC / PRO


                XIAO ESP32S3
                     │
                USB HID / BLE
                     ↓
                  Windows
                     ↓
             mesma aplicação
                     ↓
                 BASIC / PRO
```

---

# Responsabilidades do Firmware

O firmware é responsável por:

1. Inicializar os GPIO
2. Ler os botões
3. Fazer debounce
4. Detetar pressões
5. Mapear GPIO para números lógicos
6. Enviar eventos HID
7. Gerir BLE onde suportado
8. Gerir USB onde suportado
9. Gerir a alimentação
10. Disponibilizar informação da bateria onde suportado

O firmware **não** decide se a aplicação Windows é BASIC ou PRO.

---

# Responsabilidades da Aplicação Windows

A aplicação é responsável por:

1. Detetar o dispositivo
2. Receber eventos
3. Identificar números lógicos
4. Carregar a configuração
5. Executar ações
6. Abrir aplicações
7. Executar macros
8. Apresentar ícones
9. Gerir temas
10. Guardar configuração
11. Repor configuração
12. Gerir a área de notificação
13. Gerir a licença BASIC / PRO
14. Ativar as funcionalidades licenciadas

---

# Instalação

Instala a aplicação Windows **ALIN-TECH MACROPAD**.

Existe uma única aplicação Windows para os hardwares suportados.

O instalador não deve apresentar o RP2040-Zero como hardware BASIC nem o XIAO ESP32S3 como hardware PRO.

A seleção do hardware e a licença de software são conceitos separados.

Após a instalação:

1. Instala o único ficheiro de firmware correspondente ao microcontrolador. O mesmo firmware funciona nos layouts de 6 e 9 botões.
2. Liga o MACROPAD.
3. Inicia o ALIN-TECH MACROPAD.
4. Aguarda a deteção do dispositivo.
5. Ativa ou valida a licença BASIC / PRO quando necessário.
6. Configura os botões.
7. Guarda a configuração.
8. Utiliza o MACROPAD normalmente.

---

# Resolução de Problemas

## Dispositivo não detetado

Verifica:

- O MACROPAD está alimentado.
- O cabo USB suporta dados quando utilizas USB.
- O Bluetooth está ativo quando utilizas BLE.
- O firmware corresponde ao microcontrolador.
- O Windows deteta a interface HID necessária.
- A aplicação ALIN-TECH MACROPAD está em execução.

## BLE não detetado

Verifica:

- Bluetooth está ativo.
- O hardware suporta BLE.
- O firmware BLE está em execução.
- O dispositivo está a anunciar.
- O Bluetooth do Windows está a funcionar.

## USB não detetado

Verifica:

- O cabo USB suporta dados.
- A placa está alimentada.
- O hardware suporta USB HID.
- O Windows deteta o dispositivo.
- O firmware está a funcionar.

## Um botão não funciona

Verifica:

- O interruptor está ligado.
- O GPIO está correto.
- O GPIO não está reservado.
- O mapeamento está correto.
- O pull-down está correto.
- O debounce funciona.
- O relatório HID contém o número lógico correto.

## É executada a ação errada

```text
GPIO Físico
      ↓
Número do Botão no Firmware
      ↓
Relatório HID
      ↓
Número do Botão no Windows
      ↓
Ação Configurada
```

A numeração lógica deve permanecer consistente em todo o sistema.

---

# Estrutura de Desenvolvimento

```text
ALIN-TECH MACROPAD
│
├── Firmware
│   ├── RP2040-Zero
│   └── XIAO ESP32S3
│
├── Aplicação Windows
│   ├── BASIC
│   └── PRO
│
├── Hardware
│   ├── 6 Botões
│   └── 9 Botões
│
├── Documentação
│
└── README.md
```

`BASIC` e `PRO` na aplicação Windows referem-se às funcionalidades licenciadas do software, e não a executáveis diferentes nem a famílias de microcontroladores diferentes.

---

# Objetivos de Design

- Hardware simples
- Entrada fiável de botões
- Firmware modular
- Vários microcontroladores compatíveis
- Uma única aplicação Windows para os hardwares suportados
- Licenciamento BASIC / PRO ao nível do software
- BLE onde disponível
- USB HID onde disponível
- Configuração simples
- Número de botões expansível
- Funcionamento portátil
- Interface personalizável
- Configuração persistente
- Evolução simples de hardware no futuro

---

# Hardware Futuro

Possíveis extensões:

- Outros layouts de botões
- Encoder rotativo
- Display OLED
- Iluminação RGB
- Iluminação individual dos botões

Qualquer futuro hardware deve permanecer independente da licença BASIC / PRO do software.

---

# Licença

Este projeto é desenvolvido como **ALIN-TECH MACROPAD**.

O software e o firmware do ALIN-TECH MACROPAD são proprietários e distribuídos apenas em formato compilado.

O código-fonte dos componentes proprietários não é incluído nos binários distribuídos.

Componentes open source de terceiros permanecem sujeitos às respetivas licenças.

O nome ALIN-TECH, o logótipo, os nomes dos produtos e a identidade da marca não podem ser utilizados sem autorização da ALIN-TECH.
