CAN Communication Protocol(Controller Area Network)||CAN Master & Slave ...


MASTER:-

//YOUTUBE.COM/MKINVENTIONS MADHAN CHIRUGURI
#include <SPI.h>
#include <mcp2515.h>

int BTN1 = 4;
int BTN2 = 5;
int BTN3 = 6;
int BTN4 = 7;

int POTA = A0;


struct can_frame canMsg;
MCP2515 mcp2515(10);



void setup() {
  Serial.begin(115200);
  SPI.begin();
  mcp2515.reset();
  mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ);
  mcp2515.setNormalMode();
  

  pinMode(BTN1, INPUT_PULLUP);
  pinMode(BTN2, INPUT_PULLUP);
  pinMode(BTN3, INPUT_PULLUP);
  pinMode(BTN4, INPUT_PULLUP);
  pinMode(POTA, INPUT);
  
    canMsg.can_id  = 0x0F6;
    canMsg.can_dlc = 8;
}

void loop() {

int BUTTON1 = digitalRead(BTN1);
int BUTTON2 = digitalRead(BTN2);
int BUTTON3 = digitalRead(BTN3);
int BUTTON4 = digitalRead(BTN4);
int POTENTIOMETERA = map(analogRead(POTA), 0, 1023, 0, 255);

//Serial.print("POT:");
//Serial.println(POTENTIOMETERA);

//Serial.print("BUTTON:");
//Serial.println(BUTTON1);
//Serial.println(BUTTON2);
//Serial.println(BUTTON3);
//Serial.println(BUTTON4);

  canMsg.data[0] = BUTTON1;
  canMsg.data[1] = BUTTON2;
  canMsg.data[2] = BUTTON3;
  canMsg.data[3] = BUTTON4;
  canMsg.data[4] = POTENTIOMETERA;
  
  mcp2515.sendMessage(&canMsg);
  delay(10);
}

SLAVE:-
#include <SPI.h>
#include <mcp2515.h>


int LED1 = A0;
int LED2 = A1;
int IN1 = 5;
int IN2 = 6;


struct can_frame canMsg;
MCP2515 mcp2515(10);


void setup() {
  Serial.begin(115200);
  SPI.begin();
  mcp2515.reset();
  mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ);
  mcp2515.setNormalMode();

  
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}

void loop() 
{
  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) 
  {   
    if(canMsg.can_id == 0x0F6)
    {
      int BUTTON1 = canMsg.data[0];
      int BUTTON2 = canMsg.data[1];
      int BUTTON3 = canMsg.data[2];
      int BUTTON4 = canMsg.data[3];
      int POTA = canMsg.data[4];
      
      Serial.print("RPM:");
      Serial.println(POTA);
      
      if(BUTTON1 == 0){ digitalWrite(LED1, HIGH);} else{ digitalWrite(LED1, LOW);}
      if(BUTTON2 == 0){ digitalWrite(LED2, HIGH);} else{ digitalWrite(LED2, LOW);}

      
      if(BUTTON3 == 0){ analogWrite(IN1, POTA ); analogWrite(IN2, 0);} 
      else if(BUTTON4 == 0){ analogWrite(IN1, 0); analogWrite(IN2, POTA );}  
      else{ analogWrite(IN1, 0); analogWrite(IN2, 0); }

      
//      Serial.print("BUTTON1:");
//      Serial.println(BUTTON1);
//      Serial.print("BUTTON2:");
//      Serial.println(BUTTON2);
//      Serial.print("BUTTON3:");
//      Serial.println(BUTTON3);
//      Serial.print("BUTTON4:");
//      Serial.println(BUTTON4);

//      Serial.print("POTB:");
//      Serial.println(POTB);
//      Serial.print("POTC:");
//      Serial.println(POTC);
      delay(10);
    }
    
  }
}

Post a Comment

0 Comments