Exemplo n.º 1
0
void loop()
{
  if (Serial.available())
    if (mySerial.available())
      mySerial.println(Serial.read());
      Serial.write(mySerial.read());
}
void loop()
{
    sendMsg = "";
    recvMsg = "";
    while (Serial.available()) {
        sendMsg += (char)Serial.read();
        delay(2);
    }

    if(sendMsg.length() > 0)
    {
        mySerial1.println(sendMsg);
        Serial.print("I send: ");
        Serial.println(sendMsg);
    }
    while (mySerial2.available()) {
        recvMsg += (char)mySerial2.read();
        delay(2);
    }
    if(recvMsg.length() > 0)
    {
        Serial.print("I recv: ");
        Serial.println(recvMsg);
    }
    //delay(20);
}
Exemplo n.º 3
0
void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}
boolean readRFID() {
	//if (RFID.available()) RFID.flush();
	digitalWrite(RFID_ENABLE, LOW);    // Activate the RFID reader
	
	for (byte i = 0; i < RFID_LENGTH; i++)
		rfidCode[i] = 0;

	if (RFID.available()) {
		int val = RFID.read();
		Serial.print(val);

		if (val == RFID_START_CHAR) {
			RFID.readBytes(rfidCode, RFID_LENGTH);

			Serial.print("RFID Read: ");
			Serial.println(rfidCode);

			digitalWrite(RFID_ENABLE, HIGH);   // deactivate the RFID reader for a moment so it will not flood
			RFID.flush();                      // clear the buffer
			delay(1500);                       // wait for a bit

			return true;
		 }
	}
	return false;
}
Exemplo n.º 5
0
void loop() // run over and over
{
  int i = 0;
  bool found = false;

  raw_packet com;

  while(usb.available()){
    found = true;
    if(i < 8){
      com.raw[i] = usb.read();
    } else{
      break;
    }
    i++;
  }

  if(!found){
    return;
  }

  packet curpacket = com.nice;

  if(curpacket.cmd = 1){
    usb.print("hi");
    usb.print("\n");
  }

}
Exemplo n.º 6
0
void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}
Exemplo n.º 7
0
/* This function sets the name of an RN-42 module
   name should be an up to 20-character value. It MUST BE TERMINATED by a 
   \r character */
uint8_t makeyMateClass::setName(char * name)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

  bluetooth.print("SN,");
  for (int i=0; i<20; i++)
  {
    if (name[i] != '\r')
      bluetooth.write(name[i]);
    else
      break;
  }
  bluetooth.write('\r');
  
  delay(BLUETOOTH_RESPONSE_DELAY);
  bluetoothReceive(rxBuffer);

  /* Double check the setting, output results in Serial monitor */
  bluetooth.flush();
  bluetooth.print("GN");
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  Serial.print("Name set to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());

  return bluetoothCheckReceive(rxBuffer, "AOK", 3);
}
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";
    
    esp8266.print(command); // send the read character to the esp8266
    
    long int time = millis();
    
    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        
        // The esp has data so display its output to the serial window 
        char c = esp8266.read(); // read the next character.
        response+=c;
      }  
    }
    
    if(debug)
    {
      Serial.print(response);
    }
    
    return response;
}
/* sendPacket() is called by just about every other member function. It calculates 
	some CRC bytes, then sends the message string.
	If a response is requested, it'll return that in the response array. Otherwise
	that and the responseLength variable should be 0.
	
	If you're using a bluetooth module that's not the RN-42, this'd be the place
	to modify.
*/
void SFE_MetaWatch::sendPacket(unsigned char * data, int length, unsigned char * response, int responseLength)
{
	int crc = ComputeCRC(data, length - 2);	// Get the crc values for our string
	data[length-1] = (crc & 0xFF00) >> 8;	// LSB goes first
	data[length-2] = crc & 0xFF;	// the MSB

	// If you want a response, let's flush out the bt buffer first.
	if (responseLength > 0)
		bt.flush();
	
	// Send the data out to the BlueSMiRF
	for (int i=0; i<length; i++)
	{
		bt.write(data[i]);
	}
	
	// If a response was requested, read that into the response array.
	if (responseLength > 0)
	{
		delay(BLUETOOTH_RESPONSE_DELAY);
		int i=0;
		while (bt.available() && (i < responseLength))
		{
			response[i++] = bt.read();
		}
	}
}
void ncArduinoPollGetData()
{
  int c;
  while (mySerial.available() > 0)
  {
    c = mySerial.read();
    byteStreamToPackageStream((unsigned char) c);
  }
}
Exemplo n.º 11
0
void setupBlueToothConnection()
{
  blueToothSerial.begin(38400); 
  blueToothSerial.print("\r\n+STWMOD=1\r\n");
  blueToothSerial.print("\r\n+STNA=SeeedBTMaster\r\n");
  blueToothSerial.print("\r\n+STAUTO=0\r\n");
  delay(2000); 
  blueToothSerial.flush();
  blueToothSerial.print("\r\n+INQ=1\r\n");
  Serial.println("inquiring");
  delay(2000); 
  
  char recvChar;
 /* while(1){                                       //this part is for auto detecting and connecting to a slave but something is wrong with the parsing of the address, use this to print out the address and then put it in manulely 								below
    if(blueToothSerial.available()){
     recvChar = blueToothSerial.read();
      recvBuf += recvChar;
      nameIndex = recvBuf.indexOf(slaveName);
  
      if ( nameIndex != -1 ){
        
 	addrIndex = (recvBuf.indexOf(retSymb,(nameIndex - retSymb.length()- 18) ) + retSymb.length());	 		
 	slaveAddr = recvBuf.substring(addrIndex, nameIndex);			
 	break;
      }
   }
 }*/
  
  connectCmd += slaveAddr;
  connectCmd += "\r\n";
  int connectOK = 0;
  Serial.print("Connecting to slave:");
  Serial.print(slaveAddr);
  Serial.println(slaveName);

  do{
    blueToothSerial.print("/*put slave address here*/");
    recvBuf = "";
    while(1){
      if(blueToothSerial.available()){
        recvChar = blueToothSerial.read();
 	recvBuf += recvChar;
 	if(recvBuf.indexOf("CONNECT:OK") != -1){
          connectOK = 1;
 	  Serial.println("Connected!");
 	  blueToothSerial.print("Connected!");
 	  break;
 	}else if(recvBuf.indexOf("CONNECT:FAIL") != -1){
 	  Serial.println("Connect again!");
 	  break;
 	}
      }
    }
  }while(0 == connectOK);
}
Exemplo n.º 12
0
/* This function will attempt a connection to the stored remote address
   The first time you connect the the RN-42 HID, the master device will
   need to initiate the connection. The first time a connection is made
   the bluetooth address of the master device will be stored on the RN-42.
   If no remote address is stored, a connection will not be made. */
uint8_t makeyMateClass::connect()
{
  freshStart();  // Get the module disconnected, and out of command mode
  
  while (!enterCommandMode())
  {  // Enter command mode
    delay(BLUETOOTH_RESPONSE_DELAY);
  }
  delay(BLUETOOTH_RESPONSE_DELAY);
  bluetooth.flush();
  
  /* get the remote address and print it in the serial monitor */
  bluetooth.print("GR");  // Get the remote address
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  if (bluetooth.peek() == 'N')  // Might say "No remote address stored */
  {  // (bluetooth address is hex values only, so won'te start with 'N'.
    Serial.println("Can't connect. No paired device!");
    bluetooth.flush();
    bluetooth.print("---");  // exit command mode
    bluetooth.write('\r');
    return 0;  // No connect is attempted
  }
  else if (bluetooth.available() == 0)  
  { // If we can't communicate with the module at all, print error
    Serial.println("ERROR!");
    return 0;  // return error
  }
  /* otherwise print the address we're trying to connect to */
  Serial.print("Attempting to connect to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());
    
  /* Attempt to connect */
  bluetooth.print("C");  // The connect command
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  while (bluetooth.available())
    Serial.write(bluetooth.read());  // Should print "TRYING"
  
  return 1;
}
Exemplo n.º 13
0
 String read()
 {
   String msg = "";
   while (bluetoothModule->available() > 0)
   {
     char c = (char)bluetoothModule->read();
     if(c != '\n')
       msg += c;
   }
   return msg;
 }
Exemplo n.º 14
0
void loop()
{ 
  SoftwareSerial RFID = SoftwareSerial(rxPin,txPin);
  RFID.begin(RFID_SPEED);
  digitalWrite(LED,LOW);

  if((val = RFID.read()) == 10)
  {   // check for header 
    bytesread = 0; 
    
    while(bytesread<10)
    {  // read 10 digit code 
      val = RFID.read(); 
      if((val == 10)||(val == 13))
      {  // if header or stop bytes before the 10 digit reading 
        break;                       // stop reading 
      } 
      code[bytesread] = val;         // add the digit
      bytesread++;                   // ready to read next digit  
    } 

    // if 10 digit read is complete 
    if(bytesread == 10)
    {
      strCode.clear();
      strCode.append(code);
      if( strCode.equals(strOldCode.getChars()) ) {
        // nop  
      }else{
        Serial.print(code);            // print the TAG code
        digitalWrite(LED,HIGH);
        strOldCode = strCode;
        MsTimer2::start();             // Timer start
      }
    }
    bytesread = 0; 
    delay(WAIT_INTERVAL);              // wait for a second
  } 
} 
Exemplo n.º 15
0
void loop()
{
  if(esp8266.available()) // check if the esp is sending a message 
  {
    /*
    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window 
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    } */
    
    if(esp8266.find("+IPD,"))
    {
     delay(1000);
 
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns 
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
     
     String webpage = "<h1>Hello</h1>&lth2>World!</h2><button>LED1</button>";
 
     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";
     
     sendData(cipsend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);
     
     webpage="<button>LED2</button>";
     
     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";
     
     sendData(cipsend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);
 
     String closeCommand = "AT+CIPCLOSE="; 
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";
     
     sendData(closeCommand,3000,DEBUG);
    }
  }
}
Exemplo n.º 16
0
void sport_check(void)
{
  if (s_mode == SERIAL_RX) {
    while (sportSerial.available() && (s_mode == SERIAL_RX)) {
      const int data = sportSerial.read();
      if (data < 0) {
        break;
      }
      sport_byte_received(static_cast<uint8_t>(data));
    }
  }
  else {
    sport_set_serial(SERIAL_RX);
  }
}
Exemplo n.º 17
0
/******************
   cMsgBytes
   Send a byte array message, expect an ACK
*/
int LoRaModem::cMsgBytes(uint8_t * bytes, int16_t length) {

  _LoRaSerial.read();
  _LoRaSerial.print("AT+CMSGHEX=\"");

  do {
    prnt("%02x", *bytes++);
  } while (--length);

  _LoRaSerial.println("\"");

  if (_checkresponse(".+ACK Received.+CMSGHEX: Done"))
  {
    return 1;
  }

  return 0;
};
void loop()
{
if (GPRS.available()) // if date is comming from software serial port
	{
	while(GPRS.available()) // reading data into char array
		{
		buffer[count++]=GPRS.read(); // writing data into array
		if(count == 64)	break;
		}

	Serial.write(buffer,count); // if no data transmission ends, write buffer to hardware serial port
	clearBufferArray(); // call clear BufferArray function to clear the storage data from the array
	count = 0; // set counter of while loop to zero
	}

 if (Serial.available()) // if data is available on hardware serial port ==> data is comming from PC or notebook
 GPRS.write(Serial.read()); // write it to the GPRS shield
 }
Exemplo n.º 19
0
/* This function reads all available characters on the bluetooth RX line
   into the dest array. It'll exit on either timeout, or if the 0x0A 
   (new line) character is received. */
uint8_t makeyMateClass::bluetoothReceive(char * dest)
{
  int timeout = 1000;
  char c;
  int i = 0;

  while ((--timeout > 0) && (c != 0x0A))
  {
    if (bluetooth.available())
    {
      c = bluetooth.read();
      if (c != 0x0D)
        dest[i++] = c;
      timeout = 1000;	// reset timeout
    }
  }

  return timeout;
}
Exemplo n.º 20
0
/* This function will set the RN-42 into HID mode, from SPP mode.
   Requires a reboot to take effect! */
uint8_t makeyMateClass::setHIDMode(void)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

    bluetooth.print("S~,6");  // Bluetooth HID Mode
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  bluetoothReceive(rxBuffer);

  /* Double check the setting, output results in Serial monitor */
  bluetooth.flush();
  bluetooth.print("G~");
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  Serial.print("Profile set to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());

  return bluetoothCheckReceive(rxBuffer, "AOK", 3);
}
Exemplo n.º 21
0
/* This function can send one of the 5 special configuration commands:
   0: Disable all special commands
   4: Disable reading values of GPIO3 and 6 on power-up.
   16: Configure firmware to optimize for low-latency transfers.
   128: Allow for fast reconnect.
   256: Set 2-stop bit mode on UART.
   
   Most of these are not recommended, but the low-latency is useful. */
uint8_t makeyMateClass::setSpecialConfig(uint8_t num)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

    bluetooth.print("SQ,");  // SQ sets special config
  bluetooth.print(num);  // Should print ASCII decimal vaule
  bluetooth.write('\r');

  delay(BLUETOOTH_RESPONSE_DELAY);  // Response will go to software serial buffer
  bluetoothReceive(rxBuffer);

  /* Double check the setting, output results in Serial monitor */
  bluetooth.flush();
  bluetooth.print("GQ");
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  Serial.print("Special Config set to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());

  return bluetoothCheckReceive(rxBuffer, "AOK", 3);  
}
Exemplo n.º 22
0
/* This function enables or disables authentication (pincode pairing)
   Two options are available for Authmode:
   0: Disabled
   1: Enabled */
uint8_t makeyMateClass::setAuthentication(uint8_t authMode)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

    bluetooth.print("SA,");  // SA sets the authentication
  bluetooth.print(authMode);  // Should print ASCII vaule
  bluetooth.write('\r');

  delay(BLUETOOTH_RESPONSE_DELAY);  // Response will go to software serial buffer
  bluetoothReceive(rxBuffer);

  /* Double check the setting, output results in Serial monitor */
  bluetooth.flush();
  bluetooth.print("GA");
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  Serial.print("Authentication Mode set to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());

  return bluetoothCheckReceive(rxBuffer, "AOK", 3);
}
Exemplo n.º 23
0
/* This function enables low power SNIFF mode. Send a 4-byte string as the 
   sleepConfig variable
   "0000" = disabled
   e.g.: "0050" = Wake up every 50ms
   "8xxx" = Enables deep sleep mode */
uint8_t makeyMateClass::setSleepMode(char * sleepConfig)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

    bluetooth.print("SW,");  // SW sets the sniff mode
  bluetooth.print(sleepConfig);  // Should print ASCII vaule
  bluetooth.write('\r');

  delay(BLUETOOTH_RESPONSE_DELAY);  // Response will go to software serial buffer
  bluetoothReceive(rxBuffer);

  /* Double check the setting, output results in Serial monitor */
  bluetooth.flush();
  bluetooth.print("GW");
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  Serial.print("Deep Sleep Mode set to: ");
  while (bluetooth.available())
    Serial.write(bluetooth.read());

  return bluetoothCheckReceive(rxBuffer, "AOK", 3);
}
/* echoMode() will set up an echo interface betwen bluetooth and the Arduino hardware serial
	This is mostly useful if you're having trouble connecting from the BlueSMiRF to MetaWatch.
	
	Anything sent to the Arduino's hardware serial (e.g. entered into the Serial Monitor)
	will be echoed out to the software serial (bluetooth module). ANything sent to the bluetooth
	module will be echoed out of the Arduino's hardware serial (e.g. visible in the Serial monitor).
	
	It's not recommended to try to send message packets to the watch using this echo mode (unless
	you're some kind of genius CRC calculator).
	
	To exit echo mode, type ~~~.
*/
void SFE_MetaWatch::echoMode()
{
	int c;
	int tildeCount = 0;
	Serial.println("Echo mode. Press ~~~ to escape.");

	while(tildeCount < 3)
	{
		if (bt.available())
		{
			c = bt.peek();
			Serial.write(bt.read());
			if (c == '~') tildeCount++;
		}
		if (Serial.available())
		{
			c = Serial.peek();
			bt.write(Serial.read());
			if (c == '~') tildeCount++;
		}
	}
	Serial.println("Exiting echo mode...");
}
Exemplo n.º 25
0
/* freshStart() attempts to get the module into a known state from 
 any of these 3 possible states:
 1) Connected - Sending 0 will disconnect the module, then we'll put 
 it into command mode
 2) Disconnected - In this case, we'll just get it into command mode
 3) Disconnected, already in Command Mode - Sending 0 makes the module
 unresponsive until an undefined \r\n's are sent. I can't find any 
 reason for this in the RN-42 User manual 
 
 Once this function has completed, the RN-42 should be disconnected, 
 in non-command mode */
void makeyMateClass::freshStart(void)
{
  int timeout = 1000;  // timeout, in the rare case the module is unresponsive
  bluetooth.write((uint8_t) 0);	// Disconnects, if connected
  delay(BLUETOOTH_RESPONSE_DELAY);
  
  bluetooth.flush();  // delete buffer contents
  bluetooth.print("$$$");  // Command mode string
  do // This gets the module out of state 3
  {  // continuously send \r until there is a response, usually '?'
    bluetooth.write('\r');  
    Serial.print("-");  // Debug info for how many \r's required to get a respsonse
  } while ((!bluetooth.available()) && (timeout-- > 0));
  
  while (bluetooth.available())
    Serial.write(bluetooth.read());
  delay(BLUETOOTH_RESPONSE_DELAY);
  bluetooth.flush();  // delay and flush the receive buffer
  
  bluetooth.print("---");  // exit command mode
  bluetooth.write('\r');
  delay(BLUETOOTH_RESET_DELAY);  // longer delay
  bluetooth.flush();  // Flush the receive buffer
}
Exemplo n.º 26
0
uint8_t 	EV3_Setup(uint8_t port, uint8_t type)  // Sets up the sensor to data mode
{
	if(port == PORT_1){  // PORT_1
    DDRC |= 0x04;   // Set the Rx pin as output
    DDRC &= 0xFE;

    uint8_t mode;   // Calculate the mode as a number 
    if(type < TYPE_SENSOR_EV3_COLOR_M0)
      mode = type - TYPE_SENSOR_EV3_US_M0;
    else if(type < TYPE_SENSOR_EV3_GYRO_M0)
      mode = type - TYPE_SENSOR_EV3_COLOR_M0;
    else if(type < TYPE_SENSOR_EV3_INFRARED_M0)
      mode = type - TYPE_SENSOR_EV3_GYRO_M0;
    else if(type < TYPE_SENSOR_EV3_INFRARED_M5+1)
      mode = type - TYPE_SENSOR_EV3_INFRARED_M0;
    else mode = 0;


    data16[0] = dat16[type-43];
    sets[0] = setsd[type-43];

    sensor1.begin(2400);  // Start SoftwareSerial at base Baud rate
    sensor1.write(BYTE_ACK);  // Write ACK 
    setupDone=false;    
    while(!setupDone){
      if(sensor1.available()){   // Check if data is available 
        if(sensor1.read() == BYTE_ACK){   // if an ACK Byte was read
          delay(1);
          sensor1.write(BYTE_ACK);      // Write 2 ACKs (because, sometimes SoftwareSerial might not write the data properly)
          delay(1);
          sensor1.write(BYTE_ACK);
          sensor1.end();
          sensor1.flush();
          sensor1.begin(57600);     // Try to read at higher baud rate
          delay(10);
          if((sensor1.read() & CMD_MASK) == CMD_DATA){  // If the sensor had entered Data Mode
            sensor1.write(BYTE_NACK);     // Write NACK at higher baud rate
              setupDone=true;   // quit setup
          }
          else {        // if corrupt data or no data was received, go back to base baud rate
            sensor1.end();      
            sensor1.begin(2400);
          }
        }
      }
    }

    sensor1.write(BYTE_NACK);   // Keep the sensor in Data mode
    if(mode != 0){              // If a mode other than 0 is required, write the mode datas
      sensor1.write(CMD_SELECT);
      sensor1.write(mode);
      sensor1.write(check(0x00,CMD_SELECT,mode));
    }
    sensor1.write(BYTE_NACK);
  }
  else{                    // PORT_2
    DDRC |= 0x08; 
    DDRC &= 0xFD;

    uint8_t mode;
    if(type < TYPE_SENSOR_EV3_COLOR_M0)
      mode = type - TYPE_SENSOR_EV3_US_M0;
    else if(type < TYPE_SENSOR_EV3_GYRO_M0)
      mode = type - TYPE_SENSOR_EV3_COLOR_M0;
    else if(type < TYPE_SENSOR_EV3_INFRARED_M0)
      mode = type - TYPE_SENSOR_EV3_GYRO_M0;
    else if(type < TYPE_SENSOR_EV3_INFRARED_M5+1)
      mode = type - TYPE_SENSOR_EV3_INFRARED_M0;
    else mode = 0;

    data16[1] = dat16[type-43];
    sets[1] = setsd[type-43];

    sensor2.begin(2400);
    sensor2.write(BYTE_ACK);
    setupDone=false;
    while(!setupDone){
      if(sensor2.available()){
        if(sensor2.read() == BYTE_ACK){
          delay(1);
          sensor2.write(BYTE_ACK);
          delay(1);
          sensor2.write(BYTE_ACK);
          sensor2.end();
          sensor2.flush();
          sensor2.begin(57600);
          delay(10);
          if((sensor2.read() & CMD_MASK) == CMD_DATA){
            sensor2.write(BYTE_NACK);
              setupDone=true;
          }
          else {
            sensor2.end();
            sensor2.begin(2400);
          }
        }
      }
    }

    sensor2.write(BYTE_NACK);
    if(mode != 0){
      sensor2.write(CMD_SELECT);
      sensor2.write(mode);
      sensor2.write(check(0x00,CMD_SELECT,mode));
    }
    sensor2.write(BYTE_NACK);
  }
  return 0;
}
Exemplo n.º 27
0
long	EV3_Update(uint8_t port)
{
	if( port == PORT_1 ){

    sensor1.write(BYTE_NACK);   // To keep the sensor in data mode
    if(sensor1.available())
	{
      se = sensor1.read();      // Read the first CMD byte
      if ( (se & CMD_MASK) == CMD_DATA ){ // if it is data
        ret = 0;
        byte chk = 0xff^se;       // Checksum 
        for(byte n=0 ; n < sets[0] ; n++ ){   // read all sets
          l[n] = sensor1.read();
          m[n] = (data16[0])? sensor1.read() : 0;
          chk = chk^l[n]^m[n];
          ret = (ret<<(data16[0]?16:8)) ;
          ret |= (m[n]<<8) | l[n] ;
        }
        if (sensor1.read() == chk){ // if the checksum is matched, return data
			return ret;
        } else {
			sensor1.flush();    // else flush
        return -2;
        }
      }
    }
    sensor1.write(BYTE_NACK);
/*    sensor1.end();
    sensor1.begin(2400);
    sensor1.write(0x04);
    sensor1.end();
    sensor1.begin(57600);
*/    return -4;
	} else if( port == PORT_2 ){

    sensor2.write(BYTE_NACK);
    if(sensor2.available()){
      se = sensor2.read();
      if ( (se & CMD_MASK) == CMD_DATA ){
        ret = 0;
        byte chk = 0xff^se;
        for(byte n=0 ; n < sets[1] ; n++ ){
          l[n] = sensor2.read();
          m[n] = (data16[1])? sensor2.read() : 0;
          chk = chk^l[n]^m[n];
          ret = (ret<<(data16[1]?16:8));
          ret |= (m[n]<<8) | l[n] ;
        }
        if (sensor2.read() == chk){
          return ret;
        } else {
        sensor2.flush();
        return -2;
        }
      }
    }

    sensor2.write(BYTE_NACK);
/*    sensor2.end();
    sensor2.begin(2400);
    sensor2.write(0x04);
    sensor2.end();
    sensor2.begin(57600);
*/    return -4;
	}
  return -6;
}
Exemplo n.º 28
0
void loop() {
	if (mySerial.available())
		Serial.write(mySerial.read());
	if (Serial.available())
		mySerial.write(Serial.read());
}
Exemplo n.º 29
0
void loop()
{
    //Serial.print(F("Free RAM1:"));    Serial.println(freeRam());

    // Check secret button
    but = !digitalRead(ON_PIN);
    if(but){
        Serial.println(F("Button pressed"));
        secret_button();
    }

    bool GPS_debug = 0;
    unsigned long t = millis();
    while (ss.available() > 0 || t + 1100 < millis()){
        gps.encode(ss.read());
        GPS_debug = 1;
    }
    if (GPS_debug) {
        Serial.println(F("GPS received"));
        GPS_debug = 0;
    }


    sats_fix = gps.satellites.value();
    hdop = gps.hdop.value();
    position_lat = gps.location.lat();
    position_lon = gps.location.lng();

    //target = 3; // debug
    distance = gps.distanceBetween(position_lat, position_lon, target_lat[target], target_lon[target]);

    //distance = 4; // debug

    static int sim, ok;
#ifdef SIMULATION
    if (but == 1){
        sim = 1;
        delay (1000);
    }
    else {
        sim = 0;
        lcd.setCursor(14, 1);
        lcd.print(target);
    }

    if (distance > 30 && sim == 0){
#else
    if (distance > 30) {
#endif
        lcd_target(lcd, target, distance, sats_fix);
    }
    else {

#ifdef BUTTON_FOR_NEXT_STEP
        wait finish;
        finish.set_time(2500);
        finish.set_steps(2);
        lcd.setCursor(0, 0);

        if(finish.step() == 1){
            lcd.print(F("You are at your "));
            lcd.setCursor(0, 1);
            lcd.print(F("current target."));
        }
        if (finish.step() == 2){
            lcd.setCursor(0, 0);
            lcd.print(F("Press the button"));
            lcd.setCursor(0, 1);
            lcd.print(F("to continue...  "));
        }

        if (but == 1){
            // Go to next target
            target++;
            ok = 1;



        }
#else
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(F("You are at your "));
        lcd.setCursor(0, 1);
        lcd.print(F("current target."));
        target++;
        delay(5000);
        but = 0;
#endif
        // Open the box at the end of game
        if(target > NUMBER_OF_TARGETS){
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print(F("CONRATULATIONS! "));
            delay(5000);
            open_box();
        }
        else {
            EEPROM.write(EEPROM_TARGET_INDEX, target);
        }

    }

    if(millis() > update_time + 1000){
        update_time = millis();

        Serial.println(gps.location.lat(), 6);
        Serial.print(F("LAT="));  Serial.println(gps.location.lat(), 6);
        Serial.print(F("LONG=")); Serial.println(gps.location.lng(), 6);
        Serial.print(F("ALT="));  Serial.println(gps.altitude.meters());
        Serial.print(F("hdop="));  Serial.println(hdop);
        Serial.print(F("sats="));  Serial.println(sats_fix);

        if(hdop < 500 && sats_fix > 4){
            fix = 1;
            distance = gps.distanceBetween(position_lat, position_lon, TARGET_1_LAT, TARGET_1_LON);
        }
        else{
            fix = 0;
            strength = sats_fix;
            //lcd_gps_signal(lcd, strength);
        }
    }

    if(millis() > sleep_time + SLEEP_TIME_MS){
        go_sleep();
    }
}

void go_sleep(void)
{
    lcd.clear();
    lcd.print(F("Going to sleep.."));
    delay(2000);
    pinMode(ON_PIN, OUTPUT);
    digitalWrite(ON_PIN, 0);
}
// TODO: This is extremely kludgy right now. 
//		The delay()'s should be made more robust, faster by periodically checking for a response,
//		while still checking for a timeout.
//		Checking for just the first char of a response is a questionabl solution.
//		Needs more testing.  So many unknown states the BlueSMiRF could be in. 
//		We need some flow chart action here.
int SFE_MetaWatch::connect()
{
	char c;
	int timeout = CONNECT_TIMEOUT;
	
	bt.print('\r');	// Clear any previous commands
	delay(BLUETOOTH_RESPONSE_DELAY);
	bt.flush();
	// Entering command mode. Should either print "CMD" or "?" if already there
	while ((c != 'C') && (c != '?') && (timeout > 0))
	{
		bt.print("$$$");	// Enter command mode
		delay(BLUETOOTH_RESPONSE_DELAY);
		c = bt.read();	// Read first character of response
		bt.flush();
		timeout--;
	}
	
	if (timeout == 0)
		return -2;
	else
		timeout = CONNECT_TIMEOUT;
	
	// After sending connect command, should print "TRYING", may also print "ERR-connected"
	while ((c != 'T') && (c != 'E') && (timeout > 0)) 
	{
		bt.print("C,");
		bt.print(watchAddress);
		bt.print('\r');
		delay(BLUETOOTH_RESPONSE_DELAY);
		c = bt.read();
		bt.flush();
		timeout--;
	}
	// If there was an error, try to exit command mode
	if ((c == 'E') || timeout == 0)
	{
		bt.print("---");	// Exit command mode
		bt.print('\r');
		delay(BLUETOOTH_RESPONSE_DELAY);
		bt.flush();
	}
	
	if (timeout == 0)
		return -1;	// Return -1 if connect command error
	else if (c == 'E')
		return 2;	// Return 2 if we think we're already connected
	else
		return 1;	// Return 1 if all went according to plan
}