Usare ADC in applicazioni di alto livelloUse ADCs in high-level applications
Questo argomento descrive come usare i convertitori analogico-digitale (ADC) in un'applicazione di alto livello.This topic describes how to use analog-to-digital converters (ADCs) in a high-level application. Per informazioni sull'uso di ADC in RTApps, vedere Usare periferiche in un'applicazione con funzionalità in tempo reale.See Use peripherals in a real-time capable application for information about ADC use in RTApps.
Azure Sphere supporta la conversione analogico-digitale.Azure Sphere supports analog to digital conversion. Un convertitore ADC converte un input analogico in un valore digitale corrispondente.An ADC converts an analog input to a corresponding digital value. Il numero di canali di input e la risoluzione (ovvero il numero di bit di output di ADC) dipendono dal dispositivo.The number of input channels and the resolution (as number of ADC output bits) are device dependent.
L'esempio ADC_HighLevelApp illustra come accedere ai convertitori ADC in un dispositivo MT3620.The ADC_HighLevelApp sample demonstrates how to access ADCs on an MT3620 device.
MT3620 contiene un convertitore ADC a 12 bit con 8 canali di input.The MT3620 contains a 12-bit ADC with 8 input channels. Il convertitore ADC confronta la tensione di input con una tensione di riferimento e genera come output un valore compreso tra 0 e 4095.The ADC compares an input voltage to a reference voltage and produces a value between 0 and 4095 as its output. Viene eseguito il mapping dei canali di input di ADC e dei pin GPIO da GPIO41 a GPIO48 ai pin corrispondenti nel dispositivo MT3260.The ADC input channels and the GPIO pins GPIO41 through GPIO48 map to the same pins on the MT3260. Tuttavia, se l'applicazione usa il convertitore ADC, tutti e 8 i pin vengono allocati per l'uso come input di ADC.However, if your application uses the ADC then all 8 pins are allocated for use as ADC inputs. Nessun pin può essere usato per GPIO.None of them can be used for GPIO.
Requisiti di ADCADC requirements
Le applicazioni che comunicano con i convertitori ADC devono includere il file di intestazione adc.h e aggiungere le impostazioni di ADC al manifesto dell'applicazione.Applications that communicate with ADCs must include the adc.h header file and add ADC settings to the application manifest.
Tutte le applicazioni devono impostare il relativo hardware di destinazione e includere il corrispondente file di intestazione di definizione dell'hardware.All applications must set their target hardware and include the corresponding hardware definition header file.
File di intestazioneHeader Files
#include <applibs/adc.h>
#include "path-to-your-target-hardware.h"
Sostituire "path-to-your-target-hardware.h" con il percorso del file di intestazione dell'hardware in uso.Replace "path-to-your-target-hardware.h" with the path to the header file for your hardware.
Impostazioni del manifesto dell'applicazioneApplication manifest settings
L'impostazione di ADC nel manifesto dell'applicazione include i controller ADC a cui accede l'applicazione.The ADC setting in the application manifest lists the ADC controllers that are accessed by the application. Per configurare queste impostazioni, aggiungere la funzionalità Adc
al manifesto dell'applicazione e quindi aggiungere ogni controller ADC a tale funzionalità.To configure these settings, add the Adc
capability to the application manifest, and then add each ADC controller to the capability. Per informazioni più dettagliate, vedere l'argomento relativo al manifesto dell'applicazione di Azure Sphere.The Azure Sphere application manifest topic has more details.
Nel codice usare le costanti definite per l'hardware in uso per identificare i controller ADC.In your code, use the constants that are defined for your hardware to identify the ADC controllers. Il compilatore convertirà questi valori in valori non elaborati quando si compila l'app.The compiler will translate these values to raw values when you build the app.
Ad esempio, di seguito è riportato un estratto del manifesto di un'applicazione che ha come destinazione una scheda RDB (Reference Development Board) MT3620.For example, here's an excerpt from an application manifest for an application that targets an MT3620 reference development board (RDB).
"Adc": [ "$MT3620_RDB_ADC_CONTROLLER0" ]
Nell'estratto seguente viene illustrato come specificare lo stesso controller ADC in un'applicazione che ha come destinazione Avnet MT3620 Starter Kit:The following excerpt shows how to specify the same ADC controller in an application that targets the Avnet MT3620 Starter Kit:
"Adc": [ "$AVNET_MT3620_SK_ADC_CONTROLLER0" ]
Panoramica dell'implementazioneImplementation overview
Per implementare l'applicazione per l'accesso a ADC, sono disponibili due approcci.To implement your application for accessing ADC, you have two approaches. Un approccio consiste nell'usare Azure Sphere API ADC Applibs e l'altra tramite le API IOCTL:One approach is via Azure Sphere Applibs ADC API and the other is via ioctls APIs:
- Accesso ADC con funzioni semplificateADC access with simplified functions
- ADC Advanced con accesso alle funzioniADC advanced with functions access
In questo argomento vengono descritti entrambi i metodi.This topic describes both methods. È possibile trovare il codice di esempio completo per ogni metodo:You can find the complete sample code for each method here:
- Frammento di funzioni semplificate ADCADC Simplified Functions Snippet
- Frammento di funzioni avanzate ADCADC Advanced Functions Snippet
Accesso ADC con funzioni semplificateADC access with simplified functions
Le applicazioni di alto livello di Azure Sphere possono accedere ai controller ADC chiamando le API ADC di Applibs.Azure Sphere high-level applications can access ADCs by calling Applibs ADC APIs.
Aprire un controller ADCOpen an ADC controller
Per aprire un controller ADC per l'accesso, chiamare ADC_Open e passare l'ID del controller come parametro.To open an ADC controller for access, call ADC_Open and pass the ID of the controller as a parameter. Se la chiamata ha esito positivo, verrà restituito un descrittore di file.A file descriptor will be returned if the call is successful. In caso contrario, verrà restituito un valore di errore.Otherwise, an error value will be returned.
int ADC_Open(ADC_ControllerId id);
Leggere i dati di un controller ADCRead from an ADC
Per leggere i dati di un controller ADC, chiamare ADC_Poll.To read from the ADC, call ADC_Poll. Ad ADC_Poll vengono passati i parametri seguenti: il descrittore di file restituito da ADC_Open, il canale ADC e un puntatore alla posizione in cui verrà archiviato il valore ADC.You pass the following parameters to ADC_Poll: the file descriptor returned by ADC_Open, the ADC channel, and a pointer to where the ADC value will be stored.
Per ottenere il numero di bit validi (risoluzione) restituito dalla funzione ADC_Poll, chiamare ADC_GetSampleBitCount.To get the number of valid bits (resolution) returned by the ADC_Poll function, call ADC_GetSampleBitCount.
Impostare la tensione di riferimento per ADCSet the ADC reference voltage
Chiamare ADC_SetReferenceVoltage per impostare la tensione di riferimento di ADC.Call ADC_SetReferenceVoltage to set the ADC reference voltage.
Il riferimento di serie del dispositivo MT3620 è pari a 2,5 volt.The MT3620 has an on-chip, 2.5 volt reference. In alternativa, il dispositivo può essere connesso a un riferimento di tensione esterno inferiore o pari a 2,5 volt.Alternatively, it can be connected to an external voltage reference that is less than or equal to 2.5 volts.
Accesso ADC con funzioni avanzateADC access with advanced functions
In alternativa alle funzioni semplificate di alto livello per interagire con la periferica, è possibile sfruttare la libreria IOCTL per aprire la funzionalità.As an alternative to the high-level simplified functions to interact with the peripheral, you can take advantage of the the ioctl library to open up functionality. Questa sezione illustra come eseguire questa operazione e in che modo l'uso di IOCTL è diverso rispetto all'uso delle funzioni generiche di Linux.This section explains how to do that and how using ioctls differs from using the generic Linux functions.
Il frammento di funzioni avanzate di ADC Mostra come leggere ADC usando le funzioni avanzate Azure Sphere.ADC Advanced Functions Snippet shows how to read ADC using the Azure Sphere advanced functions.
Ad esempio, è possibile vedere un confronto affiancato della lettura di ADC con le implementazioni sysfs semplificate, avanzate e Linux:As an example, you can see a side-by-side comparison of reading ADC with the simplified, advanced, and linux sysfs implementations:
- Frammento di funzioni semplificate ADCADC Simplified Functions Snippet
- Frammento di nodi sysfs di ADC LinuxADC Linux Sysfs Nodes Snippet
- Frammento di funzioni avanzate ADCADC Advanced Functions Snippet
Aprire il canale ADCOpen the ADC channel
Per aprire un controller ADC per l'accesso, usare la open
chiamata di Linux passando il percorso alla directory che inizierà con /dev/adc<number>
dove "Number" è l'ID del controller.To open an ADC controller for access, use the Linux open
call passing in the path to the directory which will start with /dev/adc<number>
where ‘number’ is the controller ID. Se la chiamata ha avuto esito positivo, viene restituito un descrittore di file.A file descriptor is returned if the call was successful. In caso contrario, viene restituito un valore di errore.Otherwise, an error value is returned.
Vedere implementazione di esempio per parametri, autorizzazioni e controllo degli errori.See Example Implementation for parameters, permissions, and error checking.
Ottenere la specifica del canaleGet the channel specification
Quando si usano le funzioni avanzate, ottenere la specifica del canale usando le chiamate ioctl prima del polling, impostando la tensione di riferimento o ottenendo il numero di bit di esempio.While using the advanced functions, get the channel specification by using ioctl calls before polling, setting reference voltage or getting the sample bit count. Questo passaggio può essere ignorato dalla codifica a livello di codice di alcuni valori ottenuti, ma non è consigliabile.This step can be skipped by hard-coding some of the values obtained, but it is not recommended. Si noti che questo passaggio è gestito dal codice fornito nelle funzioni semplici.Note that this step is handled by code supplied in the simple functions.
// Used to get the size of the buffer to allocate for the channel specification
IIO_GET_CHANNEL_SPEC_BUFFER_TOTAL_SIZE_IOCTL
// Used to get the channel specification and set the ‘iio_ioctl_chan_spec_buffer’ struct properly
IIO_GET_CHANNEL_SPEC_BUFFER_IOCTL
Impostare la tensione di riferimentoSet the reference voltage
Per impostare la tensione di riferimento di un canale usando l'API avanzata:To set the reference voltage of a channel using the advanced API:
Impostare le informazioni di ADC popolate nella
iio_ioctl_chan_spec_buffer
struttura recuperata nella specifica del canale Get.Set the ADC information populated in theiio_ioctl_chan_spec_buffer
structure that was retrieved in Get Channel specification.Ottenere l'indice di proprietà della proprietà da impostare per il canale.Get the property index of the property to set for the channel.
Scrivere la tensione di riferimento usando l'indice della proprietà e le informazioni sulla specifica del canale.Write the reference voltage using the property index and channel specification information.
Per ottenere l'indice della proprietà della tensione di riferimento:To get the index of the reference voltage property:
Dalla
iio_ioctl_chan_spec_buffer
struttura recuperata nella specifica del canale Getusare il valore del campochannel
e, dalchannel
campo, usare il valore del campoext_info
.From theiio_ioctl_chan_spec_buffer
structure retrieved in Get Channel specification, use the value from thechannel
field and, from thechannel
field, use the value from theext_info
field. Ilext_info
campo è unoiio_ioctl_chan_spec_ext_info
struct che rappresenta il capo di un elenco collegato di descrittori di proprietà per il canale.Theext_info
field is aniio_ioctl_chan_spec_ext_info
struct that is the head of a linked list of property descriptors for the channel.A partire da 0, attraversare l'elenco contando i nodi fino a quando il
name
campo non corrisponde allareference_voltage
stringa.Starting from 0, traverse the list counting the nodes until thename
field matches thereference_voltage
string.- Ogni nodo nell'elenco ha un campo "Next" che punta al nodo successivo nell'elenco.Each node in the list has a "next" field that points to the next node in the list. L'ultimo nodo punta a NULL.The last node points to NULL.
- Il contatore risultante è l'indice della proprietà.The resulting counter is the index of the property.
Per impostare la tensione di riferimento, usare l'
IIO_WRITE_CHANNEL_EXT_INFO_IOCTL
IOCTL che accetta una struttura di tipoiio_ioctl_write_chan_ext_info
, che contiene i dati rilevanti (in questo caso la tensione), il canale da impostare e la proprietà specifica (tensione di riferimento) impostata per il canale.To set the reference voltage, use theIIO_WRITE_CHANNEL_EXT_INFO_IOCTL
ioctl that takes in a struct of typeiio_ioctl_write_chan_ext_info
, which contains the relevant data (in this case the voltage), the channel to set, and the specific property (reference voltage) that is set for that channel.
Ottenere il numero di bit di esempioGet the sample bit count
Per impostare la tensione di riferimento usando le API avanzate:To set the reference voltage using the advanced APIs:
Assicurarsi di ottenere le informazioni del canale ADC appropriato.Ensure you are getting the information of the proper ADC channel. Queste informazioni vengono popolate nella
iio_ioctl_chan_spec_buffer
struttura recuperata nella sezione ottenere la specifica del canale.This information is populated in theiio_ioctl_chan_spec_buffer
structure that was retrieved in the Get Channel Specification section.Ottenere l'indice di proprietà della proprietà che si desidera leggere per il canale, che in questo caso è il numero di bit di esempio.Get the property index of the property you want to read for the channel, which in this case is the sample bit count.
Usare IOCTL Linux per ottenere il conteggio dei bit di esempio usando l'indice delle proprietà e la specifica del canale.Use Linux ioctls to get the sample bit count using the property index and channel specification.
Per ottenere l'indice della proprietà del numero di bit di esempio, usare un processo identico per impostare la tensione di riferimento.To get the property index of the sample bit count, use a process identical to Set reference voltage. Tuttavia, durante l'iterazione sull'elenco collegato chiamato ext_info
di tipo iio_ioctl_chan_spec_ext_info
, corrisponde alla stringa current_bits
.However, while iterating over the linked list called ext_info
of type iio_ioctl_chan_spec_ext_info
, match the string current_bits
.
Chiamare il comando IOCTL IIO_READ_CHANNEL_EXT_INFO_IOCTL
per popolare uno struct di tipo iio_ioctl_read_chan_ext_info
con i dati necessari nel buffer
campo.Call the ioctl IIO_READ_CHANNEL_EXT_INFO_IOCTL
to populate a struct of type iio_ioctl_read_chan_ext_info
with the necessary data in the buffer
field.
Leggi il canale ADCRead the ADC channel
Per leggere il canale ADC, eseguire il polling utilizzando la chiamata IOCTL IIO_READ_RAW_CHANNEL_INFO_IOCTL
, passando lo struct iio_ioctl_raw_channel_info
che verrà popolato con i dati dal canale ADC.To read the ADC channel, poll using the ioctl call IIO_READ_RAW_CHANNEL_INFO_IOCTL
, passing in the struct iio_ioctl_raw_channel_info
which will be populated with the data from the ADC channel.
Implementazione di esempioExample implementation
Per leggere ADC usando l'implementazione di Azure Sphere Advanced, vedere il frammento nell' esempio di app avanzata ADC.To read ADC using the Azure Sphere advanced implementation, see the snippet in ADC Advanced app sample.
Per confrontare le differenze nella semantica tra l'interazione con la periferica quando si codifica per Azure Sphere e la codifica per un sistema Linux generico, vedere LinuxSysfsNodes.To compare the differences in semantics between interacting with the peripheral when coding for Azure Sphere and coding for a generic Linux system, see LinuxSysfsNodes.
Supporto di MT3620MT3620 support
Le funzionalità ADC supportate per MT3620 sono indicate in MT3620: stato del supporto.The supported ADC features for the MT3620 are listed in MT3620 Support Status. Il manuale utente della scheda di sviluppo MT3620 descrive il layout dei pin e le relative funzioni.The MT3620 development board user guide describes the pin layout and pin functions.
La cartella HardwareDefinitions nella directory di installazione di Microsoft Azure Sphere SDK contiene le definizioni per le lavagne di sviluppo, i moduli e i chip comuni Azure Sphere.The HardwareDefinitions folder in the Microsoft Azure Sphere SDK installation directory contains definitions for common Azure Sphere development boards, modules, and chips. Contiene file di intestazione e JSON che definiscono le interfacce master per MT3620, MT3620 RDB, insieme ad altri componenti hardware MT3620.It contains header and JSON files that define the master interfaces for the MT3620, MT3620 RDB, along with other MT3620 hardware. Il percorso predefinito per la cartella HardwareDefinitions è C:\Program Files (x86)\Microsoft Azure Sphere SDK\Hardware Definitions
in Windows e /opt/azurespheresdk/HardwareDefinitions
in Linux.The default location for the HardwareDefinitions folder is C:\Program Files (x86)\Microsoft Azure Sphere SDK\Hardware Definitions
on Windows and /opt/azurespheresdk/HardwareDefinitions
on Linux.