4位数码管控制 – Arduino

数码管

以下是用来控制4位共阴数码管的代码,接线方式根据头部的定义。目前只支持4位数字展示,没有小数点。

比如: displayFull(2018);

#define d_a 2    
#define d_b 3    
#define d_c 4    
#define d_d 5     
#define d_e 6    
#define d_f 7    
#define d_g 8    
#define d_h 9
#define COM1 10
#define COM2 11
#define COM3 12
#define COM4 13

int numPins[8] = {d_a, d_b, d_c, d_d, d_e, d_f, d_g, d_h};
int coms[4] = {COM1, COM2, COM3, COM4};

unsigned char num[11][8] = 
{
  //a,b, c, d, e, f, g, h
  {1, 1, 1, 1, 1, 1, 0, 0},     //0
  {0, 1, 1, 0, 0, 0, 0, 0},     //1  
  {1, 1, 0, 1, 1, 0, 1, 0},     //2  
  {1, 1, 1, 1, 0, 0, 1, 0},     //3  
  {0, 1, 1, 0, 0, 1, 1, 0},     //4  
  {1, 0, 1, 1, 0, 1, 1, 0},     //5  
  {1, 0, 1, 1, 1, 1, 1, 0},     //6  
  {1, 1, 1, 0, 0, 0, 0, 0},     //7  
  {1, 1, 1, 1, 1, 1, 1, 0},     //8  
  {1, 1, 1, 1, 0, 1, 1, 0},     //9  
  {0, 0, 0, 0, 0, 0, 0, 0}     //.
};

void displayNumber(int n) {
  if (n < 0 || n > 10) {
    return;
  }

  for (unsigned char i = 0; i < 8; i ++) {
    digitalWrite(numPins[i], num[n][i]);
  }
}

void clearNumber() {
  for (unsigned char i = 0; i < 8; i++) {
    digitalWrite(numPins[i], LOW);
  }
}

// select com, from 1 to 4
void selectCom(int n) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(coms[i], HIGH); // clear all first
  }

  digitalWrite(coms[n - 1], LOW);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  for (int i = 0; i < 8; i++) {
    pinMode(numPins[i], OUTPUT);
  }

  for (int i = 0; i < 4; i++) {
    pinMode(coms[i], OUTPUT);
  }
}

void displayOne(int num, int pos) {
  clearNumber();
  selectCom(pos);
  displayNumber(num);
}

// display long number: 0 - 9999
void displayFull(int n) {
  char str[4];
  sprintf(str, "%d", n);
  for (int i = 0; i < 4; i++) {
    displayOne(str[i] - '0', i+1); // char to int
  }
}

void loop() {
  displayFull(2018);
}