Example #1
0
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;
}
Example #2
0
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]);
  }
}
Example #3
0
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);
    }

}
Example #5
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 #6
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);
}
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;
}
Example #8
0
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;
}
Example #9
0
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;
    }
}
Example #10
0
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);
}
Example #12
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 #13
0
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;
   }
}
Example #14
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 #15
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);
}
/*
************** 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);
}
Example #17
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);
}
Example #18
0
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();
      }
      
  }
  
}
Example #19
0
bool COM_24g::receiveFrame(RF24 _radioCom)	// Decode the available frame on the pipe
{

int   len 	= _radioCom.getDynamicPayloadSize();  	// Size of the payload to read
bool  done 	= _radioCom.read(&_payload, len);        // Read the payload

if(done){
//_dataType        = _payload.type;
_dataVersion     = _payload.version;

  switch (_payload.type ) {
    /*case CMD_WHO:
    _data.CMD_WHO.partnum   = _payload.data.CMD_WHO.partnum;
    _data.CMD_WHO.revision  = _payload.data.CMD_WHO.revision;
    _data.CMD_WHO.parttype  = _payload.data.CMD_WHO.parttype;
    return true;
    break;
    */
    case YOUARE:
    _data.YOUARE.partid        = _payload.data.YOUARE.partid;
    _data.YOUARE.baseCmdAdd    = _payload.data.YOUARE.baseCmdAdd;
    _data.YOUARE.base_encode   = _payload.data.YOUARE.base_encode;
    _dataType                  = YOUARE;
    return true;
    break;
   
    
    default:
        //serial.println("Unknown message.");
    break;
    
  }

} else {
 //serial.println("Error of read on the Paypload"); 
 return false;
}


}
Example #20
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();
 }
}
Example #22
0
void pcmRX::pollForMusic(){

  if(!playing){
      int steps = 1;
      //testDataRates2();
    if(steps == 1){
            radi.powerUp();  // << VERY important step for some reason
            delay(5);
            if( txSelX(4,5) ){
              if( tmpArr[0] == 1 && tmpArr[1] == 2 && tmpArr[2] == 3 ){
                steps = 2;  //togLed();//txSelX(5,5); //txSelX(5,50);
              }else{txSelX(5,0); }
            }
    }
    if(steps == 2){
             Serial.println("S2");
             if ( txSel(3,5)){
              radi.read(&intData,sizeof(intData));
              if(intData < 8000 || intData > 22100){Serial.print("st2 "); /*delay(200);Serial.println(intData);*/ return;}
              //Serial.println("strt");
              whichBuff = 0;
              loadSingleBuffer(0); loadSingleBuffer(1);
              buffEmpty[0] = 0; buffEmpty[1] = 0; intCount = 0;
              SAMPLE_RATE = intData;
              if(intData > 20000){SAMPLE_RATE = 20000;}
              //Serial.println("playing");

//              if(timerTracker){  timerTracker=0; startTimer();
//              }else{resumeTimer();}
              if(!playing){ startTimer();
              }else{resumeTimer();}

            }else{ Serial.println("pl2");}
}

  }

}
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();
    }
  }
}
void gotData(void){
	bool rx = 0, blnTXOK = 0, blnTXFail = 0;
	intResult = 0;
	uint8_t pipe_num = 0;
    radio.whatHappened(blnTXOK,blnTXFail,rx, &pipe_num);

	if(blnTXFail){
		intResult = 2;
	}else if(blnTXOK){
		intResult = 1;
	}else if ( rx ){
		intResult = 3;
		uint8_t len = radio.getDynamicPayloadSize();

		bool more_available = true;
		while (more_available)
		{
			// Fetch the payload, and see if this was the last one.
			more_available = radio.read( receive_payload, len );

			// Put a zero at the end for easy printing
			receive_payload[len] = 0;
			
			// Print received packet
			printf("[%d] Data size=%i value=%s\n\r",pipe_num, len,receive_payload);
			
			// next payload can be of different size
			if (more_available){
				len = radio.getDynamicPayloadSize();
			}
		}
	
	}
//	printf("intResult %d %d %d %d \n\r",blnTXOK,blnTXFail,rx,intResult);
	fflush (stdout) ;
//	radio.clearInterrupt();
}
/**
 * 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;
    }
}
Example #26
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 #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;
}