roboforum.ru

Технический форум по робототехнике.

Считывание PPM с приемника, на прерываниях.

Считывание PPM с приемника, на прерываниях.

frwind » 13 фев 2012, 18:24

Подскажите пожалуйста как организовать считывание PPM с приемника от радиоуправления, достаточно 2х каналов, на прерываниях или еще какие нибудь варианты, на Атмега168.
PulseIn не предлагать, слишком медленно работает.

Re: Считывание PPM с приемника, на прерываниях.

=DeaD= » 13 фев 2012, 21:19


Re: Считывание PPM с приемника, на прерываниях.

wallera » 13 фев 2012, 23:37

Вопрос для меня тож интересный есть два передатчка один как раз с PPM E_SKY
4 канальный , вот нагуглил http://arduino.cc/playground/Code/ReadReceiver

Re: Считывание PPM с приемника, на прерываниях.

NeON79 » 14 фев 2012, 00:49

http://www.nest.org.ru/2011/12/17/ardiu ... #more-4247
https://github.com/kiuz/PPM-Signal-Reader-ARDUINO

ТО, что нагуглилось навскидку. Дайте знать, что из всего предложенного наиболее "оно". Спасибо.

Re: Считывание PPM с приемника, на прерываниях.

frwind » 17 фев 2012, 12:56

=DeaD= писал(а):Возможно это оно?

http://www.arduino.cc/cgi-bin/yabb2/YaB ... 655547/3#3

Постоянно увеличивается число

42208
96220
150228
204236
258240
330252
384264
438268

При отключение приемника, счет останавливается
Код: Выделить всёРазвернуть
int injPin = 3; //Pin connected to injector's ground wire
volatile unsigned long injTime; // When accessing this in setup or loop (or anything called by either) interrupts must be disabled

void setup()
{
  pinMode(injPin, INPUT);
  digitalWrite (injPin, HIGH);  //Pull-up pin - as our injector is driven by connecting it to ground, i suppose i need to pull-up pin to get it's value as 1 when injector is turned off
  attachInterrupt(1, pik, CHANGE);  //interrupt on front changing
Serial.begin(9600);
}

void loop()
{
Serial.println(injTime);
delay (50);
}

void pik()
{
unsigned long injTime1;  //Time of front raising
unsigned long injTime2;  //Time of front falling

if ( digitalRead( injPin ) == LOW ) //Or i need to digitalRead it first? YES.
{
  injTime1 = micros(); //get time of pulse going down
}
else
{
  injTime2 = micros();  //get time of pulse going up
  injTime = injTime2 - injTime1;  //measure time between down and up
}



Добавлено спустя 15 минут 39 секунд:
wallera писал(а):Вопрос для меня тож интересный есть два передатчка один как раз с PPM E_SKY
4 канальный , вот нагуглил http://arduino.cc/playground/Code/ReadReceiver


Выдает

PinChangeInt ReciverReading test

И все, тишина, не на что не реагирует.

Добавлено спустя 21 минуту 11 секунд:
NeON79 писал(а):http://www.nest.org.ru/2011/12/17/ardiuno-%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA%D0%B0-ppmint/#more-4247
https://github.com/kiuz/PPM-Signal-Reader-ARDUINO

ТО, что нагуглилось навскидку. Дайте знать, что из всего предложенного наиболее "оно". Спасибо.



Эти примеры считывают смешанный PPM типа как выходит из тренерского разъема на передатчике.
По первой ссылки при компиляции ругается на

Код: Выделить всёРазвернуть









In file included from D:\arduino-0021\libraries\PPMint\PPMint.cpp:7:
D:\arduino-0021\libraries\PPMint/PPMint.h:10:21: error: Arduino.h: No such file or directory
In file included from D:\arduino-0021\libraries\PPMint\PPMint.cpp:7:
D:\arduino-0021\libraries\PPMint/PPMint.h:24: error: 'uint8_t' does not name a type
D:\arduino-0021\libraries\PPMint/PPMint.h:25: error: 'uint8_t' does not name a type
D:\arduino-0021\libraries\PPMint/PPMint.h:27: error: 'boolean' does not name a type
D:\arduino-0021\libraries\PPMint\PPMint.cpp: In member function 'void PPMint::setup()':
PPMint:19: error: 'prevRealRaw' was not declared in this scope
PPMint:20: error: 'currentChannel' was not declared in this scope
PPMint:22: error: 'sync' was not declared in this scope
PPMint:24: error: 'INPUT' was not declared in this scope
PPMint:24: error: 'pinMode' was not declared in this scope
PPMint:26: error: 'RISING' was not declared in this scope
PPMint:26: error: 'attachInterrupt' was not declared in this scope
PPMint:28: error: 'delay' was not declared in this scope
D:\arduino-0021\libraries\PPMint\PPMint.cpp: In member function 'void PPMint::PPMinterrupt()':
PPMint:34: error: 'micros' was not declared in this scope
PPMint:38: error: 'sync' was not declared in this scope
PPMint:39: error: 'currentChannel' was not declared in this scope
PPMint:42: error: 'sync' was not declared in this scope
PPMint:44: error: 'currentChannel' was not declared in this scope
PPMint:46: error: 'currentChannel' was not declared in this scope


Второй вариант с kiuz / PPM-Signal-Reader-ARDUINO работает,
надо проверить по скорости будет успевать или нет.

Добавлено спустя 49 минут 50 секунд:
Второй вариант с kiuz / PPM-Signal-Reader-ARDUINO работает,
Код: Выделить всёРазвернуть
   //initial value
   initialsignal = pulseIn(channelpin, HIGH);

   delay(2000);

В итоге тормозит.

Добавлено спустя 2 часа 52 минуты 35 секунд:
Просмотрев выше данные ссылки и разобравшись немного с прерываниями и временем, вот что получилось.
На прерывании, считывает с D3, используя INT1, для одного канала.
Если надо два, просто добавляем второй канал на D2 INT0 и тоже все работает.
Как добавить еще каналов, не разбирался, ту что нужно было выполнить задачу, реализовал, все работает, четко с двумя каналами.

Добавлены строчки
Код: Выделить всёРазвернуть
    if(ms>2200)  // fix time bug 
    ms=tmp;        // fix time bug
    tmp=ms;        // fix time bug

Без них через 21-22 опроса вылазит время в районе 16384, поэтому ввел эти три строки чтобы убивать его.
Почему оно выскакивает, что то внутренее еще работает и дает задержку?



Код: Выделить всёРазвернуть
// PPM read from receiver, D3, 1 ch, <frwind>
int Pin = 3; //PPM in for INT1
volatile unsigned long lt, ct, ms,tmp;

void setup(){
  pinMode(Pin, INPUT);
  digitalWrite (Pin, HIGH);      //Pull-up pin
  attachInterrupt(1, ppm, CHANGE);  //PPM read interrupt
Serial.begin(9600);
}

void loop(){
Serial.println(ms); // ms = PPM ms
}

void ppm() {    // PPM read interrupt
  ct = micros(); // read current time
  ms=ct-lt; // ms = current time - last time
  lt=ct; // last time
    if(ms>2200)  // fix time bug
    ms=tmp;        // fix time bug
    tmp=ms;        // fix time bug


Re: Считывание PPM с приемника, на прерываниях.

Alecs_2000 » 30 апр 2015, 16:31

Есть машинка на ру , решил сделать свет для нее, под руку попалась ардуино мини, взял скетч с последнего поста. дописал, что я хочу, но! так как я начинающий, и всех лазеек не знаю, возник затык с включением света задней передачи.
алгоритм таков. жмем курок газа вперед , загораются фары ближнего\дальнего света. жмем назад загораются стопаки, отпускаем курок в нейтраль потом снова назад, стопы не должны загораться, должна гореть подсветка заднего хода! которую пока не смог сообразить как включать. выручайте! пните в нужном направлении.

Код: Выделить всёРазвернуть
// PPM read from receiver
int rul = 3; //PPM in for INT1
int gaz = 2; //PPM in for INT2
int gabar_stop1 = 9;
int gabar_stop2 = 10;

int left1 = 14;
int left2 = 15;
int right1 = 16;
int right2 = 17;

int fara1 = 5;
int fara2 = 6;
int fara3 = 7;
int fara4 = 8;


int zx = 12 ; // задний ход

volatile unsigned long lt, ct, ms_rul,tmp, lt1, ct1, ms_gaz,tmp1, maxgaz, mingaz, maxrul, minrul,mig,far ;

volatile  unsigned long zad, zad1 ;


void setup(){
  pinMode(rul, INPUT);
  pinMode(gaz, INPUT);
  
  pinMode (gabar_stop1, OUTPUT);
  pinMode (gabar_stop2, OUTPUT);
  
  pinMode (zx, OUTPUT);
  
  pinMode (fara1, OUTPUT );
  pinMode (fara2, OUTPUT );
  pinMode (fara3, OUTPUT );
  pinMode (fara4, OUTPUT );
  
  pinMode (left1, OUTPUT);
  pinMode (left2, OUTPUT);
  pinMode (right1, OUTPUT);
  pinMode (right2, OUTPUT);
  
 
  
  digitalWrite (gabar_stop1, LOW);
  digitalWrite (gabar_stop2, LOW);

  digitalWrite (zx, LOW);
  
  digitalWrite (left1, LOW);
  digitalWrite (left2, LOW);
  digitalWrite (right1, LOW);
  digitalWrite (right2, LOW);

  
  digitalWrite (rul, HIGH);      //Pull-up pin
  digitalWrite (gaz, HIGH);      //Pull-up pin
  
  attachInterrupt(0, rul_ppm, CHANGE);  //PPM read interrupt
  attachInterrupt(1, gaz_ppm, CHANGE);
  
  maxgaz=1500; // переменная включения фар;
  mingaz=1400; // переменная включения стопов;
  maxrul=1500; // переменная включения правого поворота;
  minrul=1450; // переменная включения левого поворота ;
  mig=0; // переменная для мигания поворотами;
  far=0; // переменная для плавного зажигания средних фар;
zad=1;
  
  
 Serial.begin(9600);
}

void loop()
{
  
  
 
 
 
 Serial.println();
// Serial.println(ms_gaz); // ms = PPM ms
//  Serial.println(ms_rul);
 Serial.println(zad);
Serial.println(zad1);

                      

                          
 if (ms_gaz < mingaz && zad==0) //включение стопов
                                     { analogWrite(gabar_stop1, 255 );
                                       analogWrite(gabar_stop2, 255 );
                                     
                                     }
       
                              else
    
                                      { analogWrite(gabar_stop1, 10);
                                        analogWrite(gabar_stop2, 10 );
                                      
                                      } 

 // включение заднего хода               
 if ( zad>=2) {digitalWrite (zx, HIGH);

              } 
                  else
                          
              {
                 digitalWrite (zx, LOW);
                          
              }
     
//включение фар

 if (ms_gaz > maxgaz)
       {analogWrite (fara1, far);
        analogWrite (fara2, far); 
   
      if (far < 255) far++;
       }
                    else
                    { 
                    analogWrite (fara1, 2);
                    analogWrite (fara2, 2);
                   far=5;
                   
                    } 
                 
// мигание поворотами

if (mig>=110) mig=0;

if (ms_rul< minrul ) {mig++; digitalWrite (left1, HIGH); }
                       else { digitalWrite (left1, LOW);}
if (ms_rul< minrul && mig >= 50) {digitalWrite (left1, LOW);}

if (ms_rul> maxrul ) {mig++; digitalWrite (right1, HIGH); }//
                       else { digitalWrite (right1, LOW);}
if (ms_rul> maxrul && mig >= 50) {digitalWrite (right1, LOW);}                       

}

void gaz_ppm() {    // PPM read interrupt
 ct = micros(); // read current time
 ms_gaz=ct-lt; // ms = current time - last time
 lt=ct; // last time
 if(ms_gaz>2200)  // fix time bug
   ms_gaz=tmp;        // fix time bug
   tmp=ms_gaz;        // fix time bug
}    
void rul_ppm() {    // PPM read interrupt
 ct1 = micros(); // read current time
 ms_rul=ct1-lt1; // ms = current time - last time
 lt1=ct1; // last time
 if(ms_rul>2200)  // fix time bug
   ms_rul=tmp1;        // fix time bug
   tmp1=ms_rul;        // fix time bug
}    
 



Re: Считывание PPM с приемника, на прерываниях.

Alecs_2000 » 13 июл 2015, 13:39

так ни кто и не подскажет???


cron
Rambler\'s Top100 Mail.ru counter