机箱里退役下来的三线风扇别扔,它自带一颗霍尔传感器,抽出来的转速信号接 Arduino 两个中断引脚就能读,做温控风扇、散热监测甚至自制风速计都用得上。整套东西成本为零,是练习硬件中断最好的入门实验。

三根线里藏着一个传感器
三线风扇:红线供电、黑线地、黄线是转速信号。风扇转子磁铁每转过一圈,内置霍尔输出一到两个脉冲(单极一颗、双极两颗),把单位时间的脉冲数换算一下就是转速。四线风扇多出的蓝线是 PWM 调速输入,转速信号仍在黄线上。

接线:一根信号线加共地
信号线接 D2(UNO 的外部中断 0),风扇单独用 12V 或 9V 供电,但地线必须和 Arduino 共地,否则信号没有参考点。信号脚建议加 10k 上拉到 5V;偷懒办法是 pinMode 后直接 digitalWrite(hallsensor, HIGH) 启用内部上拉。注意风扇电源别接板子 5V,独立供电更稳。

完整代码
经典中断计数写法逐字符原样:
//code by Crenn from http://thebestcasescenario.com
//Variables used for calculations
int NbTopsFan; int Calc;
//The pin location of the sensor
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 variable 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 rpm ()
//This is the function that the interrupt calls
{ NbTopsFan++; }
//This is the setup function where the serial port is initialised,
//and the interrupt is attached
void setup()
{ pinMode(hallsensor, INPUT);
Serial.begin(9600);
attachInterrupt(0, rpm, RISING); }
void loop ()
//Set NbTops to 0 ready for calculations
{ NbTopsFan = 0;
//Enables interrupts
sei();
//Wait 1 second
delay (1000);
//Disable interrupts
cli();
//Times NbTopsFan (which is approximately the frequency the fan
//is spinning at) by 60 seconds before dividing by the fan's divider
Calc = ((NbTopsFan * 60)/fanspace[fan].fandiv);
//Prints the number calculated above
Serial.print (Calc, DEC);
//Prints " rpm" and a new line
Serial.print (" rpm\r\n");
}思路是关中断前后夹一秒窗口:开中断计数、delay 一秒、关中断,把计到的脉冲乘 60 再除以"每圈脉冲数"(fanspace 里的分频系数,单极风扇填 1,双极填 2),得到每分钟转速。

为什么要用中断
普通风扇转速几千 RPM,换算成脉冲每秒上百次。如果用 digitalRead 在 loop 里轮询,主循环稍微一忙就丢脉冲。attachInterrupt 把计数交给硬件触发,主循环该干嘛干嘛,这是中断最典型的应用场景,比按键中断的信号还密集,练手效果更好。
踩坑提醒
一是读数跳变先查供电:风扇启动瞬间电流大,和 Arduino 共用一个 USB 电源会拉低电平造成乱脉冲,独立供电加共地即可解决;二是分频系数对不上读数会差一倍,拿不准就把 fan 变量从 1 改 2 各试一次;三是中断函数里只做自增,别塞串口打印,否则一秒窗口都不够它打完。
写在最后
这套测速方案换个对象照样成立:水表磁轮、自行车轮圈、绕线机的转盘,只要能贴上磁铁配一颗外置霍尔(A3144 几毛钱一颗),转速监测就是同一套代码。学会它,等于掌握了"脉冲计数"这一大类传感器项目的通用套路。











收了个旧机箱风扇正好练手
水表改造那个思路可以,A3144确实便宜
fanspace那个分频系数卡过,单极双极差一倍,按文中方法试一遍就出来
attachInterrupt练中断确实比按键例子直观,计数值就是真实脉冲
风扇独立供电共地这个太关键了,上次乱脉冲查了一下午就是电源混用