使用28BYJ-48步进电机制作电动调焦座的代码

//注意28BYJ-48为减速电机所以速度不会很快
//具体引脚不写了看图片吧
//使用arduino IDE自带的Stepper.h库文件
#include <Stepper.h>
#include <Keypad.h>

// 这里设置步进电机旋转一圈是多少步
#define STEPS 32

//设置步进电机的步数和引脚(随便连,只要下面的数字和实际的连线一致即可)
Stepper stepper(STEPS, 12, 13, 11,10 );//引脚要互换

//常规转速,还是微调转速.1是常规,5是微调。
int speedRadio = 1;
//控制电机转动的方向
int direction=0;

//矩阵键盘与arduino之间的接线如下图
//    Keypad Pin R1 –> Arduino Pin 2
//    Keypad Pin R2 –> Arduino Pin 3
//    Keypad Pin R3 –> Arduino Pin 4
//    Keypad Pin R4 –> Arduino Pin 5
//    Keypad Pin C1 –> Arduino Pin 6
//    Keypad Pin C2 –> Arduino Pin 7
//    Keypad Pin C3 –> Arduino Pin 8
//    Keypad Pin C4 –> Arduino Pin 9

const byte ROWS = 4; //4行
const byte COLS = 3; //3列

char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'#','0','*'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
    // 初始化串口,用于向终端输出调试信息
    Serial.begin(9600);

    // 设置电机的转速:每分钟为90步
    stepper.setSpeed(90);
}

void loop(){
    char key = keypad.getKey();

    //如果有输入
    if (key != NO_KEY){
        //打印读取到的字符,即键盘被按下的键
        Serial.println(key);

        if(key == '#'){
            speedRadio = 1;
        }else if(key == '*'){
            speedRadio = 5;
        }else {
            //将读取到的字符转换成整型,1是49,2是50等,所以要减去48。
            int ikey = int(key)-48;

            //如果是1到9之间,就转动该数字的ikey/4圈
            //一圈是2048个脉冲
            if(ikey >0 && ikey < 10){
                if(direction ==0){
                    stepper.step(-2048/ikey/speedRadio);
                }else{
                    stepper.step(2048/ikey/speedRadio);
                }
            }else if(ikey ==0){//用0设置逆时针或顺时针转动
                if(direction ==0){
                    direction = 1;
                }else{
                    direction = 0;
                }
            }
        }
    }
}

Author: bkdwei