リスト2-3-4.txt

■リスト2-3-4■

#include "mbed.h"

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

RawSerial xbee(PA_2, PA_3);
Ticker timer_setup;
DigitalOut myled(LED1);
AnalogIn analog_value0(A0);		// A/Dポートの設定
AnalogIn analog_value1(A1);		// A/Dポートの設定
AnalogIn analog_value2(A2);		// A/Dポートの設定
AnalogIn analog_value3(A3);		// A/Dポートの設定

void timer_interrupt(){
    int i;
    for (i=0; i<6; i++) ++timer_value[i] &= 65535;
}

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);
}

int main(){
    int i, sum;
    i = 0;
    rx_top = rx_end = tx_top = tx_end = phase = 0; 
    for (i=0; i<5; i++) timer_value[i] = 0;
    xbee.baud(38400);
    xbee.attach(&rx_fifoset, xbee.RxIrq);
    timer_setup.attach_us(&timer_interrupt, 50);
    while(1){
        if(timer_value[2] > 99){		// 5msecサンプリング
            timer_value[2] = 0;
            uint16_t data = analog_value3.read_u16();	// A/D変換、ここでは治具なので「3」。筋電なら「0」か「1」
            tx_message(data);						// XBeeからシリアル送信
        }
        if(timer_value[0] > 9999){
            timer_value[0] = 0;
            myled = !myled;
        }
        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 */
        }
    }
}

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