#include <Stepper.h> //include a head file
#include <Keypad.h> // keypad
//SKETH & KEYBOARD
//SKETCH
#define STEPS 2048
Stepper stepper(STEPS, 2, 3, 4, 5);
int previous = 0;
//KEYBOARD
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
// define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; // connect to the column pinouts of the keypad
// initialize an instance of class NewKeypad
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
//END KEYBOARD
//SENSOR
#define STEPS 2048
class StepperController {
private:
Stepper stepper;
const int trigPin;
const int echoPin;
long duration;
int distance;
// Private method to set up the stepper and sensor pins
void privateSetup() {
stepper.setSpeed(100);
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
// Private method to measure the distance using the ultrasonic sensor
void measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
}
// Private method to control the stepper motor based on the measured distance
void controlMotor() {
if (distance <= 0.5) {
stepper.step(0); // Stop the motor
Serial.println("Motor stopped. Object detected within 5mm.");
} else {
stepper.step(10); // Continue running the motor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
delay(100); // Delay for stability
}
public:
// Constructor to initialize the stepper and sensor pins
StepperController(int steps, int pin1, int pin2, int pin3, int pin4, int trig, int echo)
: stepper(steps, pin1, pin2, pin3, pin4), trigPin(trig), echoPin(echo) {
duration = 0;
distance = 0;
}
// Public method to set up the stepper and sensor pins
void setup() {
privateSetup();
}
// Public method to run the main loop
void loop() {
measureDistance();
controlMotor();
}
};
//END SENSOR
void setup()
{
// //speed of 180 per minute
stepper.setSpeed(100);
Serial.begin(9600);
}
void loop()
{
//get analog value
int val = analogRead(0);
//current reading minus the reading of history
stepper.step(10); //Turn the motor in val-previous steps
//store as prevous value
//Serial.println(val);
delay(1);
//previous = val;
//KEYBOARD
char customKey = customKeypad.getKey();
if (customKey)
{
Serial.println(customKey);
}
}
// void loop()
// {
// //SKETCH
// int val = analogRead(0);
// stepper.step(0);
// Serial.print(val);
// }