Advertisement
microrobotics

Vibration Motor 3V

Apr 17th, 2023
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's an example of how to control a vibration motor's speed using a potentiometer with an Arduino, without using an H-bridge. In this example, we will use an NPN transistor (e.g., 2N2222) to control the motor speed.
  3.  
  4. Wiring:
  5.  
  6. Connect the vibration motor's positive (+) terminal to the transistor's collector (C).
  7. Connect the vibration motor's negative (-) terminal to the power supply ground (GND).
  8. Connect the transistor's emitter (E) to the power supply ground (GND).
  9. Connect a resistor (1kΩ recommended) between the transistor's base (B) and the Arduino's PWM pin (e.g., pin 3).
  10. Connect the potentiometer's middle pin to the Arduino's analog pin A0.
  11. Connect the potentiometer's other two pins to the power supply voltage (VCC) and ground (GND) respectively.
  12. Now, you can use the following code to control the vibration motor's speed using the potentiometer:
  13.  
  14. This code reads the potentiometer value, maps it to the motor speed range (0-255), and sets the vibration motor's speed accordingly. Make sure the transistor and resistor values are appropriate for the motor's voltage and current requirements. Adjust the connections and pin numbers as necessary to match your hardware setup.
  15. */
  16.  
  17. #include <Arduino.h>
  18.  
  19. const int MOTOR_PIN = 3; // Transistor base connected to Arduino pin 3 through a 1kΩ resistor
  20. const int POT_PIN = A0; // Potentiometer connected to Arduino analog pin A0
  21.  
  22. void setup() {
  23.   pinMode(MOTOR_PIN, OUTPUT); // Set the motor pin as output
  24. }
  25.  
  26. void loop() {
  27.   int potValue = analogRead(POT_PIN); // Read the potentiometer value (0-1023)
  28.  
  29.   // Map the potentiometer value to the motor speed range (0-255)
  30.   int motorSpeed = map(potValue, 0, 1023, 0, 255);
  31.  
  32.   // Set the vibration motor speed
  33.   analogWrite(MOTOR_PIN, motorSpeed);
  34.  
  35.   // Optional: Add a small delay between readings
  36.   delay(10);
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement