生活随笔
收集整理的這篇文章主要介紹了
Arduino驱动直流电机风扇
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??時隔多年,重拾Arduino,先拿直流電機風扇找一下手感。配套的東西如下圖所示:直流電機、控制板、風扇、架子。 ??裝好之后的效果如下圖所示。 ??本文參照參考文獻中的示例代碼進行測試。參考文獻中的代碼主要通過按鈕控制風扇的不同轉速,本文中對代碼進行了簡化,為了測試程序的有效性,先在代碼中寫死轉速,代碼如下所示:
const int motorIn1
= 9 ;
const int motorIn2
= 10 ; #define rank
150 void
setup ( ) { pinMode ( motorIn1
, OUTPUT
) ; pinMode ( motorIn2
, OUTPUT
) ; Serial
. begin ( 9600 ) ;
} void
loop ( ) { clockwise ( rank
) ;
} void
clockwise ( int Speed
)
{ analogWrite ( motorIn1
, 0 ) ; analogWrite ( motorIn2
, Speed
) ;
}
??程序效果如下所示,代碼上傳到到Arduino后,風扇即開始轉動。 ??為了能控制轉速,對上述代碼進行改造,可以通過串口與Arduino進行通信,設置電機的轉速。詳細的代碼如下所示。需要注意的是,使用Arduino IDE中的串口監視器進行通信時,需要設置成沒有結束符模式。
#define SPEED_COMMAND
"SPD"
#define NUM_LENGTH
3
#define SPLIT_CHAR
';' #define RECEIVE_STAGE
0
#define EXECUTE_STAGE
1
#define OBSERVE_STAGE
2 #define MAX_CHARS
49 char buffer
[ MAX_CHARS
+ 1 ] ;
int charIndex
= 0 ; int currentStage
;
int curSpeed
= 0 ; const int motorIn1
= 9 ;
const int motorIn2
= 10 ; #define rank
150 void
setup ( ) { pinMode ( motorIn1
, OUTPUT
) ; pinMode ( motorIn2
, OUTPUT
) ; Serial
. begin ( 9600 ) ; currentStage
= RECEIVE_STAGE
; Serial
. println ( "Ready" ) ;
} void
loop ( ) { switch
( currentStage
) { case RECEIVE_STAGE
: ReceiveCommand ( ) ; break ; case EXECUTE_STAGE
: if ( Serial
. available ( ) > 0 ) { currentStage
= RECEIVE_STAGE
; } else if ( strncmp ( buffer
, SPEED_COMMAND
, NUM_LENGTH
) == 0 ) { char
* pInt
= & buffer
[ NUM_LENGTH
+ 1 ] ; curSpeed
= atoi ( pInt
) ; currentStage
= OBSERVE_STAGE
; } break ; case OBSERVE_STAGE
: if ( Serial
. available ( ) > 0 ) { currentStage
= RECEIVE_STAGE
; } else { clockwise ( curSpeed
) ; } break ; }
} void
clockwise ( int Speed
)
{ analogWrite ( motorIn1
, 0 ) ; analogWrite ( motorIn2
, Speed
) ;
} void
ReceiveCommand ( )
{ if ( Serial
. available ( ) > 0 ) { char ch
= Serial
. read ( ) ; if ( ( charIndex
< MAX_CHARS
) && ( ch
!= SPLIT_CHAR
) ) { buffer
[ charIndex
++ ] = ch
; } else { buffer
[ charIndex
] = 0 ; charIndex
= 0 ; currentStage
= EXECUTE_STAGE
; Serial
. print ( "received command is " ) ; Serial
. println ( buffer
) ; } }
}
??本文主要是初步介紹直流電機風扇的驅動方式,如果更深入的控制直流電機,可以在百度中自行搜索了解。
參考文獻: [1]《基于傳感器開發套件玩轉Arduino編程》
總結
以上是生活随笔 為你收集整理的Arduino驱动直流电机风扇 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。