Close

Volume Controller Code

A project log for RasPi Car Computer

Raspberry Pi car computer with Bluetooth connectivity, OBD-II integration, Arduino, and (obligatory) RGB LEDs.

AndrewMcDanAndrewMcDan 05/28/2016 at 21:270 Comments

Code for the volume controller is complete. Pretty simple stuff. Find it on GitHub here.

Here's a breakdown of code:

To start, include some libraries, declare some globals. The byte-sized variables are the I2C addresses for the digital potentiometers.

#include <Wire.h>
#include <mcp_can.h>
#include <SPI.h>

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];

MCP_CAN CAN0(9);

byte addr_MSTR_L = B0111100, addr_MSTR_R = B0111110, addr_SUBW_L = B0111101, addr_SUBW_R = B0111111;
setup() is pretty simple too. Start up the Wire library, set our "interrupt" pin for the MCP2515 as input. The CAN bus controller I'm using is a MCP2515 which has interrupt capability when it receives data on the bus that matches the filter. I'm just gonna poll this pin rather than setup and actual interrupt. After starting up the CAN library at 500kbps, we set the receive masks and filters so that we only get messages sent to device ID 0x00F.
void setup() {
  Wire.begin();
  pinMode(8, INPUT);
  CAN0.begin(CAN_500KBPS);
  CAN0.init_Mask(0, 0, 0x7ff);
  CAN0.init_Mask(1, 0, 0x7ff);
  CAN0.init_Filt(0, 0, 0x00f);
  CAN0.init_Filt(1, 0, 0x00f);
  CAN0.init_Filt(2, 0, 0x00f);
  CAN0.init_Filt(3, 0, 0x00f);
  CAN0.init_Filt(4, 0, 0x00f);
  CAN0.init_Filt(5, 0, 0x00f);
}
The loop() runs without doing much unless the "interrupt" pin is driven low, in which case we read the data from the CAN bus and send each byte to its corresponding digital pot.
void loop() {
  //  check for CAN bus interrupt
  //  if interrupt, read data and store, set new flag

  if (!digitalRead(8)) {
    CAN0.readMsgBuf(&len, rxBuf);
    Wire.beginTransmission(addr_MSTR_L);
    Wire.write(0x00);
    Wire.write(rxBuf[0]);
    Wire.endTransmission();
    Wire.beginTransmission(addr_MSTR_R);
    Wire.write(0x00);
    Wire.write(rxBuf[1]);
    Wire.endTransmission();
    Wire.beginTransmission(addr_SUBW_L);
    Wire.write(0x00);
    Wire.write(rxBuf[2]);
    Wire.endTransmission();
    Wire.beginTransmission(addr_SUBW_R);
    Wire.write(0x00);
    Wire.write(rxBuf[3]);
    Wire.endTransmission();
  }
}

Yeah, pretty simple stuff. But it works.

Discussions