Exemplo n.º 1
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);
}
Exemplo n.º 2
0
void loop()
{
  if (Serial.available())
    if (mySerial.available())
      mySerial.println(Serial.read());
      Serial.write(mySerial.read());
}
/* 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 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.º 5
0
void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}
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;
}
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.º 8
0
void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}
Exemplo n.º 9
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");
  }

}
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
 }
void ncArduinoPollGetData()
{
  int c;
  while (mySerial.available() > 0)
  {
    c = mySerial.read();
    byteStreamToPackageStream((unsigned char) c);
  }
}
Exemplo n.º 12
0
void GlobalsClass::handle()
{
	if (qCon.available() > 0) checkSerialMsg();

	//alarm time checking
	if (ResetTimeCheck > 0) {
		if (millis() - ResetTimeCheck > (ResetAlarmSeconds * 1000)) { ResetAlarms(); }   //check to see if we've past resetalarm;
	}
}
Exemplo n.º 13
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.º 14
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.º 15
0
 String read()
 {
   String msg = "";
   while (bluetoothModule->available() > 0)
   {
     char c = (char)bluetoothModule->read();
     if(c != '\n')
       msg += c;
   }
   return msg;
 }
Exemplo n.º 16
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.º 17
0
/* This function issues the reboot command, and adds a lengthy delay to 
   give the RN-42 time to restart. */
uint8_t makeyMateClass::reboot(void)
{
  if (bluetooth.available())
    bluetooth.flush();	// Get rid of any characters in the buffer, we'll need to check it fresh

  bluetooth.print("R,1");  // reboot command
  bluetooth.write('\r');
  delay(BLUETOOTH_RESPONSE_DELAY);
  bluetoothReceive(rxBuffer);

  delay(BLUETOOTH_RESET_DELAY);

  return bluetoothCheckReceive(rxBuffer, "Reboot!", 7);
}
Exemplo n.º 18
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.º 19
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.º 20
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);
}
Exemplo n.º 21
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.º 22
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.º 23
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.º 24
0
void loop() {
    
  digitalWrite(b1, LOW);
  digitalWrite(b0, LOW);
  readings[0]=analogRead(1);
  readings[1]=analogRead(2);
  readings[2]=analogRead(3);
  readings[3]=analogRead(4);
  
  digitalWrite(b0, HIGH);
  readings[4]=analogRead(1);
  readings[5]=analogRead(2);
  readings[6]=analogRead(3);
  readings[7]=analogRead(4);
  
  digitalWrite(b1, HIGH);
  digitalWrite(b0, LOW);
  readings[8]=analogRead(1);
  readings[9]=analogRead(2);
  readings[10]=analogRead(3);
  

  
  if(blueToothSerial.available ()) {
    
    char ch = Serial.read();
    
    if (ch >='a') {
      peter=addAction(peter, readings, ch);
      int i;
      for(i=0;i<11;i++)
      {
        blueToothSerial.println(peter->action->high[i]);
      }
    }
    else {
      ch = ch + 32;
      removeAction(ch);
    }
    
  }
  
  p=recognize(readings, p);
}
Exemplo n.º 25
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.º 26
0
int getState () {
    if( !wificmd("CIPSTART=\"TCP\",\"example.com\",8080", "OK")) { //start a TCP connection.
        return 0;
    }
    delay(1000);
    String getRequest = "STATE";

    ESPserial.print("AT+CIPSEND=");
    ESPserial.println(getRequest.length());
    delay(500);

    if(ESPserial.find(">")) {
        clearWifi();
        //Serial.println("Sending..");
        ESPserial.print(getRequest);

        if( ESPserial.find("SEND OK")) {
            //Serial.println("Packet sent");
            String tmpResp = "";
            while (ESPserial.available()) {
                tmpResp = ESPserial.readString();
            }
            // close the connection
            if(wificmd("CIPCLOSE", "OK")) {
                if (tmpResp.substring(11) == "1") {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                Serial.println("Error closing connection");
            }
        } else {
            Serial.println("Error sending data");
        }
    }
    return 0;
}
/* 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.º 28
0
 int available()
 {
   return bluetoothModule->available();
 }
Exemplo n.º 29
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.º 30
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;
}