Arduino 霍尔传感器

1. 霍尔传感器读取


// KY-024  Arduino的
// A0  A0
// G 地线
// + 5伏
// D0  3
int led = 13 ; // LED on arduino
int digitalPin = 3; // linear Hall magnetic sensor digital interface
int analogPin = A0; // linear Hall magnetic sensor analog interface
int digitalVal ; // digital readings
int analogVal; // analog readings

void setup ()
{
  pinMode (led, OUTPUT); 
  pinMode (digitalPin, INPUT); 
  //pinMode(analogPin, INPUT); 
  Serial.begin(9600);
}

void loop ()
{
  // Read the digital interface
  digitalVal = digitalRead(digitalPin) ; 
  if (digitalVal == HIGH) // When magnetic field is present, Arduino LED is on
  {
    digitalWrite (led, HIGH);
  }
  else
  {
    digitalWrite (led, LOW);
  }
  
  // Read the analog interface
  analogVal = analogRead(analogPin);
  Serial.println(analogVal); // print analog value

  delay(100);
}

2. 霍尔传感器 速度计算


const byte interruptPin = 3;
const long taketime = 1000; // 每次测量的时间
unsigned long time; //设置变量 time,计时
float Val = 0; //设置变量 Val,计数
void setup() {
 Serial.begin(9600);
 attachInterrupt(digitalPinToInterrupt(interruptPin), count, FALLING);//触发信号必须是变化的,上升或下降皆可
 time = millis();//开始计时,time获得当前系统时间
}
 
void loop() {
 if (millis() >= time)
 {
 Serial.println(Val*60);//转换成rpm,单磁铁触发分辨率为60rpm,2个磁铁为30rpm
 time = millis() + taketime;//标记未来的时间点,1000ms后执行if判断,输出结果。另,降低刷新频率,可以提高分辨率
 Val = 0;//输出速度结果后清零,记录下一秒的触发次数
 }
}
 
void count() {
 Val += 1;
}

 

你可能感兴趣的:(Arduino)