Infrared Rays library

Dependents:   mbed_IR

See http://developer.mbed.org/users/yasuyuki/notebook/IRmbed/

IR.cpp

Committer:
yasuyuki
Date:
2014-06-26
Revision:
0:c74b212c3cbf
Child:
1:71ca050c4d05

File content as of revision 0:c74b212c3cbf:

//**********************
// IR.cpp for mbed
//
// IR ir(P0_12);
//
// (1)NEC format
// IR carrier=38KHz
// Time unit=0.56ms
// logical 0 = on 1T + off 1T
// logical 1 = on 1T + off 3T
// reader=on 16T + off 8T
// stop=on 1T + 8ms
// frame=108ms
//
// (2)Standard IR format
// IR carrier=33 - 40KHz
// Time unit=0.35 - 0.50ms
// logical 0 = on 1T + off 1T
// logical 1 = on 1T + off 3T
// reader=on 8T + off 4T
// trailer=on 1T + 8ms
//
// (3)SONY format
// IR carrier=40KHz
// Time unit=0.6ms
// logical 0 = off 1T + on 1T
// logical 1 = off 1T + on 2T
// reader=on 4T
//
// caution:
// no detecting repeat code, return bits=0;
//
// (C)Copyright 2014 All rights reserved by Y.Onodera
// http://einstlab.web.fc2.com
//**********************

#include "mbed.h"
#include "IR.h"

IR::IR (PinName irin) : _irin(irin){
    init();
}


void IR::init()
{
    _irin.mode(PullUp);
}

unsigned char IR::CountHigh(){

    unsigned char i=0;

    while(_irin==1);    // wait

    while(_irin==0){
        ++i;
        wait_us(26);
        wait_us(26);
        if(i==0) return 0;
    }
    // NEC:i=19*8=152, i*2*26.5us=8056us
    // STD:i=19*4=76,  i*2*26.5us=4028us
    // 1T:i=19*1=19

    return i;

}


unsigned char IR::CountLow(){

    unsigned char i=0;

    while(_irin==0);    // wait

    while(_irin==1){
        ++i;
        wait_us(26);
        if(i==0) return 0;
    }
    // NEC:i=19*8=152, i*26.5us=4028us
    // STD:i=19*4=76,  i*26.5us=2014us
    // 1T:i=19*1=19
    // 3T:i=19*3=57

    return i;

}


void IR::GetIR2(){

    unsigned char i,j;
    unsigned char k;

    bits=0;
    for(j=0;j<16;j++){
        for(i=0;i<8;i++){
            k = CountHigh()*2;
            if(mode==3){
                buf[j]>>=1;
                // Threschold = 35, 23 = 1T, 46 = 2T; for SONY
                buf[j]+=((k>30) ? 0x80: 0);
                ++bits;
            }
            k = CountLow();
            if(k==0){
                buf[j]>>=(8-i);
                return;
            }
            if(mode!=3){
                buf[j]>>=1;
                // Threschold = 38, 19 = 1T, 57 = 3T; for NEC
                // Threschold = 30, 15 = 1T, 45 = 3T; for STD
                buf[j]+=((k>30) ? 0x80: 0);
                ++bits;
            }
        }
    }

}


void IR::GetIR(){

    unsigned char i;

    i = CountHigh();    // Start
    mode=0;
    if(40<i){
        if(i<51){
            mode=3; // SONY, 46
        }else{
            if(100<i){
                mode=1; // NEC, 173
            }else{
                mode=2; // STD, 54-77
            }
        }
        i = CountLow();
        GetIR2();
    }

}