Hi all ,
I wrote a simple code to read the pulses from the receiver and control the brushless motors for a quad-copter but it`s not running as expected .
the code :-
#include<Servo.h>
int ch[6] ;
Servo br[5] ;
void setup() {
for ( int i=1 ; i<=5 ; i++ )
pinMode(i, INPUT); // Channels pins
}
void loop() {
for ( int i=1; i<=5; i++ )
{
ch[i] = pulseIn(i, HIGH ); // Read the pulse width of all channels
}
if ( ch[5]<=1200 ) // DISARM
{
for ( int n=1 ; n<=4 ; n++ )
{
br[n].write(0);
br[n].detach();
}
}
if ( ch[3]<=1200 && ch[4]>=1200 ) // ARM
{
br[1].attach(8);
br[2].attach(9);
br[3].attach(10);
br[4].attach(11);
for ( int m=1 ; m<=4 ; m++ )
{
br[m].write(20);
}
delay(3000);
}
for ( int s=1 ; s<=5 ; s++ ) // map channels
{
ch[s]= map( ch[s] , 1100 , 1920 , 0 , 180 );
}
if ( ch[3]>20 ) // Throttle
{
for ( int s=0 ; s<=4 ; s++ )
{
br[s].write(ch[3]) ;
}
}
if ( ch[2]<90 ) // Roll
{
br[2].write((ch[3]-(ch[3]-ch[2])));
br[4].write((ch[3]+(ch[3]-ch[2]))) ;
}
if ( ch[2]>90 )
{
br[4].write((ch[3]-(ch[3]-ch[2])));
br[2].write((ch[3]+(ch[3]-ch[2]))) ;
}
if ( ch[1]<90 ) //Pitch
{
br[1].write((ch[3]-(ch[3]-ch[2])));
br[3].write((ch[3]+(ch[3]-ch[2]))) ;
}
if ( ch[1]>90 )
{
br[3].write((ch[3]-(ch[3]-ch[2])));
br[1].write((ch[3]+(ch[3]-ch[2]))) ;
}
}
The result is the that motors have random inputs and got random speeds !! i made sure all my connections are 100% correct .
then i wrote another code :-
#include <Servo.h>
Servo br11 , br9 ;
int ch3 ;
void setup ()
{
br11.attach(11) ;
br9.attach(9) ;
br11.write(20) ;
br9.write(20) ;
pinMode( 3 , INPUT ) ; // channel pin
delay(4000) ;
}
void loop ()
{
ch3 = pulseIn( 3 , HIGH ) ; // read the channel signal
ch3 = map( ch3 , 1000 , 2000 , 0 , 180 ) ;
br11.write(ch3) ;
br9.write(ch3);
}
and the result is that the 2 motors spin fast depending on ch3 value , slow down , then fast again , and slow down again and keeps doing this ! it seems like the pulseIn function have problems with .write function as when i remove the pulseIn function and control the motor using arduino only, it moves normally with the selected speed !
i made sure all connections are correct , batteries are fully charged , tested every motor alone without connecting the receiver to arduino ..... etc .
can anyone please tell me the problem and how can i fix it !
Thank you