リスト2-3-3.txt

■リスト2-3-3■

#include "mbed.h"

unsigned char rxFIFO[256], txFIFO[256], raw_data[6];
unsigned char rx_top, rx_end, tx_top, tx_end, phase;

RawSerial xbee(PA_2, PA_3);
DigitalOut myled(LED1);
int timer_value[5];
Ticker timer_setup;

void tx_fifo_check(){
    if(xbee.writeable() == 1){
        if(tx_top != tx_end){
            xbee.putc(txFIFO[tx_end]);
            ++tx_end &= 255;
        }
    }
}

int rx_fifo_check(){
    unsigned char data;
    if(rx_top != rx_end){
        data = rxFIFO[rx_end];
        ++rx_end &= 255;
        if (data < 33){
            phase = 0;
            return(1);
        }
        raw_data[phase] = data;
        if(++phase > 5) phase = 0;
        return(0);
    }
    return(0);
}

void rx_fifoset(void){
    rxFIFO[rx_top] = xbee.getc();
    ++rx_top &= 255;
}

void tx_fifoset(unsigned char data){
    txFIFO[tx_top] = data;
    ++tx_top &= 255;
}

unsigned char hex_conv(unsigned char data){
    data &= 15;
    if(data < 10) return(data+48);
    else return(data+55);
}

unsigned char conv_hex(unsigned char data){
    if((data > 47) && (data < 58)) return(data-48);
    else if((data > 64) && (data < 71)) return(data-55);
    return(0);
}

void tx_message(int data){
    int i;
    for (i=0; i<6; i++) tx_fifoset(hex_conv((data>>(4*(5-i))) & 15));
    tx_fifoset(13);
}

void timer_interrupt(){								// タイマ割り込み処理
    int i;
    for (i=0; i<5; i++) ++timer_value[i] &= 65535;
}

int main(){
    int i, j, sum;
    i = j = 0;
    rx_top = rx_end = tx_top = tx_end = phase = 0; 
    xbee.baud(38400);
    xbee.attach(&rx_fifoset, xbee.RxIrq);
    for (i=0; i<5; i++) timer_value[i] = 0;
    timer_setup.attach_us(&timer_interrupt, 100);		// タイマ割り込みの設定=100μ秒
    while(1){
        tx_fifo_check();
        if(rx_fifo_check() == 1){
            sum = 0;
            for (i=0; i<6; i++) sum += conv_hex(raw_data[i])<<(4*(5-i));
            tx_message(sum); 	/* Echo Back */
        }
        if(timer_value[0] > 4999){			// 0.5秒ごとにボード上のLEDを点滅
            timer_value[0] = 0;
            myled = !myled;
        }
        if(timer_value[1] > 9999){			// 1秒ごとにインクリメント値をメッセージとして送信FIFOに積む
            timer_value[1] = 0;
            j &= 8388607;
            tx_message(j++);
        }
    }
}

========================
mbedサイト
http://developer.mbed.org/users/nagasm/code/CQ_nagasm_03_timer_test/
にて公開中
========================
