直流电机(DC—Direct Current motor)是最常见的电机类型。直流电动机通常只有两个引线,一个正极和一个负极。如果将这两根引线直接连接到电池,电机将旋转。如果切换引线,电机将以相反的方向旋转。但是为了实现正反转,我们用双H桥电机驱动模块来实现。
#define IN_1 PA2 // the INx the PWM pin is attached to
#define IN_2 PA3
#define BUTTON_PIN PA1 //the button pin the PA1 pin is attached to.
//void motor_compare();
//void ButtonControl();
int16_t Speed = 135; //Reduce motor speed range within visual range.
int flag = 1; // flag bit.
int buttonState = 0; // Indicates the state of the key (press/release).
int lastButtonState = 0; // Indicates the status of the. last key.
unsigned long lastDebounceTime = 0; // Indicates the time of the last key shake elimination.
unsigned long debounceDelay = 10; // Indicates the delay time of key shake elimination.
void motor_compare(int16_t speed ) //Control motor speed.
{
if(flag == 0)
{
analogWrite(IN_1,speed);
analogWrite(IN_2,0);
}
else
{
analogWrite(IN_1,0);
analogWrite(IN_2,speed);
}
Serial.printf("Motor Speed:%d\n",speed);
}
void ButtonControl() //
{
/*
When the key status changes each time,
check the time interval since the last buffeting.
If the delay exceeds the set time,
the key status variable is updated according to the current key status
and the corresponding operation is performed.
*/
int reading = digitalRead(BUTTON_PIN);
if(reading != lastButtonState)
{
lastDebounceTime = millis();
}
if((millis() - lastDebounceTime) > debounceDelay)
{
if(reading != buttonState)
{
buttonState = reading;
if(buttonState == HIGH)
{
Speed += 20;
if(Speed > 255)
{
Speed = 135;
flag = !flag;
//Serial.printf("%d\n",flag); //Detects whether to enter the program.
}
motor_compare(Speed);
}
}
}
lastButtonState = reading;
}
void setup()
{
Serial.begin(115200);
//initialize the pin as an output.
pinMode(IN_1,PWM_OUT);
pinMode(IN_2,PWM_OUT);
// initialize the pushbutton pin as an input.
pinMode(BUTTON_PIN,INPUT_PULLUP); //如果有外接按键小模块,可设置为INPUT.
}
void loop()
{
ButtonControl();
}
最后等待上传需要十几秒的时间,显示以下即表示成功
你会看见每当按键按下一次,电机正转速度在逐渐变快直至达到最大速度之后,又从正转变成反转并且速度逐渐加快.依次循环.
I suggest working on expanding your example. Add a servo and a proportional control element. And then you can use it as a building block for RC models. We will consider data transmission over the radio channel in the near future
@AnatolSher Well,I'll try it.
@Level Das model :)
@Level pinMode(BUTTON_PIN,INPUT);
Should be replaced with pinMode(BUTTON_PIN,INPUT_PULLUP);
Because such a button connection requires a pull-up to the power
@AnatolSher oh, indeed. Thanks for the pointer.