The Arduino Nano is a microcontroller board based on the ATmega328P, which is very similar to the Arduino Uno. If you're using the Nano with the ATmega328P, you can use the same pins for driving a motor with PWM and direction control as you would with an Arduino Uno. Here's a quick guide:
-
PWM (Analog Output) Pin: Use the analogWrite() function to control the speed of the motor. On the Nano, you can use pins 3, 5, 6, 9, 10, and 11 for PWM output. These pins are connected to the ATmega328P's hardware PWM timers.
-
Direction Control: You'll need to use digital I/O pins to control the direction of your motor. Any digital I/O pin can be used for this.
Here's a simple example using pins 3 and 4 for PWM (assuming you're using a motor driver that can accept PWM signals to control speed and separate signals for direction):
// PWM pin for speed control
const int pwmPin = 3;
// Direction control pins (left and right)
const int dirLeftPin = 4;
const int dirRightPin = 5;
void setup() {
// Set up the PWM pin for analog output
pinMode(pwmPin, OUTPUT);
// Set up the direction control pins for output
pinMode(dirLeftPin, OUTPUT);
pinMode(dirRightPin, OUTPUT);
}
void loop() {
// PWM duty cycle adjustment for motor speed goes here
analogWrite(pwmPin, 128); // Mid-range PWM value
// Toggle direction control pins to change motor direction
digitalWrite(dirLeftPin, HIGH); // Forwards
digitalWrite(dirRightPin, LOW); // Backwards
delay(1000); // Wait for 1 second
digitalWrite(dirLeftPin, LOW); // Stop
digitalWrite(dirRightPin, LOW); // Stop
delay(1000); // Wait for 1 second
// Reverse direction
digitalWrite(dirLeftPin, LOW); // Backwards
digitalWrite(dirRightPin, HIGH); // Forwards
delay(1000); // Wait for 1 second
digitalWrite(dirLeftPin, LOW); // Stop
digitalWrite(dirRightPin, LOW); // Stop
delay(1000); // Wait for 1 second
}
Make sure to replace const int pwmPin = 3; with the actual PWM pin you're using and adjust the delay() times as needed for your application.
If you're using a different version of the Arduino Nano (such as the Nano 33 or other models with different microcontrollers), check the pinout and specifications of your specific board to determine which pins can be used for PWM and digital output.
Remember to also consider the power requirements of your motor and the capabilities of your Arduino Nano. Motors can draw a significant amount of current, so you may need to use a motor driver module to handle the increased power demands and isolate the Arduino from the electrical noise and high currents involved.