int main(int argc, char** argv){ // bool role_ping_out = true, role_pong_back = false; // bool role = role_pong_back; printf("RF24/examples/GettingStarted/\n"); // Setup and configure rf radio radio.begin(); radio.setChannel(2); radio.setDataRate(RF24_2MBPS); radio.setPayloadSize(8); // optionally, increase the delay between retries & # of retries // radio.setRetries(15,15); // Dump the configuration of the rf unit for debugging radio.printDetails(); /***********************************/ radio.startListening(); // forever loop while (1) { // if there is data ready if ( radio.available() ) { // Dump the payloads until we've gotten everything unsigned long got_time; // Fetch the payload, and see if this was the last one. while(radio.available()){ radio.read( &got_time, sizeof(unsigned long) ); } // radio.stopListening(); // radio.write( &got_time, sizeof(unsigned long) ); // Now, resume listening so we catch the next packets. // radio.startListening(); // Spew it printf("Got payload(%d) %lu...\n",sizeof(unsigned long), got_time); } delay(925); //Delay after payload responded to, minimize RPi CPU time printf("."); fflush(stdout); // radio.printDetails(); } // forever loop return 0; }
uint8_t COM_24g::isAvailable(RF24 _radioCom) { uint8_t i; uint8_t pipeAvailable; if (_radioCom.available()) { for (i=1;i<5;i++) { if (_radioCom.available(&i)) { pipeAvailable = i; break; } } return pipeAvailable; } else { return NULL; } }
void loop(void) { radio.startListening(); delay(10); if ( radio.available() ) { while ( radio.available() ) { len = radio.getDynamicPayloadSize(); radio.read(receive_payload, len); receive_payload[len] = 0; printf("Payload size=%i value=%s\n\r", len, receive_payload); lcd.setCursor(0, 0); delay(1); lcd.print(receive_payload); } } radio.stopListening(); delay(1); radio.write( send_payload, 16 ); delay(10); }
void loop() { unsigned long time = micros(); unsigned char pipeNo; while(radio.available(&pipeNo)){ radio.read(dmxData, 3); printf("%d %d %d \r\n", dmxData[0], dmxData[1], dmxData[2]); digitalWrite(LED, !digitalRead(LED)); analogWrite(OUT, dmxData[2]); } }
void loop(void) { char receivePayload[PAYLOAD_SIZE]; while ( radio.available() ) { uint8_t len = PAYLOAD_SIZE; radio.read( receivePayload, len ); //structure of data: 2bytes (int)-humidity | 2bytes (int)-thermistor | 2bytes (int) - mV int hum = 0; hum = receivePayload[1] << 8; hum = hum + receivePayload[0]; int thermistor = 0; thermistor = receivePayload[3] << 8; thermistor = thermistor + receivePayload[2]; int mV = 0; mV = receivePayload[5] << 8; mV = mV + receivePayload[4]; //convert the reading to mV mV = 1126400 / mV; //1100mV*1024=1126400 //calculate temperature double temp = calcTemp(mV, thermistor); time_t t; t = time ( NULL ); //write data to file ofstream file ("data.txt", ios::out | ios::app); if(file.is_open()){ file << temp << ", " << t << "\n"; file.close(); } //print data printf("Payload: size=%i bytes",len); printf("\nHumidity: %i", hum); printf("\nBattery status (mV): %i", mV); printf("\nTemp (C): %f", temp); printf("\nTime: %ld", t); printf("\n\n"); //start the update script FILE *stream = popen("python updater.py", "r"); pclose(stream); } sleep(1); }
void RF24Loop(void) { if ( radio.available() ) { Packet packet; radio.read( &packet, sizeof(Packet) ); _processPacket(packet); } }
void loop(void) { // // Ping out. // // The payload will always be the same, what will change is how much of it we send. static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; // First, stop listening so we can talk. radio.stopListening(); // Take the time, and send it. This will block until complete printf("Now sending length %i...",next_payload_size); radio.write( send_payload, next_payload_size ); // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout long started_waiting_at = __millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) if (__millis() - started_waiting_at > 500 ) timeout = true; // Describe the results if ( timeout ) { printf("Failed, response timed out.\n\r"); } else { // Grab the response, compare, and send to debugging spew uint8_t len = radio.getDynamicPayloadSize(); radio.read( receive_payload, len ); // Put a zero at the end for easy printing receive_payload[len] = 0; // Spew it printf("Got response size=%i value=%s\n\r",len,receive_payload); } // Update size for next time. next_payload_size += payload_size_increments_by; if ( next_payload_size > max_payload_size ) next_payload_size = min_payload_size; sleep(1); }
int main(int argc, char** argv) { printf("RF24 example starting.") /** Set up the radio **/ radio.begin(); radio.setRetries(15, 15); radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1, pipes[1]); radio.startListening(); /** Loop forever, writing and then listening for response **/ while (1) { /** Send out the current time **/ radio.stopListening(); unsigned long time = millis(); bool ok = radio.write(&time, sizeof(unsigned long)); if (!ok) printf("Failed to send for some reason.\n"); radio.startListening(); /** Start waiting around for the response **/ unsigned long started_waiting_at = millis(); bool timeout = false; while( !radio.available() && !timeout ) { if (millis() - started_waiting_at > 200) timeout = true; } /** Describe the results **/ if (timeout) { printf("Failed. Response timed out.\n") } else { unsigned long got_time; radio.read(&got_time, sizeof(unsigned long)) printf("Got response %lu, round-trip delay: %lu\n", got_time, millis() - got_time); sleep(1); } }
void intHandler(){ // // Pong back role. Receive each packet, dump it out, and send it back // if ( role == role_pong_back ) { // if there is data ready if ( radio.available() ) { // Dump the payloads until we've gotten everything uint8_t len=0; while (radio.available()) { // Fetch the payload, and see if this was the last one. len = radio.getDynamicPayloadSize(); radio.read( receive_payload, len ); // Put a zero at the end for easy printing receive_payload[len] = 0; // Spew it printf("Got payload size=%i value=%s\n\r",len,receive_payload); } // First, stop listening so we can talk radio.stopListening(); // Send the final one back. radio.write( receive_payload, len ); printf("Sent response.\n\r"); // Now, resume listening so we catch the next packets. radio.startListening(); } } }
unsigned long loop(void) { unsigned long sender_id = 0; ArPiMessage data; char blank[21]="FFFFFFFFFFFFFFFFFFFF"; int max_sleep = 10000; while (!radio.available()) { usleep(1000); } if (max_sleep > 0) { uint8_t len = radio.getDynamicPayloadSize(); radio.read( receivePayload, len ); TRI_LOG(len); memcpy(&data, receivePayload, sizeof(data)); if (data.parity != parity(data.data)) { TRI_LOG_STR("parity doesn't match, rejecting...\n"); } else { unsigned long timer = data.data; sender_id = data.sender_id; // Send back payload to sender radio.stopListening(); // Match for blank and do not re-send it out TRI_LOG_STR("All good"); // if ( strcmp(receivePayload,blank) ) { // radio.write(receivePayload,len); // TRI_LOG_STR("Sending back"); // } else { // TRI_LOG_STR("Not sending anything back"); // } } } TRI_LOG_STR("radio.startListening()"); radio.startListening(); // radio.startListening(); return sender_id; }
float requestData(const byte cmd_buffer[], const byte write_pipe[]) { if( !radio_hw_available ) { debugPrint("Radio is NOT available"); return -1.0; } debugPrint("Request data from Radio ... "); radio.openWritingPipe(write_pipe); // Open different pipes when writing. Write on pipe 0, address 0 radio.openReadingPipe(1,pipes[1]); // Read on pipe 1, as address 1 byte rec_buffer[8]; /* if( !radio.testRPD() || !radio.isValid() ) { debugPrint("Radio is not available"); return false; } */ if( !sendRadioCommand(cmd_buffer) ) { debugPrint("Send Radio command failed"); return false; } unsigned long started_waiting_at = millis(); // Set up a timeout period, get the current milliseconds boolean timeout = false; // Set up a variable to indicate if a response was received or not while ( ! radio.available() ){ // While nothing is received if (millis() - started_waiting_at > 200 ) { // If waited longer than 200ms, indicate timeout and exit while loop timeout = true; break; } } if ( timeout ) { debugPrint("Failed, response timed out.\n\r"); } else { radio.read( &rec_buffer, 8 ); byte fbytes[4]; for(int i=0,j=4;i<4;i++,j++) fbytes[i] = rec_buffer[j]; return convertToFloat(fbytes); } return -99.99; }
void loop(void) { // 32 byte character array is max payload char receivePayload[32]; while (radio.available()) { // read from radio until payload size is reached uint8_t len = radio.getDynamicPayloadSize(); radio.read(receivePayload, len); // display payload cout << receivePayload << endl; } }
/** * Handles interrupts from the radio * * */ void check_radio(void) { bool tx, fail, rx; // What happened? radio.whatHappened(tx, fail, rx); if (tx) { // Have we successfully transmitted? message_good++; // printf("Ack Payload:Sent\n\r"); } if (fail) { // Have we failed to transmit? message_fail++; // printf("Ack Payload:Failed\n\r"); } // Did we receive a message? if (rx || radio.available()) { // get payload and store in buffer; set command flag while (radio.available()) { radio.read((void *) commandBuffer, MAX_COMMAND_SIZE); } radio.writeAckPayload(1, &message_count, sizeof(message_count)); ++message_count; commandAvailable = true; } }
boolean readPackage(void * package,unsigned char len) { unsigned long started_waiting_at = millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) if (millis() - started_waiting_at > 1000 ) timeout = true; if(!timeout) { timeout = !radio.read(package, len); } //else Serial.println("\nTimeout fail"); return !timeout; }
int main() { data_t receivedMessage; //temporary packet storage sqlite3 *db; //database char *zErrMsg = 0; //database error message //Connecting to DB if (sqlite3_open("sensorData.db", &db)) { printf("Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { printf("Everything's okay, folks! Database up!\n\r"); } //Radio setup radioSetup(); while(1) { if (radio.available()) { radio.read(&receivedMessage, sizeof(data_t)); //Debug stuff printf("netID: %i, nodeID: %i, valueType: %i, value: %f \n", (int)receivedMessage.netID, (int)receivedMessage.nodeID, (int)receivedMessage.valueType, receivedMessage.value); //Write to DB stringstream ss; ss << "INSERT INTO SENSORDATA (NETID, NODEID, VALUETYPE, VALUE) VALUES (" << (int)receivedMessage.netID << ", " << (int)receivedMessage.nodeID << ", " << (int)receivedMessage.valueType << ", " << receivedMessage.value << ");"; //sql injection security is overradted string sql = ss.str(); //that's definitely not pretty, use just str.append()?? if (sqlite3_exec(db, sql.c_str(), callback, 0, &zErrMsg) != SQLITE_OK) { printf("SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //Debug stuff printf("Insert successful, folks!\n"); } } } //wait, we'll never reach here. out of the loop man, out of the loop man,, sqlite3_close(db); }
void loop(void) { char receivePayload[32]; uint8_t pipe = 0; while ( radio.available( &pipe ) ) { uint8_t len = radio.getDynamicPayloadSize(); radio.read( receivePayload, len ); // Display it on screen printf("Recv: size=%i payload=%s pipe=%i",len,receivePayload,pipe); // Send back payload to sender radio.stopListening(); // if pipe is 7, do not send it back if ( pipe != 7 ) { // Send back using the same pipe // radio.openWritingPipe(pipes[pipe]); time_t now = time(0); tm * gmtm = gmtime(&now); char * dt = asctime(gmtm); //sprintf(dt, "%d", time_t); strftime(dt, 20, "%Y-%m-%d %H:%M:%S", localtime(&now)); radio.write(dt,strlen(dt)); receivePayload[len]=0; printf("\t Send: size=%i payload=%s pipe:%i\n\r",strlen(dt),dt,pipe); } else { printf("\n\r"); } // Enable start listening again radio.startListening(); // Increase the pipe outside the while loop pipe++; // reset pipe to 0 if ( pipe > 5 ) pipe = 0; } usleep(20); }
void loop(void) { // 32 byte character array is max payload // char receivePayload[32]; char str[80]; while (radio.available()) { // read from radio until payload size is reached uint8_t len = radio.getDynamicPayloadSize(); // radio.read(receivePayload, len); // display payload // cout << receivePayload << endl; radio.read(&mpu_data, len); Quat quat = mpu_data.Q; sprintf(str, "Quat: w=%f, x=%f, y=%f, z=%f", quat.w, quat.x, quat.y, quat.z); cout << str << endl; } }
bool switchLight(int action){ //This function send a message, the 'action', to the arduino and wait for answer //Returns true if ACK package is received //Stop listening radio.stopListening(); unsigned long message = action; printf("Now sending %lu...", message); //Send the message bool ok = radio.write( &message, sizeof(unsigned long) ); if (ok) printf("ok..."); else printf("failed.\n\r"); //Listen for ACK radio.startListening(); //Let's take the time while we listen unsigned long started_waiting_at = __millis(); bool timeout = false; //if(!radio.available() ){ // printf("No hay radio disponible\n"); // } while ( ! radio.available() && ! timeout ) { __msleep(10); if (__millis() - started_waiting_at > 5000 ) timeout = true; } if( timeout ){ //If we waited too long the transmission failed printf("Failed, response timed out.\n\r"); radio.printDetails(); return false; }else{ //If we received the message in time, let's read it and print it unsigned long got_time; radio.read( &got_time, sizeof(unsigned long) ); printf("Got response %lu, round-trip delay: %lu\n\r",got_time,__millis()-got_time); return true; } }
/* ************** LOOP Procedure ************** */ void loop(void) { if (radio.available(&pipeNo)) { int len = radio.getDynamicPayloadSize(); // Size of th epayload to read radio.read(&payload, len); // Read the payload printf("%d:",pipeNo); sprintf(SQLstring,";"); // Initialise SQLString to a default value "nothing" switch(payload.type) { case SENSOR_STATION: printf("SENSOR_STATION:"); printf("packet %d:%d ID:%u PowerVoltage:%u status:%u \n", len, sizeof(payload), payload.data.SENSOR_STATION.Station_id, payload.data.SENSOR_STATION.Power_Voltage, payload.data.SENSOR_STATION.status); break; case CC_SENSOR_DYN: printf("CC_SENSOR_DYN:"); printf("packet %d:%d Sensor:%d Temp:%f Watts:%d status:%u \n", len, sizeof(payload), payload.data.CC_SENSOR_DYN.sensor_id, payload.data.CC_SENSOR_DYN.temperature, payload.data.CC_SENSOR_DYN.watts, payload.data.CC_SENSOR_DYN.status); sprintf(SQLstring,"INSERT INTO CC_SENSOR_DYN VALUES(NOW(),%d,%5.1f,%d)",payload.data.CC_SENSOR_DYN.sensor_id, payload.data.CC_SENSOR_DYN.temperature, payload.data.CC_SENSOR_DYN.watts); break; case CC_SENSOR_HIST: printf("CC_SENSOR_HIST:"); printf("packet %d:%d Sensor:%d Period:%lc:%i Watts:%3.3f status:%u \n", len, sizeof(payload), payload.data.CC_SENSOR_HIST.sensor_id, payload.data.CC_SENSOR_HIST.hist_type, payload.data.CC_SENSOR_HIST.hist_period, payload.data.CC_SENSOR_HIST.watts, payload.data.CC_SENSOR_HIST.status); sprintf(SQLstring,"INSERT INTO CC_SENSOR_HIST VALUES(NOW(),%d,'%lc',%i, %3.3f)",payload.data.CC_SENSOR_HIST.sensor_id, payload.data.CC_SENSOR_HIST.hist_type, payload.data.CC_SENSOR_HIST.hist_period, payload.data.CC_SENSOR_HIST.watts); break; default: printf("Unknown message.\n"); break; } // Executing the SQL instruction. There is one payload per loop, therefore one SQL instructions per loop. if ((mysql1 != NULL) && (strcmp(SQLstring,";") != 0)) { // Check mySql connection availability and Sql Instructions validity if (!mysql_query(mysql1, SQLstring)) { //printf(" >SQL Ok: %s\n",SQLstring); } else { printf(" >SQL NOk: %s\n",SQLstring); // Error Occured printf("%s\n", mysql_error(mysql1)); // Print mysql Error } } } delay(20); }
void loop(void) { char receivePayload[32]; uint8_t pipe = 0; while ( radio.available( &pipe ) ) { uint8_t len = radio.getDynamicPayloadSize(); radio.read( receivePayload, len ); // Display it on screen printf("Recv: size=%i payload=%s pipe=%i",len,receivePayload,pipe); // Send back payload to sender radio.stopListening(); // if pipe is 7, do not send it back if ( pipe != 7 ) { // Send back using the same pipe // radio.openWritingPipe(pipes[pipe]); radio.write(receivePayload,len); receivePayload[len]=0; printf("\t Send: size=%i payload=%s pipe:%i\n\r",len,receivePayload,pipe); } else { printf("\n\r"); } // Enable start listening again radio.startListening(); // Increase the pipe outside the while loop pipe++; // reset pipe to 0 if ( pipe > 5 ) pipe = 0; } usleep(20); }
void loop() { if(Serial.available()) { re=Serial.read(); if(re=='1') { radio.stopListening(); radio.openWritingPipe(pipe[0]); select(2); trans(); }else if(re=='R') { software_Reboot(); //where the system restarts without the need //to interrupt the power }else { Serial.println("Error Selection"); } }else if(radio.available(&pipe_num)) { bool done=false; while(!done) { done = radio.read( income, sizeof(income) ); } Serial.print("Received = "); Serial.print(income); Serial.println(); sender_id = pipe_num; if(sender_id==1) // selection which pipe u 'll send via { Serial.print("host1"); Serial.println(); } } }
void updateRadio() { PosData& ctrlData = getCtrlData(); unsigned long now = millis(); if(now >= nextMessage) { unsigned long time = now; radio.stopListening(); bool ok = radio.write( &ctrlData, sizeof(PosData) ); radio.startListening(); unsigned long started_waiting_at = millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) { if (millis() - started_waiting_at > 100 ) { timeout = true; } delay(1); } if(!timeout) { // Grab the response, compare, and send to debugging spew PosData imuData = {0.0, 0.0, 0.0}; radio.read( &imuData, sizeof(PosData) ); // Spew it Serial.print(imuData.roll); Serial.print(' '); Serial.print(imuData.pitch); Serial.print(' '); Serial.print(imuData.yaw); Serial.print(' '); Serial.print(millis()-started_waiting_at); Serial.print('\n'); } nextMessage += MSG_FREQUENCY; } }
//This part of program is executed forever. It is assumed that the Raspberry Pi is powered on 24 x 7 so that program runs forever. void loop(void) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1,pipes[1]); radio.openReadingPipe(2,pipes[2]); radio.openReadingPipe(3,pipes[3]); time_t t; count++; FILE *F1; F1 = fopen("database.txt","a"); unsigned long incoming; if(radio.available()) //If any data packet is available on "ANY PIPE" { unsigned long got_time; bool done = false; while (!done) { done = radio.read( &got_time, sizeof(unsigned long) ); //Read the data printf("Got payload %lu...",got_time); time(&t); incoming = got_time%1000; //Finding out the node number because the format in which data is sent is ~ timing_data * 1000 + node_number unsigned long value = got_time/1000; //Finding out the timing data because the format in which data is sent is ~ timing_data * 1000 + node_number fprintf(F1, "%i %lu %lu %s", count,incoming,value,ctime(&t));//putting into a file to keep a log. Improve the data logging based on your requirements delay(20); } // First, stop listening so we can talk radio.stopListening(); radio.openWritingPipe(pipes[incoming-1]); //I must send back the confirmation to the sensor_node from which I received the data // Send the final one back. printf("Sent response.\n\r"); radio.write( &got_time, sizeof(unsigned long) ); // Now, resume listening so we catch the next packets. radio.startListening(); } }
int main(int argc, char** argv){ bool role_ping_out = true, role_pong_back = false; bool role = role_pong_back; printf("RF24/examples/GettingStarted/\n"); // Setup and configure rf radio radio.begin(); // optionally, increase the delay between retries & # of retries radio.setRetries(15,15); // Dump the configuration of the rf unit for debugging radio.printDetails(); /********* Role chooser ***********/ printf("\n ************ Role Setup ***********\n"); string input = ""; char myChar = {0}; cout << "Choose a role: Enter 0 for pong_back, 1 for ping_out (CTRL+C to exit) \n>"; getline(cin,input); if(input.length() == 1) { myChar = input[0]; if(myChar == '0'){ cout << "Role: Pong Back, awaiting transmission " << endl << endl; }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; role = role_ping_out; } } /***********************************/ // This simple sketch opens two pipes for these two nodes to communicate // back and forth. if ( !radioNumber ) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1,pipes[1]); } else { radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1,pipes[0]); } radio.startListening(); // forever loop while (1) { if (role == role_ping_out) { // First, stop listening so we can talk. radio.stopListening(); // Take the time, and send it. This will block until complete printf("Now sending...\n"); unsigned long time = millis(); bool ok = radio.write( &time, sizeof(unsigned long) ); if (!ok){ printf("failed.\n"); } // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout (250ms) unsigned long started_waiting_at = millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) { if (millis() - started_waiting_at > 200 ) timeout = true; } // Describe the results if ( timeout ) { printf("Failed, response timed out.\n"); } else { // Grab the response, compare, and send to debugging spew unsigned long got_time; radio.read( &got_time, sizeof(unsigned long) ); // Spew it printf("Got response %lu, round-trip delay: %lu\n",got_time,millis()-got_time); } sleep(1); } // // Pong back role. Receive each packet, dump it out, and send it back // if ( role == role_pong_back ) { // if there is data ready if ( radio.available() ) { // Dump the payloads until we've gotten everything unsigned long got_time; // Fetch the payload, and see if this was the last one. while(radio.available()){ radio.read( &got_time, sizeof(unsigned long) ); } radio.stopListening(); radio.write( &got_time, sizeof(unsigned long) ); // Now, resume listening so we catch the next packets. radio.startListening(); // Spew it printf("Got payload(%d) %lu...\n",sizeof(unsigned long), got_time); delay(925); //Delay after payload responded to, minimize RPi CPU time } } } // forever loop return 0; }
static void vTaskRoute(void* pvParam) { while (1) { if (node_type == NODE_SENSOR) { // apa ada paket yang mau masuk? if (!radio.available()) { // kalau nggak, kirim paketnya sekarang // rawan chaos: tambahkan mutex di sini // TODO: tambah flag untuk info data udah siap atau belum while(xSemaphoreTake(&sem_pckt, 0)) ; pckt.addr_s = addr_saya; pckt.addr_t = ADDR_SINK; xSemaphoreGive(&sem_pckt); kirim_paket(&pckt); } else { // tahan, ada paket masuk bool done = false; while (!done) { done = radio.read(&buf, PANJANG_PAKET); } // liat alamatnya, buat kita apa bukan? uint16_t addr_tujuan_paket = buf[5] << 8 | buf[4]; uint16_t addr_asal_paket = buf[3] << 8 | buf[2]; if (addr_tujuan_paket == addr_saya) { // apa yang mau dilakuin seandainya paket ini buat saya // misalnya ini perintah dari server atau informasi dari // tetangga printf("hore kita dapet paket "); cetakpaket(buf); ; } if (addr_asal_paket == addr_saya) { // ini paket yang mau saya kirim, keluar dari loop saat ini printf("paket ini sih punya saya "); cetakpaket(buf); continue; } // paket ini bukan dari saya dan bukan buat saya, forward ke node berikutnya printf("ada paket yang diterusin "); cetakpaket(buf); radio.write(&buf, PANJANG_PAKET); } delay_rand(); } else { bool done = false; uint8_t arr[PANJANG_PAKET]; if (radio.available()) { while (!done) done = radio.read(&arr, PANJANG_PAKET); printf("yang ditangkep: "); cetakpaket(arr); } } } }
int main(int argc, char** argv){ // Print preamble: cout << "RF24/examples/pingpair_dyn/\n"; // Setup and configure rf radio radio.begin(); radio.enableDynamicPayloads(); radio.setRetries(5,15); radio.printDetails(); /********* Role chooser ***********/ printf("\n ************ Role Setup ***********\n"); string input = ""; char myChar = {0}; cout << "Choose a role: Enter 0 for receiver, 1 for transmitter (CTRL+C to exit) \n>"; getline(cin,input); if(input.length() == 1) { myChar = input[0]; if(myChar == '0'){ cout << "Role: Pong Back, awaiting transmission " << endl << endl; }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; role = role_ping_out; } } /***********************************/ if ( role == role_ping_out ) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1,pipes[1]); } else { radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1,pipes[0]); radio.startListening(); } attachInterrupt(interruptPin, INT_EDGE_FALLING, intHandler); //Attach interrupt to bcm pin 23 // forever loop while (1) { if (role == role_ping_out) { // The payload will always be the same, what will change is how much of it we send. static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; // First, stop listening so we can talk. radio.stopListening(); // Take the time, and send it. This will block until complete printf("Now sending length %i...",next_payload_size); radio.write( send_payload, next_payload_size ); // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout unsigned long started_waiting_at = millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) if (millis() - started_waiting_at > 500 ) timeout = true; // Describe the results if ( timeout ) { printf("Failed, response timed out.\n\r"); } else { // Grab the response, compare, and send to debugging spew uint8_t len = radio.getDynamicPayloadSize(); radio.read( receive_payload, len ); // Put a zero at the end for easy printing receive_payload[len] = 0; // Spew it printf("Got response size=%i value=%s\n\r",len,receive_payload); } // Update size for next time. next_payload_size += payload_size_increments_by; if ( next_payload_size > max_payload_size ) next_payload_size = min_payload_size; // Try again 1s later delay(100); } } }
int main(int argc, char** argv) { int fr = atoi(argv[1]); int to = atoi(argv[2]); int ac = atoi(argv[3]); printf("vendor/TMRh20/RF24_RPi/Task\n"); // Refer to RF24.h or nRF24L01 DS for settings radio.begin(); delay(5); radio.setPayloadSize(10); radio.setRetries(15,15); // optionally, increase the delay between retries & # of retries //radio.setAutoAck(1); // Ensure autoACK is enabled radio.setAutoAck(0); // Ensure autoACK is disabled radio.setPALevel(RF24_PA_HIGH); radio.setDataRate(RF24_250KBPS); //radio.setCRCLength(RF24_CRC_8); radio.setChannel(114); radio.openWritingPipe(pipes[(to-1)]); // atoi() change a char to a int radio.openReadingPipe(1,pipes[(fr-1)]); radio.startListening(); radio.printDetails(); // First, stop listening so we can talk. radio.stopListening(); radio.powerUp(); // Take the time, and send it. This will block until complete char payload_send[10] = ""; snprintf(payload_send, 10, "to:%d,ac:%d", to, ac); char payload_send_size[10] = ""; snprintf(payload_send_size, 10, "%d", sizeof(payload_send)); printf("Sending ..\n"); printf("Payload size: "); printf(payload_send_size); printf("\n"); printf("Payload: "); printf(payload_send); printf("\n"); //bool ok = radio.write( &payload_send, 10 ); radio.write( &payload_send, 10 ); /*if (!ok){ printf("failed.\n"); exit(1); }*/ //radio.powerDown(); // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout (250ms) unsigned long started_waiting_at = millis(); bool timeout = false; // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) while ( ! radio.available() && ! timeout ) { if (millis() - started_waiting_at > 3000 ) { timeout = true; } } // Describe the results if ( timeout ) { printf("err: response timed out.\n"); exit(1); } else { // Grab the response, compare, and send to debugging spew char payload_receive[10] = ""; radio.read( &payload_receive, 10 ); char payload_receive_size[10] = ""; snprintf(payload_receive_size, 32, "%d", 10); // Spew it printf("Received ..\n"); printf("Payload size: "); printf(payload_receive_size); printf("\n"); printf("Payload: "); printf(payload_receive); printf("\n"); printf(payload_receive); exit(0); } exit(1); }
void loop() { char receivePayload[32]; uint8_t pipe = 0; while ( radio.available( &pipe ) ) { uint8_t len = radio.getDynamicPayloadSize(); radio.read( &p, sizeof(p) ); char temp[5]; char outBuffer[1024]=""; strcat(outBuffer, ""); strcat(outBuffer, "key="); strcat(outBuffer, p.id); int val = 0; if ((p.type & TEMPERATURE) == TEMPERATURE) { strcat(outBuffer,"&1="); sprintf(temp, "%3.2f", p.val[val++]/100.0); strcat(outBuffer, temp); } if ((p.type & HUMIDITY) == HUMIDITY) { strcat(outBuffer,"&2="); sprintf(temp, "%3.2f", p.val[val++]/100.0); strcat(outBuffer, temp); } if ((p.type & CURRENT) == CURRENT) { strcat(outBuffer,"&3="); sprintf(temp, "%3.2f", p.val[val++]/100.0); strcat(outBuffer, temp); } if ((p.type & LUMINOSITY) == LUMINOSITY) { strcat(outBuffer,"&4="); sprintf(temp, "%3.2f", p.val[val++]/100.0); strcat(outBuffer, temp); } if ((p.type & PRESSURE) == PRESSURE) { strcat(outBuffer,"&6="); sprintf(temp, "%3.2f", p.val[val++]/100.0); strcat(outBuffer, temp); } // Display it on screen printf("\n\rRecv: size:%i pipe:%i type:%d data:%s\n\r",len,pipe,p.type,outBuffer); sendToServer(outBuffer); // Send back payload to sender radio.stopListening(); // if pipe is 7, do not send it back if ( pipe != 7 ) { // Send back using the same pipe // radio.openWritingPipe(pipes[pipe]); radio.write(receivePayload,len); receivePayload[len]=0; printf("\t Send: size=%i payload=%s pipe:%i\n\r",len,receivePayload,pipe); } else { printf("\n\r"); } // Enable start listening again radio.startListening(); } //read on all pipes pipe++; if ( pipe > 5 ) pipe = 0; usleep(20); }
void loop(void) { // Read the current command from the user std::string command; std::getline(std::cin, command); std::cerr << "Got '" << command << "'.\n"; // Split the command on spaces std::stringstream ss("0 "); ss << command; ss << " 0"; unsigned char bytes[PAYLOAD]; int buf = 0; // Read each space-separated value into an integer and put it into bytes int used = 0; for (int i = 0; i < PAYLOAD && ss >> buf; i++) { bytes[i] = (unsigned char)buf; used = i; } std::cerr << "Read " << used << " bytes from stdin." << std::endl; // Stop listening so we can talk. radio.stopListening(); // Send the bytes std::cerr << "Sending bytes: "; for (int i = 0; i < used; i++) { std::cerr << (int)bytes[i] << " "; } std::cerr << std::endl; bool ok = radio.write( bytes, used ); if (ok) { std::cerr << "ok..." << std::endl; } else { std::cerr << "failed..." << std::endl; // TODO: retry! } // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout (500ms) unsigned long started_waiting_at = __millis(); bool timeout = false; while ( !radio.available() && ! timeout ) { __msleep(5); //add a small delay to let radio.available to check payload timeout = ((__millis() - started_waiting_at) > TIMEOUT); } // Describe the results if (timeout) { std::cerr << "response timed out..." << std::endl; // TODO: retry! } else { // Grab the response, compare, and send to debugging spew radio.read( bytes, PAYLOAD ); // TODO: replace PAYLOAD // Print the bytes for (int i = 0; i < PAYLOAD; i++) { std::cout << (unsigned int)bytes[i] << " "; } std::cout << std::endl; } }
void loop() { // - Sleep loop int i = 0; for(i = 0; i < SLEEP_STEP_NB; i++) { LowPower.powerDown(SLEEP_STEP_DURATION, ADC_OFF, BOD_OFF); } Serial.println(F("Awake")); // - Wake up the sensor through the step-up converter digitalWrite(STEP_UP_PIN, HIGH); // - Wait few ms for sensor init (TBD: minimal value) delay(100); // - Let's measure the distance between the sensor and the surface of the water int valuesInCm[NB_MEASURES]; double avgMeasureCm = 0.0d; for(i = 0; i < NB_MEASURES; i++) { valuesInCm[i] = sonar.ping_cm(); Serial.print(F("Distance: ")); Serial.print(valuesInCm[i]); Serial.println(F("cm")); // - Skip some values if necessary if(i >= NB_MEASURES_SKIP) { avgMeasureCm += valuesInCm[i]; } // - Delay for remaining echos (cf. sensor datasheet) before next reading delay(70); } // - Power off the sensor digitalWrite(STEP_UP_PIN, LOW); // - Computing average value (still in centimeters) unsigned short valueToSend = (unsigned short) round(avgMeasureCm / (double) (NB_MEASURES - NB_MEASURES_SKIP)); Serial.print(F("Now sending: ")); Serial.println(valueToSend); // - Message content Message msg; msg.address = nodeAddress[0]; msg.value = valueToSend; // - Time to start the radio radio.powerUp(); // - Message emission (with ACK) if ( radio.write(&msg, PAYLOAD_SIZE) ) { if(!radio.available()) { Serial.println(F("Got (blank) ack")); } } else { Serial.println(F("Sending failed")); } // - Time to stop the radio radio.powerDown(); Serial.println(F("----------")); // - Delay necessary to serial buffer flush delay(50); }