3.霍尔传感器的程序霍尔传感器的库请从下述官方网站下载。从下载到安装的流程已在第4回、第3回、第2回、第1回的内容中详细介绍,初次使用传感器套件的用户请参阅上述内容。 从上述网站的页面下方下载传感器用软件后,打开Arduino IDE,通过添加库分别选择下载的文件,完成库的安装。
图2 添加库
库安装完成后,请从sketch示例中打开气压传感器及温度传感器的样本,写入Arduino,检查能否正常运行。 - 霍尔传感器的样本:"文件"-"sketch示例"-"BD7411G"-"example"-"BD7411"
此样本程序是在传感器作出反应时,向串行监视器输出"BD7411G Magnet field Detect!"显示的程序。通过写入Arduino,可以确认磁铁靠近传感器时显示的情形。
※将使用BD7411G的程序写入Arduino时,在笔者使用的环境中,若为连接传感器的状态则上传会失败。出现类似情况时,请试着暂时卸下BD7411G传感器进行上传,等上传正常完成后再安装传感器。
霍尔传感器的样本程序
/***************************************************************************
BD7411.ino
Copyright (c) 2016 ROHM Co.,Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <BD7411.h>
int hallout_pin = 0; // use D0 pin
BD7411 bd7411;
void setup() {
Serial.begin(9600);
while (!Serial);
bd7411.init(hallout_pin);
Serial.println("BD7411G Sample");
}
void loop() {
int hallout;
hallout = bd7411.readoutpin();
if (hallout == 0) {
Serial.println("BD7411G Magnet field Detect!");
} else {
Serial.println();
}
delay(500);
}
图3 霍尔传感器的输出结果
创建测量转速的程序请将磁铁安装在电机上测量转速。该程序在串联两节五号电池时计算转速。我们已将齿轮安装在电机上,并在齿轮的局部贴上了四方形的磁铁。为了使磁铁和霍尔传感器间保持2~3mm的距离,制作了一个基座。
这里,我们设定delay(30),若电机转速较快,设为30时可能无法追上一圈,从而无法正确获得数据,这种情况下请缩短delay值,设定为5或10等进行尝试。
#include <BD7411.h>
int hallout_pin = 0; // use D0 pin
int _cnt = 0;
bool _flg = false;
BD7411 bd7411;
void setup() {
Serial.begin(9600);
while (!Serial);
bd7411.init(hallout_pin);
Serial.println("BD7411G Sample");
}
void loop() {
int hallout;
hallout = bd7411.readoutpin();
if (hallout == 0 && _flg == false) {
Serial.print("BD7411G Magnet field Detect! - ");
_flg = true;
_cnt++;
Serial.println(_cnt);
} else {
_flg = false;
}
delay(30);
}
照片3 转速测量测试机
图4 转速显示结果
大家可以看见,样本程序信息显示之后显示了当前的旋转计数!
总结现在我们已经了解了霍尔传感器的简单使用方法,下次我们将实际使用此传感器评估套件的霍尔传感器来挑战自行车速度仪的制作。
|