Example #1
0
bool COM_24g::sendFrame(RF24 _radioCom)
{
	// First, stop listening so we can talk
	_radioCom.stopListening(); 
 
	//Opening the writting Pipe
	_radioCom.openWritingPipe(_writingPipe);
	delay(20);

	//put in place the Paypload
	_payload.type    = _dataType;
	_payload.version = _dataVersion;
	_payload.data    = _data;
	bool Writestatus = _radioCom.write(&_payload, sizeof(_payload));

  if (Writestatus)
      printf("Communication has been sent successfully. \n");
    else
      printf("Communication has failed.\n\r");

	//back in read mode
	_radioCom.startListening(); 
	
 
}
Example #2
0
void loop(void){

    const char text[] = "girish ramnani";
    radio.write(text,sizeof(text));


}
Example #3
0
boolean writePackage(void * package, unsigned char len)
{
    radio.stopListening();
    boolean temp = radio.write(package,32);
    radio.startListening();
    return temp;
}
Example #4
0
void trans()
{
    Serial.println("Enter a msg (max 32 Characters)");
    while(!Serial.available());
      delay(32); // for collection
      char tx[32];
      for(int j=0;j<32;j++)
      {
       tx[j]=Serial.read();
       if(tx[j]==(char)-1)    // to avoid writing unkown char in spaces
       {
         tx[j]='\0';
         goto loop1;
       }
      }
      loop1:
     loop2: 
     bool done = radio.write(tx, sizeof(tx));  
     if(done==false)
     { 
       retx++;
       Serial.println("Tx Failed");
       if(retx<10)
       {
       goto loop2;
       }else retx=0;
     }
     radio.startListening();
     print_welcome_message();
}
boolean sendRadioCommand(const byte cmd_buffer[]) {
  if( !radio_hw_available ) {
    debugPrint("Radio is NOT available");
    return false;
  }
  
  int counter = 0;
  
  //byte cmd_buffer[] = { 0xFF, 0x00, 0xFC, 0x01, 0x00, 0x00, 0x00, 0x00};
  
  radio.stopListening();
  
  debugPrint("Now sending payload: ",counter);
  
  boolean radio_write_ok = false;
  
  while( !radio_write_ok && counter < MAX_RADIO_RETRIES ) {
    radio_write_ok = radio.write(cmd_buffer,8);
    if( !radio_write_ok )
      debugPrint("Retry send: ", counter++);
  }
  
  debugPrint("Payload sent. ",counter);
  
  radio.startListening();
  
  return radio_write_ok;
}
Example #6
0
void add_names_to_devices(){
	uint8_t i=0;
	uint64_t mask=0xFFFFFFFFFF000000LL;
	dev device;
	uint8_t tam;
	printf("Please add names to the devices\r\n");
	while(load_address(&RFbuffer.destino,i)){
		blink_led();
		device.addr=RFbuffer.destino;
		RFbuffer.comando=all_on;
		radio.stopListening();
		radio.openWritingPipe((RFbuffer.destino & mask));
		radio.write(&RFbuffer,sizeof(RFbuffer));
		radio.startListening();
		printf("enter name for device:%d,with addr:%lX%08lX\r\n",i+1,(uint32_t)(device.addr>>32),(uint32_t)device.addr);
		while(!Serial.available());
		do {
			blink_led();
			tam=Serial.readBytes(device.name,sizeof(device));
			if (tam>=sizeof(device.name)){
				printf("name must be smaller than 7 letter\r\n");
			}else{
				device.name[tam]='\0';
				printf("device name set to:");
				int n=0;
				do{
					printf("%c",device.name[n]);
					n++;
				} while (device.name[n]!='\0');
				printf("\r\n");
				file=SD.open("devs.lst",FILE_WRITE);
				if (file){
					file.write((byte *)&device,sizeof(device));
				}
				file.close();
			}
		} while (tam>=sizeof(device.name));
		RFbuffer.comando=all_off;
		radio.stopListening();
		radio.openWritingPipe((RFbuffer.destino & mask));
		radio.write(&RFbuffer,sizeof(RFbuffer));
		radio.startListening();
		i++;
	}
	printf("done\r\n");
	return;
}
void sendPacket(Packet packet)
{
	radio.stopListening();
	radio.openWritingPipe(base_pipe+packet.nodeId); //open pipe unique to the node
	radio.setAutoAck(0, false);
	radio.write( &packet, sizeof(Packet) );
	radio.startListening();
}
/**
   fungsi untuk mengirim paket via radio
   @param paket* alamat ke paket
   @return ok bernilai true jika pengiriman berhasil, false jika sebaliknya
*/
bool kirim_paket(paket* paket_dikirim)
{
  uint8_t yang_dikirim[PANJANG_PAKET];
  toarray(paket_dikirim, yang_dikirim);
  printf("ngirim paket gan "); cetakpaket(paket_dikirim);
  radio.stopListening();
  bool ok = radio.write(yang_dikirim, PANJANG_PAKET);
  radio.startListening();
  return ok;
}
Example #9
0
void loop() {
	radio.stopListening();

	uint8_t data[] = {111, 101};
	bool ok = radio.write(data, 2);

    if (ok)
      printf("ok...\n\r");
    else
      printf("failed.\n\r");
}
Example #10
0
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);
    }
  }
Example #11
0
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);
}
Example #12
0
uint8_t send(uint8_t * data_pointer){
    // Stop listening so we can talk
    radio.stopListening();

    // Send data. This is a blocking call.
    uint8_t result = radio.write(data_pointer, PAYLOADLEN);

    // Resume listening
    radio.startListening();

    // Return the error code. If result is 0, there was a sending failure.
    return (result == 0); 
}
Example #13
0
void loop(void)
{
    // First, stop listening so we can talk.
    radio.stopListening();

    bool ok = radio.write( &packet, PACKET_LENGTH);
    
    if (ok)
      printf("sent...%d\n\r",packet[2]);
    else
      printf("failed.\n\r");

	sleep(1);
	packet[2]++;
//	packet[5]++;
}
Example #14
0
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);
}
Example #15
0
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;
  }

   }
Example #16
0
int main(int argc, char** argv){

    uint8_t tank1pipes[][6] = {"1Node","2Node"};
    uint8_t tank2pipes[][6] = {"3Node","4Node"};
    
    if (argc > 1)
    {
        int tank;
        sscanf(argv[1],"%d", &tank);
        int num;
        sscanf(argv[2],"%d", &num);
        
        radio.begin();
        
        radio.setRetries(15,15);
        
        if(tank>0 && tank < 3){
            if(tank==1)
            {
                radio.openWritingPipe(tank1pipes[1]);
                radio.openReadingPipe(1,tank1pipes[0]);
            }
            if(tank==2)
            {
                radio.openWritingPipe(tank2pipes[1]);
                radio.openReadingPipe(1,tank2pipes[0]);
            }
            bool ok = radio.write( &num, sizeof(int) );
            if (!ok){
                printf("failed.\n");
            }
        }
        else
        {
            printf("Usage: senddata <tanknumber> <action number>\n");
        }
    }
    else
    {
        printf("Usage: senddata <tanknumber> <action number>\n");
    }
    
    return 0;
}
Example #17
0
boolean pcmRX::txSel(byte sel, int timeoutDelay){
  radi.write(&sel,sizeof(byte));
  int result = radi.getDynamicPayloadSize();
  if( result == 2 ){  return(1);}
  else{
	  Serial.println(result);
      if(result > 32){

		  SPI.setBitOrder(MSBFIRST);
		  SPI.setDataMode(SPI_MODE0);
		  SPI.setClockDivider(SPI_CLOCK_DIV4);
		  digitalWrite(csPin,LOW);
		  SPI.transfer( FLUSH_RX );
		  digitalWrite(csPin,HIGH);

      }
      if(timeoutDelay > 0){ delay(timeoutDelay);}  return(0);
  }
}
Example #18
0
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);
}
Example #19
0
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(void)
{
  DHT11Readings payload = getReadings();

  Serial.print("Humidity (%): ");
  Serial.println(payload.humidity);

  Serial.print("Temperature (°C): ");
  Serial.println(payload.temperature);

  radio.stopListening();

  Serial.print(F("Now sending length "));
  Serial.println(sizeof(payload));
  radio.write(&payload, sizeof(payload));

  // Now, continue listening
  radio.startListening();

  delay(55000);
}
Example #21
0
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();
 }
}
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();
    }
  }
}
Example #24
0
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);
}
Example #25
0
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;
  }
}
Example #26
0
boolean txSelX(byte sel, int timeoutDelay){
  radi.write(&sel,1);
  if(radi.isAckPayloadAvailable() == 1){ radi.read(&tmpArr,sizeof(tmpArr)); return(1);}
  else{ if(timeoutDelay > 0){ delay(timeoutDelay);}  return(0); }
}
Example #27
0
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);
}
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);
  }


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

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