以下以四位共阳极数码管为例;
本文所有说明均以注释的方式进行。
使用方法:
#include "DigitalTube.h"
//每位共阳极对应的引脚int digital[4] = {8, 11, 12, 7};//参数分别为a f b g e c d dp digital(共阳极引脚数组) length(digital长度)DigitalTube tube = DigitalTube(9, 10, 13, 6, 2, 5, 3, 4, digital, 4);void setup() {for(int i=0; i<=13 ; i++){pinMode(i, OUTPUT);}//亮灯函数;第一个参数位灯的形状,第二个参数为第几位//灯的形状以八位二进制表示,从左到右分别的 a f b g e c d dp; 0为灭、1为亮//该函数表示在第二位显示0tube.light(0b11101110, 2);delay(5000);//清空灯光,防止余晖tube.clear();
}void loop() {//亮灯函数;示数891.0 长度为5位(包括小数点)//第一个参数不一定为严格的小数可以有多个小数点例如tube.light("1.5.7.0", 7);tube.light("891.0", 5);
}
以下为核心代码;代码以共阳极数码管为例,可以根据自己的需要更改HIGH和LOW;或将需要的电平添加到构造函数中使用;
#ifndef _DIGITALTUBE_H_
#define _DIGITALTUBE_H_#include"Arduino.h"class DigitalTube
{private://八位数字引脚int figure[8];//共阳极引脚数组int* digitalPin;//共阳极引脚长度int digitalLength;public://0-9的形状int shapeList[10] = {0b11101110, 0b00100100, 0b10111010, 0b10110110, 0b01110100, 0b11010110, 0b11011110, 0b10100100, 0b111111110, 0b11110110};//初始化DigitalTube(int a, int f, int b, int g, int e, int c, int d, int dp, int digital[], int length);//亮单个灯光, shape 灯光形状; unit 第几位void light(int shape, int unit);void light(String num, int size);//清空灯光void clear();
};
#endif
#include "Print.h"
#include"DigitalTube.h"
#include"Arduino.h"DigitalTube::DigitalTube(int a, int f, int b, int g, int e, int c, int d, int dp, int digital[], int length)
{//初始化PINfigure[0] = a;figure[1] = f;figure[2] = b;figure[3] = g;figure[4] = e;figure[5] = c;figure[6] = d;figure[7] = dp;this->digitalPin = digital;this->digitalLength = length;// 初始化电压for(int i=0; i< sizeof(figure) ; i++){digitalWrite(figure[i], LOW);}for(int i=0; i< sizeof(digital) ; i++){digitalWrite(digitalPin[i], LOW);}
};
void DigitalTube::light(int shape, int unit){for(int i =0; i< digitalLength ;i++){digitalWrite(digitalPin[i], LOW);}digitalWrite(digitalPin[unit], HIGH);for(int i=0; i< 8;i++){int level = shape&(1<<i);if(level != 0){digitalWrite(figure[7-i], LOW);}else{digitalWrite(figure[7-i], HIGH);}}
};void DigitalTube::light(String num, int size){int i = 0, y = 0;while(i< size){int shape = this->shapeList[(int)num[i] - 48];if(num[i+1] == '.'){i++;shape = shape | 1;}this->light(shape, y);delay(1);this->clear();i++;y++;}
};void DigitalTube::clear(){// for(int i =0; i< sizeof(digitalPin) ;i++){// digitalWrite(digitalPin[i], HIGH);// }for(int i=0; i< 8;i++){digitalWrite(figure[i], HIGH);}
}