/*
This code measures the speed of a motor connected to an Arduino Uno
using a speed sensor module.
Board: Arduino Uno R4 (or R3)
Component: Speed Sensor Module
*/
// Define the sensor and motor pins
volatile int sensorPin = 2;
const int motorB_1A = 9;
const int motorB_2A = 10;
int Speed;
int PWMSpeed;
int PWMSpeedRamp = 12;
int flag = 0;
volatile int count = 0;
// Define variables for measuring speed
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT_PULLUP); // set sensor pin as input
pinMode(motorB_1A, OUTPUT); // set motor pin 1 as output
pinMode(motorB_2A, OUTPUT); // set motor pin 2 as output
attachInterrupt(digitalPinToInterrupt(sensorPin), blink1, FALLING);
analogWrite(motorB_1A, 0); // set motor speed
analogWrite(motorB_2A, 0);
pinMode(A0, INPUT);
}
void loop() {
PWMSpeed = (analogRead(A0)/1023.00)*255;
Speed = (PWMSpeed*100)/255;
if (PWMSpeedRamp < PWMSpeed){
++PWMSpeedRamp;
}
if (PWMSpeedRamp > PWMSpeed){
--PWMSpeedRamp;
}
Serial.print(PWMSpeed);
Serial.print(" ");
Serial.print(PWMSpeedRamp);
Serial.print(" ");
Serial.println(count);
if ((count >= 0) && (count <399)){
analogWrite(motorB_1A, PWMSpeedRamp);
}
if ((count >= 460)&& (count <499)){
analogWrite(motorB_1A, 20);
}
if (count >=500){
analogWrite(motorB_1A, 0);
count = 0;
delay (3000);
PWMSpeedRamp = 12;
flag = 0;
}
}
void blink1(){
count = count + 1;
}