//-----------------------------------------------
//ライブラリ宣言
#include<Stepper.h>
//-----------------------------------------------
//-----------------------------------------------
//変数定義
const int D = 50; //プーリー直径
const float STEPANG = 1.8; //ステップ角
const int WIDTH = 420; //ステージ横幅
const int T = 3; //移動時間
const float TA = 0.1; //加速時間
const int STEP = 360 / STEPANG; //一回転のステップ数
const int LIGHT_NUM = 7; //光受光センサー数
const int LIGHT_PIN[LIGHT_NUM] = {2,3,4,5,6,7,8}; //光受光センサーピン
#define pi 3.14 //円周率
#define AP 9 //ステッピングモーターピン
#define AM 10 //ステッピングモーターピン
#define BP 11 //ステッピングモーターピン
#define BM 12 //ステッピングモーターピン
#define LIM_SEN1 A0 //原点リミットスイッチ
#define LIM_SEN2 A1 //上限リミットスイッチ
//-----------------------------------------------
//-----------------------------------------------
//ライブラリ変数
Stepper stepm(STEP,AP,AM,BP,BM);
//-----------------------------------------------
void setup()
{
Serial.begin(9600);
stepm.setSpeed(30); //ステッピングモーター初期速度
pinMode(LIM_SEN1,INPUT_PULLUP);
pinMode(LIM_SEN2,INPUT_PULLUP);
for(int i = 0; i < 7; i++)
{
pinMode(LIGHT_PIN[i], INPUT_PULLUP);
}
step_set(); //ステッピングモーター原点セット
}
void step_set()
{
while(1)
{
if(digitalRead(LIM_SEN1) == LOW) { break; }
stepm.step(-1);
}
}
void step_move(int rpm, int stepping, float movdist)
{
int pulse_count = 0; //パルス数カウント
stepm.setSpeed(rpm);
while(1)
{
if(digitalRead(LIM_SEN1) == LOW || digitalRead(LIM_SEN2) == LOW) { break; }
if(pulse_count == stepping) { break; }
stepm.step(movdist / abs(movdist));
pulse_count++;
}
}
void loop()
{
static float pulse_num = 0.0; //パルス数
static float plspeed = 0.0; //パルス速度
float movdist = 0.0; //移動距離
static int rpm = 0; //回転数
static int stepping = 0; //移動距離分のステップ数
static int light_old = 0; //受光センサー一つ前の入力
static int light_new = 0; //受光センサー現在の入力
int i = 0;
while(1)
{
if(i > LIGHT_NUM) { i = 0; }
if(digitalRead(LIGHT_PIN[i]) == LOW) { light_new = i; break; }
i++;
}
delay(500);
movdist = (light_new * 60) - (light_old * 60);
light_old = light_new;
if(movdist != 0)
{
pulse_num = (abs(movdist) / (D * pi)) * (360 / STEPANG);
plspeed = pulse_num / (T - TA);
rpm = (STEPANG / 360) * plspeed * 60;
stepping = ((abs(movdist) * 360) / (pi * D)) / STEPANG;
step_move(rpm, stepping, movdist);
}
}