# SBUS HAL interface documentation

## Hardware introduction

K230 supports the SBUS (Serial Bus) protocol through the UART interface. SBUS is a serial communication protocol commonly used in remote control receivers, using a 100kbps baud rate, 8 data bits, 2 stop bits, and even parity. Supports 16 channels (11 bits of precision per channel), plus frame loss and fail-safe flags.

---

## Data structure description

### `sbus_flag_t`

**Description**: SBUS flag structure.

- `ch17`: Digital channel 17 status
- `ch18`: Digital channel 18 status
- `frame_lost`: frame loss flag
- `failsafe`: fail-safe flag

### `sbus_dev_t`

**Description**: SBUS device handle type.

---

## Function interface description

### `sbus_dev_t sbus_create(int uart_id);`

**Function**: Create SBUS device instance and configure UART parameters.

**parameter**:

- `uart`: UART device id, supports 1 ~ 4, represents uart1 ~ uart4

**Return Value**:

- Success: Returns SBUS device handle
- Failure: Return `NULL`

---

### `void sbus_destroy(sbus_dev_t dev);`

**Function**: Destroy the SBUS device instance and release resources.

**parameter**:

- `dev`: SBUS device handle

---

### `int sbus_set_channel(sbus_dev_t dev, uint8_t channel_index, uint16_t value);`

**Function**: Set the value of the specified channel.

**parameter**:

- `dev`: SBUS device handle
- `channel_index`: channel index, range `[0, 15]`
- `value`: Channel value, 11-bit precision, typical range `[172, 1811]`, median value 1024

**Return Value**:

- `0`: Success
- `-1`: failed

---

### `int sbus_set_all_channels(sbus_dev_t dev, uint16_t *channels);`

**Function**: Set the values ​​of all 16 channels.

**parameter**:

- `dev`: SBUS device handle
- `channels`: Array containing 16 channel values

**Return Value**:

- `0`: Success
- `-1`: failed

---

### `void sbus_set_flags(sbus_dev_t dev, const sbus_flag_t *flags);`

**Function**: Set the SBUS flag.

**parameter**:

- `dev`: SBUS device handle
- `flags`: flag structure pointer

---

### `void sbus_get_flags(sbus_dev_t dev, sbus_flag_t *flags_out);`

**Function**: Get the current SBUS flag.

**parameter**:

- `dev`: SBUS device handle
- `flags_out`: Structure pointer used to store flag bits

---

### `int sbus_send_frame(sbus_dev_t dev);`

**Function**: Send SBUS data frame. Encode the currently set channel value and flag bits into a 25-byte SBUS frame and send it through UART.

**parameter**:

- `dev`: SBUS device handle

**Return Value**:

- `0`: Success
- `-1`: failed

---

### `void sbus_set_debug(sbus_dev_t dev, bool val);`

**Function**: Set debugging mode. When sending a frame in debug mode, the decoded channel value and flag bit will be printed.

**parameter**:

- `dev`: SBUS device handle
- `val`: `true` turns on debugging, `false` turns off debugging

---

## Usage example

Please refer to `src/rtsmart/libs/testcases/rtsmart_hal/test_sbus.c`

**Note**:

1. The corresponding UART TX pin needs to be configured through FPIOA before use.
