stm 32 mbed 入门教程(五)-----模拟输入

一.Introduction(介绍)

在之前的教程中,我们学会了使用数字输出DigitalOut去控制引脚的直接状态,以及用数字输入DigitalIn做数字开关,但是数字输入输出代表的逻辑数值只能是0和1。那么有没有什么操作可以表示0-1之间的数值呢?------>今天的主题:模拟输入和输出(AnalogIn AnalogOut)

二.AnalogIn(模拟输入)

从理论上来说,模拟输入输出涉及到的底层原理是ADC和DAC的相关内容,但是其中的相关知识相对来说会比较繁琐,而本期入门级别的教程主要目的在于直接能够使用mbed去做一些实际的事情所以这里就会略讲底层原理。

Use the AnalogIn API to read an external voltage applied to an analog input pin. AnalogIn() reads the voltage as a fraction of the system voltage. The value is a floating point from 0.0(VSS) to 1.0(VCC). For example, if you have a 3.3V system and the applied voltage is 1.65V, then AnalogIn() reads 0.5 as the value.

stm32 mbed 官网中给出的AnalogIn如上,具体意思为在程序中AnalogIn函数读取的值为0-1的浮点数类型的值,加入在一个3.3v总电压的系统中,如果AnalogIn读取的值为0.5,那么系统中应用的电压则为1.65v(3.3*0.5)

那么经过这个例子我们可以很清楚的理解其实就是占比问题,这里有点像我们pwm中占空比。但是为什么能这样做呢?真的能这么准确的分配吗?

这张图代表的是3bit的ADC。所以总共我们可以讲一个系统分成2的3次方份,也就是8份,假设系统为3.3v,那么3.3/8则为每一步的步长,那么在一个步长之内的电压值就会被定义为对应的数字。所有是存在误差的。那么我们如何减小误差呢?很简单,就是增大系统的bit,如果是12bit,那么总共台阶就为2的12次方bit,步长也就会减小,对应的误差也就会减小。

下面是官方给的example

/*
 * Copyright (c) 2017-2020 Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "mbed.h"

// Initialize a pins to perform analog input and digital output functions
AnalogIn   ain(A0);
DigitalOut dout(LED1);

int main(void)
{
    while (1) {
        // test the voltage on the initialized analog pin
        //  and if greater than 0.3 * VCC set the digital pin
        //  to a logic 1 otherwise a logic 0
        if (ain > 0.3f) {
            dout = 1;
        } else {
            dout = 0;
        }

        // print the percentage and 16 bit normalized values
        printf("percentage: %3.3f%%\n", ain.read() * 100.0f);
        printf("normalized: 0x%04X \n", ain.read_u16());
        ThisThread::sleep_for(200);
    }
}

 首先我们先要定义一个AnalogIn的引脚,然后同理对这个引脚进行个性化命名。那么这个能进行AnalogIn也是有讲究的,如下图:

 

扫描二维码关注公众号,回复: 14548602 查看本文章

 这里面引脚信息具有ADC的都能够进行AnalogIn。

应用:AnalogIn的应用可以说是非常的广泛:一般来说我们使用传感器与mbed进行交互,比如电位计,温湿度计,声音传感器,都是需要从传感器传给mbed的,所以这些都是应用AnalogIn。

猜你喜欢

转载自blog.csdn.net/weixin_64524066/article/details/125686407
今日推荐