SHARE
TWEET

TWI Master

a guest Feb 1st, 2014 30 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Written by Nick Gammon
  2. // Date: 18th February 2011
  3. // Modified by Synthetic Physical Computing
  4. // Date: 1st Febuary 2014
  5.  
  6. #include <Wire.h>
  7.  
  8. const int SLAVE_ADDRESS = 0x42;
  9.  
  10. // various commands we might send
  11. enum {
  12.     CMD_ID = 1,
  13.     CMD_READ_A0  = 2,
  14.     CMD_READ_A1  = 3,
  15.     CMD_READ_A2  = 4,
  16.     CMD_READ_A3  = 5,
  17.     CMD_READ_D2  = 6,
  18.     CMD_READ_D3  = 7,
  19.     CMD_READ_D4  = 8,
  20.     CMD_READ_D5  = 9,
  21.     };
  22.  
  23. void sendCommand (const byte cmd, const int responseSize)
  24.   {
  25.   Wire.beginTransmission (SLAVE_ADDRESS);
  26.   Wire.write (cmd);
  27.   Wire.endTransmission ();
  28.  
  29.   Wire.requestFrom (SLAVE_ADDRESS, responseSize);  
  30.   }  // end of sendCommand
  31.  
  32. void setup ()
  33.   {
  34.   Wire.begin ();
  35.   //TWBR = 12;  
  36.   Serial.begin (9600);  // start serial for output
  37.  
  38.   sendCommand (CMD_ID, 1);
  39.  
  40.   if (Wire.available ())
  41.     {
  42.     Serial.print ("Slave is ID: ");
  43.     Serial.println (Wire.read (), HEX);
  44.     }
  45.   else
  46.     Serial.println ("No response to ID request");
  47.  
  48.   }  // end of setup
  49.  
  50. void loop()
  51.   {
  52.   int val;
  53.  
  54.   sendCommand (CMD_READ_A0, 2);
  55.   val = Wire.read ();
  56.   val <<= 8;
  57.   val |= Wire.read ();
  58.   Serial.print ("Value of A0: ");
  59.   Serial.println (val, DEC);
  60.  
  61.   sendCommand (CMD_READ_A1, 2);
  62.   val = Wire.read ();
  63.   val <<= 8;
  64.   val |= Wire.read ();
  65.   Serial.print ("Value of A1: ");
  66.   Serial.println (val, DEC);
  67.  
  68.   sendCommand (CMD_READ_A2, 2);
  69.   val = Wire.read ();
  70.   val <<= 8;
  71.   val |= Wire.read ();
  72.   Serial.print ("Value of A2: ");
  73.   Serial.println (val, DEC);
  74.  
  75.   sendCommand (CMD_READ_A3, 2);
  76.   val = Wire.read ();
  77.   val <<= 8;
  78.   val |= Wire.read ();
  79.   Serial.print ("Value of A3: ");
  80.   Serial.println (val, DEC);
  81.  
  82.   sendCommand (CMD_READ_D2, 1);
  83.   val = Wire.read ();
  84.   Serial.print ("Value of D2: ");
  85.   Serial.println (val, DEC);
  86.  
  87.   sendCommand (CMD_READ_D3, 1);
  88.   val = Wire.read ();
  89.   Serial.print ("Value of D3: ");
  90.   Serial.println (val, DEC);
  91.  
  92.   sendCommand (CMD_READ_D4, 1);
  93.   val = Wire.read ();
  94.   Serial.print ("Value of D4: ");
  95.   Serial.println (val, DEC);
  96.  
  97.   sendCommand (CMD_READ_D5, 1);
  98.   val = Wire.read ();
  99.   Serial.print ("Value of D5: ");
  100.   Serial.println (val, DEC);
  101.  
  102.   delay (500);  
  103.   }  // end of loop
RAW Paste Data
Want to get better at C++?
Learn to code C++ in 2017
Top