在前一個章節中我們已經可以利用MOSFET來控制電壓控制風扇轉速,

現在我們要結合前面章節中的轉速偵測,讓arduino可以控制電壓

並同時於LCD 1602A上顯示轉速。

 

/*
使用1602A I2C LCD模組及函式庫
LCD I2C Library,從這裡可以下載:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
本程式使用Newliquidcrystal_1.3.5版函式庫
本程式目的:將轉動VR後的角度比例輸出到PWM接腳並將風扇轉速顯示在LCD上
PWM輸出為pin 9
可變電阻輸入為A0
Interrupt0為風扇轉速輸入腳

程式名稱:Fan_Speed_2
作者:Lu yaku
日期:2018.05.13
*/

#include <Wire.h>               
#include <LiquidCrystal_I2C.h>  

// 初始化 I2C 1602A LCD,I2C預設地址為0x27
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

int fanout = 9; //設定 Arduino 風扇腳位在 9 pin
int count;  //設定變數作為計算使用
int Calc;
int hallsensor = 2; 
typedef struct{
//Defines the structure for multiple fans and 
//their dividers 
char fantype; unsigned int fandiv; }fanspec;
 
//Definitions of the fans
//This is the varible used to select the fan and it's divider,
//set 1 for unipole hall effect sensor
//and 2 for bipole hall effect sensor
fanspec fanspace[3]={{0,1},{1,2},{2,8}}; char fan = 1;


void setup() {

  pinMode(hallsensor, INPUT);
  attachInterrupt(0, rpm, RISING); 
  pinMode(fanout, OUTPUT); //定義 pinmode 為 pin 9 OUTPUT 輸出
  
  lcd.begin(16, 2);
    // 閃爍三次
  for(int i = 0; i < 3; i++) {
  lcd.backlight(); // 開啟背光
  delay(250);
  lcd.noBacklight(); // 關閉背光
  delay(250);
  }
  lcd.backlight();
  delay(250);
  
// 輸出初始化文字
  lcd.setCursor(0, 0); // 設定游標位置在第一行行首
  lcd.print("Hello, world!");
  delay(1000);
  lcd.setCursor(0, 1); // 設定游標位置在第二行行首
  lcd.print("LCD is Working!");
  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0); 
  lcd.print("DutyCycle: ");

}

void rpm ()
//This is the function that the interupt calls
{ count++; }

void loop() {

 // 讀取輸入 on analog pin 0:
 int pot = analogRead(A0); //設定A0 值為讀取類比訊號
 int fan_speed = pot * (255 / 1023.0); //這個公式將會計算風扇速度的pwm輸出介於 0-255
 analogWrite(fanout,fan_speed); //我們設定 9 pin 為 pwm 風扇速度輸出
 int pwm_output = fan_speed * (100 / 254.0);//將PWM輸出轉成百分比顯示到LCD螢幕上
  lcd.setCursor(11, 0); 
  lcd.print(pwm_output);
  lcd.print(" % "); 

//計數器歸零
count = 0;

//開啟中斷interrupt0
attachInterrupt(0, rpm, RISING);  
  
 delay(1000); 

//關閉中斷interrupt0
detachInterrupt(0);

//計算每分鐘轉速RPM
Calc = ((count * 60)/fanspace[fan].fandiv);
//Calc = ((count * 60)/2);

//將轉速計算後輸出到1602A LCD上
 lcd.setCursor(0, 1); 
 lcd.print("RPM = ");
 lcd.print(Calc); 
 lcd.print("   ");
 
}

arrow
arrow
    文章標籤
    arduino PWM FAN 風扇
    全站熱搜

    呂阿谷 發表在 痞客邦 留言(0) 人氣()