工控板驱动步进电机,是项目中常用的场景。今天试着用三个IO驱动步进电机:
【硬件准备】
1、开发板。
2、步进电机驱动器,前面活动中申请到【免费试用13期】TB5128FTG步进电机驱动套件
3、步进电机一个。
4、杜绑线。
5、可调数控电源。
【接线原理图】
【程序】
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
FILE *fp=NULL;
int init_io(void)
{
fp = fopen("/sys/class/gpio/export", "w");
if (fp == NULL)
{
perror("fopen");
return -1;
}
fprintf(fp,"%d",24);
fclose(fp);
fp = fopen("/sys/class/gpio/export", "w");
if (fp == NULL)
{
perror("fopen");
return -1;
}
fprintf(fp,"%d",25);
fclose(fp);
fp = fopen("/sys/class/gpio/export", "w");
if (fp == NULL)
{
perror("fopen");
return -1;
}
fprintf(fp,"%d",26);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio24/direction","w");
fprintf(fp,"out");
fclose(fp);
fp = fopen("/sys/class/gpio/gpio25/direction","w");
fprintf(fp,"out");
fclose(fp);
fp = fopen("/sys/class/gpio/gpio26/direction","w");
fprintf(fp,"out");
fclose(fp);
}
void io_ena(int value)
{
fp = fopen("/sys/class/gpio/gpio26/value", "w");
fprintf(fp,"%d", value);
fclose(fp);
}
void io_Dir(int value)
{
fp = fopen("/sys/class/gpio/gpio25/value", "w");
fprintf(fp,"%d", value);
fclose(fp);
}
void close_IO(void)
{
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp,"%d",24);
fclose(fp);
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp,"%d",25);
fclose(fp);
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp,"%d",26);
fclose(fp);
}
void pwm_PULL(int times)
{
int i;
for (i = 0; i < times; i++)
{
fp = fopen("/sys/class/gpio/gpio24/value", "w");
fprintf(fp,"%d", 1);
usleep(10);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio24/value", "w");
fprintf(fp,"%d", 0);
usleep(10);
fclose(fp);
}
}
int main(void)
{
init_io();
io_ena(1);//diable en
io_Dir(1); //正转
io_ena(0);
pwm_PULL(500);
sleep(1);
io_Dir(0); //正转
pwm_PULL(500);
close_IO();
return 0;
}
编译上传开发板,运行程序,就可以实现电机的正反转。
更多回帖