esp32 arduino 蓝牙 使用uln2003 驱动四相五线步进电机备忘
代码很简单,直接能看明白
// Load libraries
#include "BluetoothSerial.h"
// Check if Bluetooth configs are enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
// Bluetooth Serial object
BluetoothSerial SerialBT;
// GPIO where LED is connected to
const int p1 = 12;
const int p2 = 13;
const int p3 = 25;
const int p4 = 26;
int angle = 0;
char inputdata = 0; //Variable for storing received data
void setup() {
// 初始化引脚
pinMode(p1, OUTPUT);
pinMode(p2, OUTPUT);
pinMode(p3, OUTPUT);
pinMode(p4, OUTPUT);
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
//初始化蓝牙
Serial.begin(115200);
// Bluetooth device name
SerialBT.begin("ESP32");
Serial.println("The device started, now you can pair it with bluetooth!");
}
void right() {
angle = angle + 45;
for (int i = 0; i < 16; i++) {
digitalWrite(p1, HIGH);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
delay(10);
digitalWrite(p1, LOW);
digitalWrite(p2, HIGH);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
delay(10);
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, HIGH);
digitalWrite(p4, LOW);
delay(10);
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, HIGH);
delay(10);
}
}
//左转
void left() {
angle = angle - 45;
for (int i = 0; i < 16; i++) {
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, HIGH);
delay(10);
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, HIGH);
digitalWrite(p4, LOW);
delay(10);
digitalWrite(p1, LOW);
digitalWrite(p2, HIGH);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
delay(10);
digitalWrite(p1, HIGH);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
delay(10);
}
}
// 回原位并拉低所有电平
void stoprun() {
int zero = angle / 45;
Serial.print("zero:");
Serial.print(zero);
if (zero > 0) {
for (int i = 0; i<zero; i++) {
Serial.print("stop:left\n");
left();
}
}
if (zero < 0) {
for (int i = 0; i<-zero; i++) {
right();
Serial.print("stop:right\n");
}
}
digitalWrite(p1, LOW);
digitalWrite(p2, LOW);
digitalWrite(p3, LOW);
digitalWrite(p4, LOW);
}
void loop() {
if (SerialBT.available() > 0) // Send data only when you receive data:
{
inputdata = SerialBT.read(); //Read the incoming data & store into data
Serial.print(inputdata);
Serial.print("\n");
if (angle / 360 == 1) {
angle = 0;
}
//接收到1右转45度
if (inputdata == '1')
{
right();
SerialBT.printf("%s:%d", "right", angle);
}
//接收到0拉低所有电平,回原位
else if (inputdata == '0')
{
stoprun();
SerialBT.print("LED OFF\n");
}
//接受到2左转
else if (inputdata == '2')
{
left();
SerialBT.print("LED OFF\n");
}
}
}