# PWM HAL interface documentation

## Hardware introduction

K230 integrates a PWM controller internally, providing 2 channels of PWM, with a total of 6 Channels. Among them, Channel 0 ~ 2 belongs to one channel of PWM, and Channel 3 ~ 5 belongs to another channel of PWM. **Note that the same PWM can only use the same frequency, but the duty cycle can be different**.

---

## Function interface description

### `int drv_pwm_init(void);`

**Function**: Initialize PWM driver.

**Return Value**:

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

---

### `int drv_pwm_deinit(void);`

**Function**: Deinitialize PWM driver and shut down the device.

**Return Value**:

- `0`: Success

---

### `int drv_pwm_set_freq(int channel, uint32_t freq);`

**Function**: Set the PWM frequency of the specified channel. The current duty cycle is maintained when setting the frequency.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`
- `freq`: frequency value (Hz), cannot be 0

**Return Value**:

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

---

### `int drv_pwm_get_freq(int channel, uint32_t* freq);`

**Function**: Get the PWM frequency of the specified channel.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`
- `freq`: Pointer used to store frequency value (Hz)

**Return Value**:

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

---

### `int drv_pwm_set_duty(int channel, uint32_t duty);`

**Function**: Set the PWM duty cycle of the specified channel.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`
- `duty`: Duty cycle (%), range `[0, 100]`

**Return Value**:

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

---

### `int drv_pwm_get_duty(int channel, uint32_t* duty);`

**Function**: Get the PWM duty cycle of the specified channel.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`
- `duty`: Pointer (%) used to store the duty cycle value

**Return Value**:

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

---

### `int drv_pwm_enable(int channel);`

**Function**: Enable the PWM output of the specified channel.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`

**Return Value**:

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

---

### `int drv_pwm_disable(int channel);`

**Function**: Disable the PWM output of the specified channel.

**parameter**:

- `channel`: PWM channel number, range `[0, 5]`

**Return Value**:

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

---

## Usage example

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

**Note**:

1. Before using PWM, you need to configure the corresponding pin to the PWM function through FPIOA.
1. The same PWM can only use the same frequency, but the duty cycle can be different.
