arduino定时器控制舵机_Arduino学习经验(一)之解决舵机库和pwm输出冲突
一.前言
最近在公司學(xué)習(xí)Arduino?uno ,用它實(shí)現(xiàn)小車超聲波避障功能。實(shí)現(xiàn)的功能很簡單,就是在小車前方掛一個(gè)超聲波模塊,當(dāng)碰到障礙物時(shí),會(huì)通過舵機(jī)進(jìn)行擺頭,判斷兩邊的距離,進(jìn)行左右轉(zhuǎn)彎。但是碰到了這樣一個(gè)問題,舵機(jī)庫和pwm輸出沖突,當(dāng)舵機(jī)旋轉(zhuǎn)時(shí),pwm輸出函數(shù)analogWrite()不管用了。
二.解決
先分析一下問題產(chǎn)生的原因,我們之前如果想控制舵機(jī),比較常見的方法就是調(diào)用舵機(jī)庫:
#include
Servo myservo;? // create servo
object to control a
servo
// a maximum of eight servo objects can be created
int pos =
0;??? // variable to store the servo position
void
setup()
{
myservo.attach(9);? // attaches the servo on pin 9
to the servo object
}
void loop()
{
for(pos = 0; pos < 180; pos += 1)? // goes from 0 degrees to 180
degrees
{
// in steps of 1 degree
myservo.write(pos);
// tell servo to go to position in variable 'pos'
delay(15);
// waits 15ms for the servo to reach the position
}
for(pos
= 180; pos>=1; pos-=1)???? // goes from 180 degrees to 0
degrees
{
myservo.write(pos);
// tell servo to go to position in variable 'pos'
delay(15);
// waits 15ms for the servo to reach the position
}
}
這種做法非常方便,但是為什么會(huì)跟pwm沖突呢,因?yàn)樵贏rduino里的庫封裝里,它們都是用了同一個(gè)定時(shí)器1,T/C1: Pin9(OC1A)和Pin10(OC1B),所以會(huì)導(dǎo)致沖突,如何解決呢,可以在硬件上修改引腳。不費(fèi)事的辦法就是通過修改代碼來解決沖突。我們可以換一種方法來實(shí)現(xiàn)舵機(jī)的控制:
int servopin = 7;??? //定義舵機(jī)接口數(shù)字接口7 也就是舵機(jī)的橙色信號(hào)線。
void servopulse(int angle)//定義一個(gè)脈沖函數(shù)
{
int pulsewidth=(angle*11)+500;? //將角度轉(zhuǎn)化為500-2480的脈寬值
digitalWrite(servopin,HIGH);??? //將舵機(jī)接口電平至高
delayMicroseconds(pulsewidth);? //延時(shí)脈寬值的微秒數(shù)
digitalWrite(servopin,LOW);???? //將舵機(jī)接口電平至低
delayMicroseconds(20000-pulsewidth);
}
void setup()
{
pinMode(servopin,OUTPUT);//設(shè)定舵機(jī)接口為輸出接口
}
void loop()
{
//把值的范圍映射到0到165左右
for( int angle = 0;angle<180;angle+=10){
for(int i=0;i<50;i++)? //發(fā)送50個(gè)脈沖
{
servopulse(angle);?? //引用脈沖函數(shù)
} ? delay(1000); ?} }
直接通過延時(shí)函數(shù)來給舵機(jī)脈沖,達(dá)到控制的效果,因?yàn)锳rduino里延時(shí)函數(shù)delay()用的是定時(shí)器0,所以就不會(huì)沖突了。
總結(jié)
以上是生活随笔為你收集整理的arduino定时器控制舵机_Arduino学习经验(一)之解决舵机库和pwm输出冲突的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js寻找两个数组的差集_js求两个数组的
- 下一篇: matplotlib xticks 基于