xbee communication for UWB quadcopter project Originally by Greg Abdo Forking to reduce impact of interrupt by moving packetbuilder out of the interrupt and letting be handled in the main loop
Fork of com by
com.cpp
- Committer:
- oprospero
- Date:
- 2014-10-15
- Revision:
- 18:19bcb2dbf3c8
- Parent:
- 17:acef0fb07510
- Child:
- 19:dc9d18037565
File content as of revision 18:19bcb2dbf3c8:
#include "com.h" //#define DEBUG_COM #ifdef DEBUG_COM #define NL "\n\r" #define PRINT(x) xbee.printf(x) //Serial.print(x) #define PRINTF xbee.printf //Serial.print(x, y) #define PRINTLN(x) PRINT(x);PRINT(NL) #define START timerCom.start(); #define STOP timerCom.stop() #define RESET timerCom.reset() #define READ timerCom.read_us() #define GET(x) x = READ #else #define PRINT(x) #define PRINTF(x, y) #define PRINTLN(x) #define PRINTLNF(x, y) #define START #define STOP #define RESET #define READ #define GET(x) #endif com::com(PinName tx, PinName rx): xbee(tx,rx) { xbee.baud(BAUDRATE); xbee.attach(this,&com::callback); } com::~com() { } void com::callback() { while(xbee.readable()) { char data = xbee.getc(); // xbee.putc(data); rxBuffer.add(data); } } bool com::isData() { static char packetIndex = 0; static char pack_cmd = 0; static char pack_value[2] = {0,0}; static char pack_seq = 0; static char pack_checksum = 0; __disable_irq(); while ( !rxBuffer.isEmpty() ) { char data = rxBuffer.pop(); __enable_irq(); // PRINTF("d: %d \n\r", data); switch (packetIndex) { case 0: { if ( data == 255 ) packetIndex++; break; } case 1: { if ( data < 13 ) { pack_cmd = data; packetIndex++; } else packetIndex = 0; break; } case 2: { pack_value[1] = data; packetIndex++; break; } case 3: { if ( data < 128 ) { pack_value[0] = data; packetIndex++; } else packetIndex = 0; break; } case 4: { pack_seq = data; packetIndex++; break; } case 5: { short temp = pack_value[0] + pack_cmd; pack_checksum = data; if ( temp == pack_checksum ) { short * ackPacket = new short[2]; ackPacket[0] = pack_cmd; ackPacket[1] = pack_seq; txBuffer.add( ackPacket ); // Ack the packet with sequence nuber. short * array = new short[2]; array[0] = pack_cmd; array[1] = pack_value[1] * 128 + pack_value[0]; cmdBuffer.add( array ); } packetIndex = 0; break; } default: packetIndex = 0; break; } __disable_irq(); } __enable_irq(); return !cmdBuffer.isEmpty(); } short * com::read() { if ( !cmdBuffer.isEmpty() ) return cmdBuffer.pop(); else return NULL; } bool com::rdy2ack() { return !txBuffer.isEmpty(); } void com::sendACK() { if( !txBuffer.isEmpty()) { short * pkt = txBuffer.pop(); __disable_irq(); write(pkt[0],pkt[1]); //may need to disable interrupt __enable_irq(); delete[] pkt; } } void com::write( short command, short seq ) { xbee.putc( 255 ); // End of message. xbee.putc( (char)command ); // Command xbee.putc( (char) seq); // Second 8 bits in array. xbee.putc( (char) command + seq ); // Checksum array[0] + array[1]. }