/*
 * @Author: dugulingping
 * @Date: 2022-06-09 16:14:32
 * @LastEditTime: 2022-06-12 23:28:17
 * @LastEditors: dugulingping
 * @Description: 
 * @FilePath: \test\turangshidu\turangshidu.ino
 */

// 定义字库
unsigned char LED_0F[] = {
    // 0	 1	  2	   3	4	 5	  6	   7	8	 9	  A	   b	C    d	  E    F    -
    0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x8C,0xBF,0xC6,0xA1,0x86,0xFF,0xbf
};
// 定义位
unsigned char LED_BIT[] = {
    //  1   2   3   4   1+2   3+4   1~4
    0x01,0x02,0x04,0x08,0x03,0x0C,0x0F
};

// 土壤湿度
#define PIN_AO A0
#define PIN_DO 4

// LED
#define SCLK 14
#define RCLK 13
#define DIO 15

int M0 = 1024;  // 在空气中AO读取的值最大为1024，代表干燥时的读数
int M1 = 550;   // 浸泡在水里的最小值 550 （最小值会改变），代表100%湿度

int data[2] = {0};

void setup(){
    pinMode(PIN_AO, INPUT);    
    pinMode(PIN_DO, INPUT);

    // 让三个脚都是输出状态
    pinMode(SCLK,OUTPUT);
    pinMode(RCLK,OUTPUT);
    pinMode(DIO,OUTPUT); 
    Serial.begin(115200);     
}
int delay_date = 0; // 定时
void loop(){
    if(delay_date < 2000){
        delay_date += 4;
        delay(4);
    }else{
        delay_date = 0;
        soilMoisture();
    }

    if(!data[0]){
        LED_display(LED_BIT[6], 0xBF);
        return;
    }

    // 模拟量
    int num1 = data[0] / 1000;
    int num2 = data[0] / 100 % 10;
    int num3 = data[0] / 10 % 10;
    int num4 = data[0] % 10;

    LED_display(LED_BIT[3], LED_0F[num1]);
    LED_display(LED_BIT[2], LED_0F[num2]);
    LED_display(LED_BIT[1], LED_0F[num3]);
    LED_display(LED_BIT[0], LED_0F[num4]);
    
    // delay(3000);

    // num1 = data[1] / 10;
    // num2 = data[1] % 10;
    // LED_display(LED_BIT[0], LED_0F[0xBF]);
    // LED_display(LED_BIT[1], LED_0F[0xBF]);
    
    // LED_display(LED_BIT[2], LED_0F[num1]-128);
    // LED_display(LED_BIT[3], LED_0F[num2]);
    // delay(3000);


} 

void soilMoisture(){
    data[0] = analogRead(PIN_AO);
    Serial.print("AO:");
    Serial.println(data[0]);

    Serial.print("DO=");
    Serial.println(digitalRead(PIN_DO));
    
    float HUMI = (M0 - analogRead(PIN_AO)) / ((M0 - M1) / 100); // 将湿度模拟量转换成数字量
    Serial.print("HUMI= ");
    Serial.print(HUMI);
    Serial.println("% ");
    data[1] = HUMI;
}

void LED_display(unsigned char bit, unsigned char digit ){
    LED_OUT(digit);
    LED_OUT(bit);
    digitalWrite(RCLK,LOW);
    digitalWrite(RCLK,HIGH);
    delay(1);
}
void LED_OUT(unsigned char X){
    unsigned char i;
    for(i=8;i>=1;i--)
    {
        if(X&0x80)
            digitalWrite(DIO,HIGH);
        else
            digitalWrite(DIO,LOW);
        X<<=1;
        digitalWrite(SCLK,LOW);
        digitalWrite(SCLK,HIGH);
    }
}