IoT - Kubus / Mbed 2 deprecated Kubus

Dependencies:   mbed nRF24L01P

pir1_sensor.cpp

Committer:
pannaannap
Date:
2017-01-05
Revision:
5:fbd5b1e953e6
Parent:
4:aa25f65395e3
Child:
6:98401b545e0c

File content as of revision 5:fbd5b1e953e6:

#include "mbed.h"

#include "common.h"

// ***** SETTINGS START *****

const unsigned long long RX_ADDRESS = PIR1_ADDRESS;
const unsigned long long TX_ADDRESS = MASTER_ADDRESS;
const double SEND_INTERVAL = 5.0;
const uint8_t SENSOR_ID = PIR1;

// ***** SETTINGS END *****

Serial pc(USBTX, USBRX); // tx, rx
nRF24L01P radio(PB_15, PB_14, PB_13, PB_12, PB_1, PB_2); // mosi, miso, sck, csn, ce, irq
DigitalIn sensor(PA_10);

Ticker sender;
bool send_acc_results = false;

void set_send() {
    send_acc_results = true;
}

void init() {
    sensor.mode(PullDown);
    pc.baud(115200);
    sender.attach(&set_send, SEND_INTERVAL);
    radio_init(&radio, RX_ADDRESS, TX_ADDRESS);
}

int main() {
    init();
    
    // Display the (default) setup of the nRF24L01+ chip
    pc.printf( "nRF24L01+ Frequency    : %d MHz\r\n",  radio.getRfFrequency() );
    pc.printf( "nRF24L01+ Output power : %d dBm\r\n",  radio.getRfOutputPower() );
    pc.printf( "nRF24L01+ Data Rate    : %d kbps\r\n", radio.getAirDataRate() );
    pc.printf( "nRF24L01+ TX Address   : 0x%010llX\r\n", radio.getTxAddress() );
    pc.printf( "nRF24L01+ RX0 Address   : 0x%010llX\r\n", radio.getRxAddress(NRF24L01P_PIPE_P0) );
    pc.printf( "nRF24L01+ RX1 Address   : 0x%010llX\r\n", radio.getRxAddress(NRF24L01P_PIPE_P1) );
    
    uint8_t count_changes;
    int last_state;
    
    while (1) {
        int state;
        if (sensor.read()) {
            state = 1;
        } else {
            state = 0;
        }
        
        if (last_state != state) {
            last_state = state;
            count_changes++;
        }
        
        if (send_acc_results) {
            Data data(SENSOR_ID, count_changes);
            std::string serialized_data = data.serialize();
            pc.printf("string data '%s', len %d\r\n", serialized_data.c_str(), serialized_data.size());
            
            char message[TRANSFER_SIZE];
            memcpy(message, serialized_data.c_str(), 2);
            int tx_bytes = radio.write(NRF24L01P_PIPE_P0, message, TRANSFER_SIZE);
            
            if (tx_bytes > 0) {
                pc.printf("Counter: %d\r\n", count_changes);
                pc.printf("RETR: %d\r\n", radio.getRetrCount());  
                count_changes = 0;
                send_acc_results = false;
            }
            if(tx_bytes < 0)
                pc.printf("TX ERROR\r\n");       
        }
        
    }
}