這一個範例是說明如何使用Mega2560與MCP23018作I2C通訊,

MCP23018為一個16通道的IO擴充IC,可以一口氣增加16個Digtal input 與 output,

在使用Arduino的通訊協定時,我們會用到Wire的函式庫,所以一開始要將Wire.h include進來,

我參考了一些網站來撰寫這個範例:

1. https://github.com/maniacbug/Arduino/blob/master/Double_Seven_LED_Test/Double_Seven_LED_Test.pde

2. http://byterule.com/2013/8/21/i2c-arduino-to-mcp-23018.aspx

3. http://www.arduino.cc/en/reference/wire

基本的接腳為:

MCP23018/Arduino

Addr -> gnd  (gets mcpaddr for wire of 0x20)

Reset-> V+

VSS -> gnd

Vdd -> v+

SDA->  20 W/pullup resistor 1.5K+

SCL ->  21 W/pullup resistor 1.5K+

GPB0--> LED G

GPB1--> LED B

GPB2--> LED R

 

Arduino code為:

#include <Wire.h>

const uint8_t I2C_MCP23018 = B0100000;

// MCP23018 registers

const uint8_t IODIRA = 0x0;
const uint8_t IODIRB = 0x1;
const uint8_t IOCON = 0xA;
const uint8_t IOCON_SEQOP[] = { IOCON, 5 };
const uint8_t GPPUA = 0x0C;
const uint8_t GPPUB = 0x0D;
const uint8_t GPIOA = 0x12;
const uint8_t GPIOB = 0x13;
const uint8_t OLATA = 0x14;
const uint8_t OLATB = 0x15;

void setup()
{
  Serial.begin(9600); //start serial for debug purpose

  delay(2000); //wait for the pc to be able to connect to serial this is due to some issues with serial communications and my pc I think due to the number of devices connected oh well
 
  Wire.begin();
 
  // Set all pins to outputs
  Wire.beginTransmission(I2C_MCP23018);    
  Wire.write(IODIRA);
  Wire.write(0x00);    
  Wire.write(0x00);
  Wire.endTransmission();
}

void loop()
{
  Wire.beginTransmission(I2C_MCP23018);    
  Wire.write(GPIOA);
  Wire.write(0xff);    
  Wire.write(B00000001); //set PGPB0 1/high
  Wire.endTransmission();
  delay(1000);
  Wire.beginTransmission(I2C_MCP23018);    
  Wire.write(GPIOA);
  Wire.write(0xff);    
  Wire.write(B00000010); //set PGPB1 1/high
  Wire.endTransmission();
  delay(1000);
  Wire.beginTransmission(I2C_MCP23018);    
  Wire.write(GPIOA);
  Wire.write(0xff);    
  Wire.write(B00000100); //set PGPB2 1/high
  Wire.endTransmission();
  delay(1000);
}

Mega2560與MCP23018接線狀況:

mcp23018 001.jpg mcp23018 002.jpg  

RGB LED的控制狀況: 紅,綠,藍顏色會每一秒做一次變化。

 

 

 

 

創作者介紹
創作者 fishark 的頭像
fishark

魚的方舟 * 圖形語言的世界* - LabVIEW 工作室 & APP開發研究室 & Arduino整合開發 -

fishark 發表在 痞客邦 留言(0) 人氣()