1# ADC 2 3## Overview 4 5### Function 6 7An analog-to-digital converter (ADC) is a device that converts analog signals into digital signals. 8 9### Basic Concepts 10 11- Resolution 12 13 The number of binary bits that can be converted by an ADC. A greater number of bits indicates a higher resolution. 14 15- Conversion error 16 17 Difference between the actual and theoretical digital values output by an ADC. It is expressed by a multiple of the least significant bit. Generally, the maximum output error is used. 18 19- Transition time 20 21 Time required by an ADC to perform a complete conversion. 22 23 24### Working Principles 25 26In the Hardware Driver Foundation (HDF), the ADC module uses the unified service mode for API adaptation. In this mode, a device service is used as the ADC manager to handle access requests from the devices of the same type in a unified manner. The unified service mode applies to the scenario where there are many device objects of the same type. If the independent service mode is used in this case, more device nodes need to be configured and more memory resources will be consumed. The following figure illustrates the unified service mode of the ADC module. 27 28The ADC module is divided into the following layers: 29 30- Interface layer: provides the capabilities of opening a device, writing data, and closing a device. 31- Core layer: binds services, initializes and releases the PlatformManager, and provides the capabilities of adding, deleting, and obtaining controllers. 32- Adaptation layer: implements hardware-related functions, such as controller initialization. 33 34In the unified service mode, the core layer manages all controllers in a unified manner and publishes a service for the interface layer. That is, the driver does not need to publish a service for each controller. 35 36**Figure 1** Unified service mode 37 38![](figures/unified-service-mode.png "ADC Unified Service Mode") 39 40## Usage Guidelines 41 42### When to Use 43 44ADC devices are used to convert analog voltage into digital parameters. For example, an ADC can be used with an NTC resistor to measure temperature, or can be used to convert the output of an analog sensor into a digital parameter. Before using ADC devices with OpenHarmony, you need to adapt the ADC driver to OpenHarmony. The following describes how to do it. 45 46### Available APIs 47 48To enable the upper layer to successfully operate the hardware by calling the ADC APIs, hook functions are defined in **//drivers/hdf_core/framework/support/platform/include/adc/adc_core.h** for the core layer. You need to implement these hook functions at the adaptation layer and hook them to implement the interaction between the interface layer and the core layer. 49 50Definitions of **AdcMethod** and **AdcLockMethod**: 51 52```c 53struct AdcMethod { 54 int32_t (*read)(struct AdcDevice *device, uint32_t channel, uint32_t *val); 55 int32_t (*start)(struct AdcDevice *device); 56 int32_t (*stop)(struct AdcDevice *device); 57}; 58 59struct AdcLockMethod { 60 int32_t (*lock)(struct AdcDevice *device); 61 void (*unlock)(struct AdcDevice *device); 62}; 63 64``` 65 66At the adaptation layer, **AdcMethod** must be implemented, and **AdcLockMethod** can be implemented based on service requirements. The core layer provides the default **AdcLockMethod**, in which a spinlock is used to protect the critical section. 67 68```c 69static int32_t AdcDeviceLockDefault(struct AdcDevice *device) 70{ 71 if (device == NULL) { 72 return HDF_ERR_INVALID_OBJECT; 73 } 74 return OsalSpinLock(&device->spin); 75} 76 77static void AdcDeviceUnlockDefault(struct AdcDevice *device) 78{ 79 if (device == NULL) { 80 return; 81 } 82 (void)OsalSpinUnlock(&device->spin); 83} 84 85static const struct AdcLockMethod g_adcLockOpsDefault = { 86 .lock = AdcDeviceLockDefault, 87 .unlock = AdcDeviceUnlockDefault, 88}; 89 90``` 91 92If spinlock cannot be used, you can use another type of lock to implement **AdcLockMethod**. The custom **AdcLockMethod** will replace the default **AdcLockMethod**. 93 94 **Table 1** Hook functions in **AdcMethod** 95 96| Function| Input Parameter| Output Parameter| Return Value| Description| 97| -------- | -------- | -------- | -------- | -------- | 98| read | **device**: structure pointer to the ADC controller at the core layer.<br>**channel**: channel number, which is of the uint32_t type.| **val**: pointer to the signal data to be transmitted. It is of the uint32_t type.| HDF_STATUS| Reads the signal data sampled by the ADC.| 99| stop | **device**: structure pointer to the ADC controller at the core layer.| –| HDF_STATUS| Stops an ADC device.| 100| start | **device**: structure pointer to the ADC controller at the core layer.| –| HDF_STATUS| Starts an ADC device.| 101 102**Table 2** Functions in **AdcLockMethod** 103 104| Function| Input Parameter| Output Parameter| Return Value| Description| 105| -------- | -------- | -------- | -------- | -------- | 106| lock | **device**: structure pointer to the ADC device object at the core layer.| –| HDF_STATUS| Acquires the critical section lock.| 107| unlock | **device**: structure pointer to the ADC device object at the core layer.| –| HDF_STATUS| Releases the critical section lock.| 108 109### How to Develop 110 111The ADC module adaptation involves the following steps: 112 1131. Instantiate the driver entry. 114 - Instantiate the **HdfDriverEntry** structure. 115 - Call **HDF_INIT** to register the **HdfDriverEntry** instance with the HDF. 116 1172. Configure attribute files. 118 - Add the **deviceNode** information to the **device_info.hcs** file. 119 - (Optional) Add the **adc_config.hcs** file. 120 1213. Instantiate the core layer APIs. 122 - Initialize **AdcDevice**. 123 - Instantiate **AdcMethod** in the **AdcDevice** object. 124 > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> 125 > For details about the functions in **AdcMethod**, see [Available APIs](#available-apis). 126 127### Example 128 129The following uses the Hi3516D V300 driver **//device/soc/hisilicon/common/platform/adc/adc_hi35xx.c** as an example to describe how to perform the ADC driver adaptation. 130 1311. Instantiate the driver entry. 132 133 The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke. 134 135 Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit. 136 137 ADC driver entry example: 138 139 Multiple devices may connect to the ADC controller. In the HDF, a manager object needs to be created for this type of devices. When a device needs to be started, the manager object locates the target device based on the specified parameters. 140 141 You do not need to implement the driver of the ADC manager, which is implemented by the core layer. However, the **AdcDeviceAdd** function of the core layer must be invoked in the **Init** function to implement the related features. 142 143 ```c 144 static struct HdfDriverEntry g_hi35xxAdcDriverEntry = { 145 .moduleVersion = 1, 146 .Init = Hi35xxAdcInit, 147 .Release = Hi35xxAdcRelease, 148 .moduleName = "hi35xx_adc_driver", // (Mandatory) The value must be the same as the module name in the device_info.hcs file. 149 }; 150 HDF_INIT(g_hi35xxAdcDriverEntry); // Call HDF_INIT to register the driver entry with the HDF. 151 152 /* Driver entry of the adc_core.c manager service at the core layer */ 153 struct HdfDriverEntry g_adcManagerEntry = { 154 .moduleVersion = 1, 155 .Init = AdcManagerInit, 156 .Release = AdcManagerRelease, 157 .moduleName = "HDF_PLATFORM_ADC_MANAGER", // The value must be that of device0 in the device_info.hcs file. 158 }; 159 HDF_INIT(g_adcManagerEntry); 160 ``` 161 1622. Add the **deviceNode** information to the **//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs** file and configure the device attributes in **adc_config.hcs**. 163 164 The **deviceNode** information is related to the driver entry registration. The device attribute values are closely related to the driver implementation and the default values or value ranges of the **AdcDevice** members at the core layer. 165 166 In the unified service mode, the first device node in the **device_info.hcs** file must be the ADC manager. The parameters must be set as follows: 167 168 | Parameter| Value| 169 | -------- | -------- | 170 | moduleName | **HDF_PLATFORM_ADC_MANAGER**| 171 | serviceName | –| 172 | policy | **0**, which indicates that no service is published.| 173 | deviceMatchAttr | Reserved.| 174 175 Configure ADC controller information from the second node. This node specifies a type of ADC controllers rather than an ADC controller. In this example, there is only one ADC device. If there are multiple ADC devices, add the **deviceNode** information to the **device_info.hcs** file and add the corresponding device attributes to the **adc_config** file for each device. 176 177 - **device_info.hcs** example 178 179 ```c 180 root { 181 device_info { 182 platform :: host { 183 device_adc :: device { 184 device0 :: deviceNode { 185 policy = 0; 186 priority = 50; 187 permission = 0644; 188 moduleName = "HDF_PLATFORM_ADC_MANAGER"; 189 serviceName = "HDF_PLATFORM_ADC_MANAGER"; 190 } 191 device1 :: deviceNode { 192 policy = 0; // The value 0 indicates that no service is published. 193 priority = 55; // Driver startup priority. 194 permission = 0644; // Permission for the device node created. 195 moduleName = "hi35xx_adc_driver"; // (Mandatory) Driver name, which must be the same as moduleName in the driver entry. 196 serviceName = "HI35XX_ADC_DRIVER"; // (Mandatory) Unique name of the service published by the driver. 197 deviceMatchAttr = "hisilicon_hi35xx_adc"; // (Mandatory) Private data of the controller. The value must be the same as that of the controller in adc_config.hcs. 198 // The specific controller information is in adc_config.hcs. 199 } 200 } 201 } 202 } 203 } 204 ``` 205 206 - **adc_config.hcs** example 207 208 The following uses Hi3516D V300 as an example. Some fields are unique to Hi3516D V300. You can delete or add fields as required. 209 210 ```c 211 root { 212 platform { 213 adc_config_hi35xx { 214 match_attr = "hisilicon_hi35xx_adc"; 215 template adc_device { 216 regBasePhy = 0x120e0000; // Physical base address of the register. 217 regSize = 0x34; // Bit width of the register. 218 deviceNum = 0; // Device number. 219 validChannel = 0x1; // Valid channel. 220 dataWidth = 10; // Data width after AD conversion, that is, the resolution. 221 scanMode = 1; // Scan mode. 222 delta = 0; // Error range of the conversion result. 223 deglitch = 0; // Setting of the deglitch. 224 glitchSample = 5000; // Deglitch time window. 225 rate = 20000; // Conversion rate. 226 } 227 device_0 :: adc_device { 228 deviceNum = 0; 229 validChannel = 0x2; 230 } 231 } 232 } 233 } 234 ``` 235 236 After the **adc_config.hcs** file is configured, include the file in the **hdf.hcs** file. Otherwise, the configuration file cannot take effect. 237 238 For example, if the **adc_config.hcs** file is in **//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/adc/**, add the following statement to **hdf.hcs** of the product: 239 240 ```c 241 #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/adc/adc_config.hcs" // Relative path of the configuration file 242 ``` 243 244 This example is based on the Hi3516D V300 development board that runs the LiteOS. The corresponding **hdf.hcs** file is in **vendor/hisilicon/hispark_taurus/hdf_config/hdf.hcs** and **//device/hisilicon/hispark_taurus/sdk_liteos/hdf_config/hdf.hcs**. You can modify the file as required. 245 2463. Initialize the **AdcDevice** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init** and **Release**) to instantiate **AdcMethod** in **AdcDevice** (so that the underlying driver functions can be called). 247 248 - Define a custom structure. 249 250 To the driver, the custom structure holds parameters and data. The DeviceResourceIface() function provided by the HDF reads **adc_config.hcs** to initialize the custom structure and passes some important parameters, such as the device number and bus number, to the **AdcDevice** object at the core layer. 251 252 ```c 253 struct Hi35xxAdcDevice { 254 struct AdcDevice device; // (Mandatory) Control object at the core layer. It must be the first member of the custom structure. For details, see the following description. 255 volatile unsigned char *regBase; // (Mandatory) Register base address. 256 volatile unsigned char *pinCtrlBase; 257 uint32_t regBasePhy; // (Mandatory) Physical base address of the register. 258 uint32_t regSize; // (Mandatory) Register bit width. 259 uint32_t deviceNum; // (Mandatory) Device number. 260 uint32_t dataWidth; // (Mandatory) Data bit width of received signals. 261 uint32_t validChannel; // (Mandatory) Valid channel. 262 uint32_t scanMode; // (Mandatory) Scan mode. 263 uint32_t delta; 264 uint32_t deglitch; 265 uint32_t glitchSample; 266 uint32_t rate; // (Mandatory) Sampling rate. 267 }; 268 269 /* AdcDevice is the core layer controller structure. The **Init()** function assigns values to the members of AdcDevice. */ 270 struct AdcDevice { 271 const struct AdcMethod *ops; 272 OsalSpinlock spin; 273 uint32_t devNum; 274 uint32_t chanNum; 275 const struct AdcLockMethod *lockOps; 276 void *priv; 277 }; 278 ``` 279 280 - Instantiate the hook function structure **AdcMethod** of **AdcDevice**. 281 282 The **AdcLockMethod** is not implemented in this example. To instantiate the structure, refer to the I2C driver development. Other members are initialized in the **Init** function. 283 284 ```c 285 static const struct AdcMethod g_method = { 286 .read = Hi35xxAdcRead, 287 .stop = Hi35xxAdcStop, 288 .start = Hi35xxAdcStart, 289 }; 290 ``` 291 292 - Implement the **Init** function. 293 294 Input parameter: 295 296 **HdfDeviceObject**, an interface parameter provided by the driver, contains the .hcs information. 297 298 Return value: 299 300 **HDF_STATUS**<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **//drivers/hdf_core/framework/include/utils/hdf_base.h** file. 301 302 | Status| Description| 303 | -------- | -------- | 304 | HDF_ERR_INVALID_OBJECT | Invalid controller object.| 305 | HDF_ERR_INVALID_PARAM | Invalid parameter.| 306 | HDF_ERR_MALLOC_FAIL | Failed to allocate memory.| 307 | HDF_ERR_IO | I/O error.| 308 | HDF_SUCCESS | Transmission successful.| 309 | HDF_FAILURE | Transmission failed.| 310 311 Function description: 312 313 Initializes the custom structure object and **AdcDevice**, and calls the **AdcDeviceAdd** function at the core layer. 314 315 ```c 316 static int32_t Hi35xxAdcInit(struct HdfDeviceObject *device) 317 { 318 int32_t ret; 319 struct DeviceResourceNode *childNode = NULL; 320 ... 321 /* Traverse and parse all nodes in adc_config.hcs and call the **Hi35xxAdcParseInit** function to initialize the devices separately. */ 322 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { 323 ret = Hi35xxAdcParseInit(device, childNode); // The function definition is as follows: 324 ... 325 } 326 return ret; 327 } 328 329 static int32_t Hi35xxAdcParseInit(struct HdfDeviceObject *device, struct DeviceResourceNode *node) 330 { 331 int32_t ret; 332 struct Hi35xxAdcDevice *hi35xx = NULL; // (Mandatory) Custom structure object. 333 (void)device; 334 335 hi35xx = (struct Hi35xxAdcDevice *)OsalMemCalloc(sizeof(*hi35xx)); // (Mandatory) Allocate memory. 336 ... 337 ret = Hi35xxAdcReadDrs(hi35xx, node); // (Mandatory) Use the default values in the adc_config file to fill in the structure. The function definition is as follows. 338 ... 339 hi35xx->regBase = OsalIoRemap(hi35xx->regBasePhy, hi35xx->regSize); // (Mandatory) Address mapping. 340 ... 341 hi35xx->pinCtrlBase = OsalIoRemap(HI35XX_ADC_IO_CONFIG_BASE, HI35XX_ADC_IO_CONFIG_SIZE); 342 ... 343 Hi35xxAdcDeviceInit(hi35xx); // (Mandatory) Initialize the ADC. 344 hi35xx->device.priv = (void *)node; // (Mandatory) Save device attributes. 345 hi35xx->device.devNum = hi35xx->deviceNum;// (Mandatory) Initialize AdcDevice. 346 hi35xx->device.ops = &g_method; // (Mandatory) Attach the AdcMethod instance object. 347 ret = AdcDeviceAdd(&hi35xx->device)); // (Mandatory) Call this function to set the structure at the core layer. The driver can access the platform core layer only after a success signal is returned. 348 ... 349 return HDF_SUCCESS; 350 351 __ERR__: 352 if (hi35xx != NULL) { // If the operation fails, deinitialize related functions. 353 if (hi35xx->regBase != NULL) { 354 OsalIoUnmap((void *)hi35xx->regBase); 355 hi35xx->regBase = NULL; 356 } 357 AdcDeviceRemove(&hi35xx->device); 358 OsalMemFree(hi35xx); 359 } 360 return ret; 361 } 362 363 static int32_t Hi35xxAdcReadDrs(struct Hi35xxAdcDevice *hi35xx, const struct DeviceResourceNode *node) 364 { 365 int32_t ret; 366 struct DeviceResourceIface *drsOps = NULL; 367 368 /* Obtain the drsOps method. */ 369 drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); 370 if (drsOps == NULL || drsOps->GetUint32 == NULL) { 371 HDF_LOGE("%s: invalid drs ops", __func__); 372 return HDF_ERR_NOT_SUPPORT; 373 } 374 /* Read the configuration parameters in sequence and fill them in the structure. */ 375 ret = drsOps->GetUint32(node, "regBasePhy", &hi35xx->regBasePhy, 0); 376 if (ret != HDF_SUCCESS) { 377 HDF_LOGE("%s: read regBasePhy failed", __func__); 378 return ret; 379 } 380 ret = drsOps->GetUint32(node, "regSize", &hi35xx->regSize, 0); 381 if (ret != HDF_SUCCESS) { 382 HDF_LOGE("%s: read regSize failed", __func__); 383 return ret; 384 } 385 ··· 386 return HDF_SUCCESS; 387 } 388 ``` 389 390 - Implement the **Release** function. 391 392 Input parameter: 393 394 **HdfDeviceObject**, an interface parameter provided by the driver, contains the .hcs information. 395 396 Return value: 397 398 No value is returned. 399 400 Function description: 401 402 Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. 403 404 ```c 405 static void Hi35xxAdcRelease(struct HdfDeviceObject *device) 406 { 407 const struct DeviceResourceNode *childNode = NULL; 408 ... 409 /* Traverse and parse all nodes in adc_config.hcs and perform the release operation on each node. */ 410 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { 411 Hi35xxAdcRemoveByNode(childNode);// The function definition is as follows: 412 } 413 } 414 415 static void Hi35xxAdcRemoveByNode(const struct DeviceResourceNode *node) 416 { 417 int32_t ret; 418 int32_t deviceNum; 419 struct AdcDevice *device = NULL; 420 struct Hi35xxAdcDevice *hi35xx = NULL; 421 struct DeviceResourceIface *drsOps = NULL; 422 423 drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); 424 ... 425 ret = drsOps->GetUint32(node, "deviceNum", (uint32_t *)&deviceNum, 0); 426 ... 427 /* You can use AdcDeviceGet() to obtain the AdcDevice object based on deviceNum and use AdcDeviceRemove() to release the AdcDevice object. */ 428 device = AdcDeviceGet(deviceNum); 429 if (device != NULL && device->priv == node) { 430 AdcDevicePut(device); 431 AdcDeviceRemove(device); // (Mandatory) Remove the AdcDevice object from the driver manager. 432 hi35xx = (struct Hi35xxAdcDevice *)device; // (Mandatory) Obtain the custom object through forcible conversion and perform the Release operation. To perform this operation, the device must be the first member of the custom structure. 433 OsalIoUnmap((void *)hi35xx->regBase); 434 OsalMemFree(hi35xx); 435 } 436 return; 437 } 438 ``` 439