/* file: receiveMaskaBIN.ino, lib Master, <multi CAN>
*  demo: CAN-BUS Shield, receive data
* 2014.04.04
* sniffer for CAN, transmitter can
*/
#include <mcp_can.h>
#include <SPI.h>
 
byte myArray160[] = {0x33,0x03,0x50,0xF5,0xE0,0x02,0x28,0x44,0x33,0x23,0x51,0xF1,0xE0,
 01,0x88,0x09,0x20,0x11,0x10,0x13,0x01,0x88,0x09,0x24,0x11,0x10,0x13,01,0x88,0x05,0x28,0x05,0x90,
 0xff,0xff,0xaf,0xaf,0xaf,0xaf,0xf0,0xa0,10,10,10,0xfa,0xfa,0xfa,0x44}; 
 
unsigned char resp0[7] = {0x06, 0x50, 0x60, 0x00, 0x32, 0x01, 0xF4};
 
char stmp[8] = {0xF, 0xE, 0xD, 0xC, 0xB, 0xA, 9, 8};
unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
INT8U stan = 0;
long previousMillis = 0;
INT8U t = 100;      				// delay 20 .. 100 msec.
 
MCP_CAN CAN0(10);           // Set CS to pin 10
 
void setup()
{
  Serial.begin(38400);
  if (CAN0.begin(CAN_50KBPS) == CAN_OK)
    {
      Serial.println("MCP2515 Library Receive Sniffer...");
														// init can bus : baudrate = 50k 
    }
	else Serial.println("init Library failed...");
  pinMode(2, INPUT);        // Setting pin 2 for /INT input
 
  CAN0.init_Filt(0,0,0x7C0);
  Serial.println("filt:0x7C0"); 
  Serial.println();
}
 
void serialEvent() {
	while (Serial.available()) {
		char sdata = (char)Serial.read();
		if (sdata == 'S') {																	// start init.
			CAN0.sendMsgBuf(0x7C0, 0, 7, resp0);  
			delay(t);
			 
		}
	}//-------------- while ------------------
}
 
void loop()
{
    if(!digitalRead(2))                         // If pin 2 is low, read receive buffer
    {
    unsigned long currentMillis = millis();
	  long delta = 0;
	  delta = currentMillis - previousMillis;
	  if (delta > 29000) delta = 10;
	  previousMillis = currentMillis;
		stan = CAN0.readMsgBuf(&len, rxBuf);       // Read data: len = data length, buf = data byte(s)
     rxId = CAN0.getCanId();                    // Get message ID
			Serial.print(" ID:");
      Serial.print(rxId, HEX);
			Serial.print(" ");
			Serial.print(len);
			Serial.print(" ");
			Serial.print("  Data:");
      for(int i = 0; i<len; i++)                // Print each byte of the data
      {
        if(rxBuf[i] < 0x10)                     // If data byte is less than 0x10, add a leading zero
        {
          Serial.print("0");
        }
        Serial.print(rxBuf[i], BIN);
        Serial.print(" ");
      }
	   Serial.print("t:");
	   Serial.print(delta, DEC);
	   Serial.println();
		}//----------------------- if ( digitalRead ------------------
}
