树莓派拓展模拟量采集(AD)功能

树莓派拓展模拟量采集(AD)功能1 前言树莓派自身不带有模拟量采集功能 A D 功能 当需要 AD 功能时 常通过 IIC 外接一个 A D 模块来实现 如 8 位 A D 芯片 PCA9685 本文首先简要介绍 PCA9685 特性 然后基于树莓派的 Bcm2835 库开发 PCA9685 的驱动库 树莓派安装 Bcm2835 库参考这篇文章 2 PCA9685PCA96 芯片有 4 路 8 位的 A D 采集通道和一路 8 位 D A 输出通道 其他通过 IIC 与外部通信 其芯片引脚见下图 其工作电压 VDD 可以 2 5 6V 参考电压 VREF 为 A D 转化参考电压可以与 VDD 一致也可不一致

1.前言

树莓派自身不带有模拟量采集功能(A/D)功能,当需要AD功能时,常通过IIC外接一个A/D模块来实现,如8位A/D芯片PCA9685。本文首先简要介绍PCA9685特性,然后基于树莓派的Bcm2835库开发PCA9685的驱动库。树莓派安装Bcm2835库参考这篇文章

2.PCA9685

3.树莓派基于Bcm2835编写驱动库

使用C++语言编写该库,为PCA9685芯片编写一个类,其头文件pca9685.h

#ifndef PCF8591_H #define PCF8591_H #include  
     #include  
     #include  
     / * A class to control the 8-bits A/D(D/A) device PCF8591 */ class PCF8591{ 
    public: PCF8591(uint8_t addr = 0x48); bool init(); void setRefV(float refV); uint8_t readAD(uint8_t channel); float readVoltage(uint8_t channel); private: uint8_t _addr; float _refV; char sendBuf[3]; uint8_t errCode; }; #endif 

pca9685.cpp文件

#include "pcf8591.h" PCF8591::PCF8591(uint8_t addr) { 
    _addr = addr; _refV = 5.03f; //设置参考电压Vref, 该值为A/D和D/A的参考电压,需要使用万用表测量出来 } / * Before MS5837::init(), please bcm2835_init() in main.c! / bool PCF8591::init() { 
    printf("PCF8591 Init...\n"); if(!bcm2835_i2c_begin()) { 
    printf("bcm2835_i2c_begin failed at %s%d\n",__FILE__,__LINE__); return false; } bcm2835_i2c_setSlaveAddress(_addr); bcm2835_i2c_set_baudrate(); return true; } void PCF8591::setRefV(float refV) { 
    _refV = refV; //设置参考电压Vref, 该值为A/D和D/A的参考电压,需要使用万用表测量出来 } / * brief Read the channel A/D * param channel 0-3 * return 0-255 */ uint8_t PCF8591::readAD(uint8_t channel) { 
    bcm2835_i2c_setSlaveAddress(_addr); //发送CONTROL BYTE sendBuf[0] = 0x00 | channel; if((errCode = bcm2835_i2c_write(sendBuf,1))) printf("bcm2835_i2c_write failed at %s%d, errCode = 0x%x\n",__FILE__,__LINE__, errCode); //读取1字节数据  char byte; if((errCode = bcm2835_i2c_read(&byte,1))) printf("bcm2835_i2c_read failed at %s%d, errCode = 0x%x\n",__FILE__,__LINE__, errCode); return byte; } / * brief read the channel voltage * param channel 0-3 * return 0-_refV */ float PCF8591::readVoltage(uint8_t channel) { 
    return readAD(channel)/255.0f*_refV; } 

一个测试例程testMain.cpp

#include "pcf8591.h" #include  
     using namespace std; int main() { 
    bcm2835_init(); PCF8591 pcf8591; if(pcf8591.init()) cout << "PCF8591 init successfully" << endl; else { 
    cout << "PCF8591 init failed" << endl; exit(-1); } int i = 10; while(i) { 
    int byte = pcf8591.readAD(3); cout << byte << endl; bcm2835_delay(100); } return 0; } // g++ testMain.cpp pcf8591.cpp -lbcm2835 -o testMain 

驱动库可以直接github下载

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220962.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午7:14
下一篇 2026年3月17日 下午7:15


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号