/*
Arduino | coding-help
Motor speed control
mechanicfactory — 7/17/24 at 6:54 AM
In my opinion, it only turns on at maximum speed and does
not turn on at previous speeds, so it seems like only turn
on and off. However, the maximum speed when turned on is
slower than when connected directly to a 9v battery.
What's the problem?
Below is the code modified to use IRremote V4.
The Wokwi remote uses different keys, this uses the
same "raw data" as the original code.
>>>
IRremote interferes with PWM on pin 9, pins were changed.
<<<
See https://github.com/Arduino-IRremote/Arduino-IRremote?tab=readme-ov-file#timer-and-pin-usage
The output of the motor driver is 2v lower than input voltage.
*/
#include <IRremote.hpp>
#include <Servo.h>
const int MAX_SPEED = 255;
const int MIN_SPEED = 0;
const int SPD_INCREMENT = 25;
const int SERVO_PIN = 2;
const int IN1_PIN = 5; // IN1
const int IN2_PIN = 4; // IN2
const int ENA_PIN = 6; // ENA (PWM 제어 핀)
const int IR_RECEIVE_PIN = 11;
int motorSpeed = 0; // Motor speed (0-255)
Servo servo;
void setup() {
Serial.begin(9600);
IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);
servo.attach(SERVO_PIN);
pinMode(IN1_PIN, OUTPUT);
pinMode(IN2_PIN, OUTPUT);
pinMode(ENA_PIN, OUTPUT);
// initialize driver
digitalWrite(IN1_PIN, LOW);
digitalWrite(IN2_PIN, LOW);
analogWrite(ENA_PIN, motorSpeed);
}
void loop() {
if (IrReceiver.decode()) {
int command = IrReceiver.decodedIRData.command;
Serial.print("Command:\t");
Serial.println(command);
Serial.print("Raw data:\t");
Serial.println(IrReceiver.decodedIRData.decodedRawData, HEX);
if (command == 168) { // -번 // PLAY 168
motorSpeed = constrain(motorSpeed + SPD_INCREMENT, 0, 255);
}
else if (command == 224) { // +번 // REW 224
motorSpeed = constrain(motorSpeed - SPD_INCREMENT, 0, 255);
}
else if (command == 2) { // >> // + 2
digitalWrite(IN1_PIN, HIGH);
digitalWrite(IN2_PIN, LOW);
}
else if (command == 34) { // << // TEST 34
digitalWrite(IN1_PIN, LOW);
digitalWrite(IN2_PIN, HIGH);
}
else if (command == 104) { // 0 // 0 104
servo.write(0);
}
else if (command == 152) { // 100+ // - 152
servo.write(90);
}
else if (command == 176) { // 200+ // C 176
servo.write(180);
}
analogWrite(ENA_PIN, motorSpeed);
Serial.print("Motor speed:\t");
Serial.println(motorSpeed);
Serial.println();
IrReceiver.resume(); // Receive the next value
}
}
ENA IN1 IN2