Skip to content

Instantly share code, notes, and snippets.

@7m4mon
Created July 13, 2016 14:05
Show Gist options
  • Save 7m4mon/da5be22c0fdeaea331fff0e5b00400ca to your computer and use it in GitHub Desktop.
Save 7m4mon/da5be22c0fdeaea331fff0e5b00400ca to your computer and use it in GitHub Desktop.
/***********************************************************
STEPPER.C
ステッピングモーターをコントロールする
1つのユニポーラステッピングモーターをPORTBの0~3に接続。
ボリュームかパルスで制御
ボリュームは中点あたりでオフ、右に回すと右回転、左に回すと左回転
パルス制御の場合、方向とパルスの2ピン使う
CCSのサンプルプログラムEX_STEP.CをベースにPIC16FF88向けに改造した。
***********************************************************/
#include <16F88.h>
#device ADC=8 //8bit A/D
#define MVAL 10 //ボリュームの変異を無視する範囲
//コンフィギュレーション設定
#fuses INTRC_IO,NOWDT,PUT,NOPROTECT,NOMCLR
#use delay(CLOCK = 4000000) //4MHz
#define VOL_A 0 //PIN_A0
#define PLUSE_A PIN_A1
#define DIR_A PIN_A7
#define STAT_OUT PIN_A3
#define MODE_SEL PIN_A2
#define ONE_STEP 1
/* ステッピングモーターのステート */
BYTE const POSITIONS[8] = {0b0101,
0b0001,
0b1001,
0b1000,
0b1010,
0b0010,
0b0110,
0b0100};
int stepper_state;
void drive_stepper(int speed, short dir, int steps) {
int i; // for conter
output_high(STAT_OUT);
for(i=0; i<steps; ++i) {
delay_ms(speed);
output_b( POSITIONS[ stepper_state ]);
if(dir != 0)
stepper_state=(stepper_state+1)&(sizeof(POSITIONS)-1);
else
stepper_state=(stepper_state-1)&(sizeof(POSITIONS)-1);
}
output_low(STAT_OUT);
}
void main(){
short dir;
int value; //for adc
/* 初期設定 */
// A/Dコンバータ初期設定 AN0
setup_adc_ports(sAN0 |VSS_VDD);
setup_adc(adc_clock_internal);
set_adc_channel( 0 );
setup_adc(ADC_CLOCK_DIV_8);
set_tris_a(0b10110111); //A3とA6は出力
set_tris_b(0b00000000); //all output
output_b(0); //全部L
output_low(STAT_OUT);
output_high(PIN_A6);
stepper_state = 0;
while(true){
while(input(PLUSE_A) && !input(MODE_SEL)) ;
if(input(MODE_SEL)){ //モードスイッチがマニュアル操作モードだったら
/* ボリュームを読み込んで */
value=read_adc();
if(value<(0x80 -MVAL)){
drive_stepper(value +1 ,0,1); //128 ~ 1
}else if(value>(0x80+MVAL)){
drive_stepper(128-(value-128),1,8); //128~255を0~127に直した後、128から引く(128~1になる)
}else{
output_b(0); //開放
}
}else{
// while(input(PLUSE_A)) ; //パルスの入力待ち
dir = input(DIR_A); //方向の読み取り
drive_stepper(0,dir,ONE_STEP);
while(!input(PLUSE_A)) ; //パルスの立ち上がり待ち
delay_ms(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment