# ADC Usage Instructions

The K230 chip integrates a high-performance ADC module internally, with the following features:

- **Number of channels**: 6 independent channels (channel 0-5)
- **Resolution**: 12-bit (output value range is 0~4095)
- **Sampling rate**: Up to 1 MHz

## Usage

### Device Tree Configuration

The ADC device tree configuration already exists in the `k230.dtsi` file (lines 536-540):

```dts
adc: adc@9140d000 {
    compatible = "canaan,k230-adc";
    reg = <0x0 0x9140d000 0x0 0x1000>;
    clocks = <&adc_clk>;
};
```

### User Space Usage (via sysfs)

After the driver registers as an IIO device, it can be accessed via the `/sys/bus/iio/devices/` path:

```bash
# View devices
ls /sys/bus/iio/devices/

# Read raw ADC value of channel0
cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

# Read raw ADC value of channel1
cat /sys/bus/iio/devices/iio:device0/in_voltage1_raw
```

### C Language Programming

Access ADC via the sysfs interface, no additional dependency libraries required:

```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int read_adc_channel(int channel) {
    char path[64];
    FILE *fp;
    int value;

    snprintf(path, sizeof(path),
             "/sys/bus/iio/devices/iio:device0/in_voltage%d_raw", channel);

    fp = fopen(path, "r");
    if (!fp) {
        perror("Failed to open ADC sysfs");
        return -1;
    }

    if (fscanf(fp, "%d", &value) != 1) {
        perror("Failed to read ADC value");
        fclose(fp);
        return -1;
    }

    fclose(fp);
    return value;
}

int main() {
    int value;

    // Read all channels
    for (int i = 0; i < 6; i++) {
        value = read_adc_channel(i);
        printf("ADC channel %d value: %d\n", i, value);
    }

    return 0;
}
```

### Python Programming

Directly read sysfs

```python
# Read ADC value of channel0
with open('/sys/bus/iio/devices/iio:device0/in_voltage0_raw', 'r') as f:
    value = int(f.read().strip())
    print(f"ADC value: {value}")

# Multi-channel reading example
def read_adc(channel):
    path = f'/sys/bus/iio/devices/iio:device0/in_voltage{channel}_raw'
    with open(path, 'r') as f:
        return int(f.read().strip())

for i in range(6):
    print(f"Channel {i}: {read_adc(i)}")
```

## Notes

The k230 chip ADC pin voltage is 1.8V, but some development boards have a pre-voltage divider circuit (such as the 01studio standard board):
![For example, 01studio has the following circuit](https://www.kendryte.com/api/imagecdn/zh/adc_01.png)
