Fork of TxIR

Fork of TxIR by Nordic Pucks

TxIR.cpp

Committer:
aleksanb
Date:
2014-07-09
Revision:
3:bc64c2d5bc26
Parent:
2:cc8371213c85

File content as of revision 3:bc64c2d5bc26:


/******************************************************************************
 * Low level infrared transmission
 * This library provides a low level interface to send IR commands. in principle
 * other higher level IR type remotes could be build on top of this. I wrote
 * this code to send IR commands to a Nikon camera, which it works rather well
 * for.
 *
 * Copyright (C) 2010 Ali Saidi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "mbed.h"
#include "TxIR.hpp"

Serial pc(USBTX, USBRX);

Timer timer;

bool
TxIR::txSeq(unsigned freq, unsigned len, const unsigned *data)
{
    // @todo a lock or semaphore should be used here
    if (inUse()) {
        return false;
    }
    _inUse = true;

    // keep a copy of the data, so it can't change
    int pos = 0;
    // setup the PWM
    txPin.write(0.0);
    txPin.period_us(freq);

    int times[len];
    for (int i=0; i<len; i++) {
        times[i] = 0;
    }

    int bit = 1;
    pc.printf("S\n");
    txPin.write(0.5);
    timer.start();

    int time = timer.read_us();
    int old_time = time;
    int dt = 0;

    while (pos < len) {
        // TODO: Handle timer overflow
        // Consider using GPIOTE
        old_time = time;
        time = timer.read_us();
        dt += time - old_time;

        while (dt > data[pos] && pos < len) {
            dt -= data[pos];
            bit = !bit;
            txPin.write(0.5 * bit);
            times[pos] = dt;
            pos++;
        }
    }

    timer.stop();
    pc.printf("Success, wrote %i/%i\n", pos, len);
    pc.printf("Miss timings: [%i", times[0]);
    for (int i=1; i<len; i++) {
        pc.printf(", %i", times[i]);
    }
    pc.printf("]\n");
    txPin.write(0);
    _inUse = false;
    return true;
}