Hi,
I want to be able to write to a digipot and read wiper resistance.
My code is based on a widely published example to to control the wipers, but I can't find an extension to this approach for reading.
I have attempted to write a read function. This does not work, in the sense that expected data assigned to 'res' remains zero under all attempts.
Could some one help me understand what I am doing wrong, please?
John
/* Attempt to control and read wiper resistance of digital potenetiometer MCP4231.
Arduino pins are connected conventionally: 11 = MOSI, 12 = MISO, 13 = CLK.
Control loops (based on many published examples) work fine.
Can't find suitable example of a read function as simple extension of this.
My attempted read function produces no errors, but 'res' variable prints zero.
What have I done wrong?
*/
//Include SPI library
#include <SPI.h>
//By default, 11 = MOSI, 12 = MISO, 13 = CLK
const int SS1=10; //Slave Select Chip 1
//const int SS2=9; //Slave Select Chip 2
const byte REG0=B00000000; //Register 0 Write command
const byte REG1=B00010000; //Register 1 Write command
const byte rdREG0=B00001100; //pot 0 read command
const byte rdREG1=B00011100; //pot 1 read command
void setup()
{
//Set pin directions for SS
pinMode(SS1, OUTPUT);
//pinMode(SS2, OUTPUT);
//Initialize SPI
SPI.begin();
Serial.begin(9600); //Sets up serial port for monitoring (if required)
}
void setPot(int SS, int reg, int level)
{
digitalWrite(SS, LOW); //Set the given SS pin low
SPI.transfer(reg); //Choose the register to write to
SPI.transfer(level); //Set the LED level (0-128)
digitalWrite(SS, HIGH); //Set the given SS pin high again
}
// attempt to implement a read function
void rdPot(int SS, int rdreg, int res)
{
digitalWrite(SS, LOW); //Set the given SS pin low
SPI.transfer(rdreg); //Choose the register to read from
SPI.transfer(res); //read resistance
digitalWrite(SS, HIGH); //Set the given SS pin high again
}
void loop()
{
for (int i=0; i<=128; i++)
{
int res=0;
setPot(SS1, REG0, i);
setPot(SS1, REG1, i);
rdPot(SS1, rdREG1, res);
Serial.print(i);
Serial.print("\t");
Serial.print(SS1);
Serial.print("\t");
Serial.print(rdREG1, BIN);
Serial.print("\t");
Serial.print(res);
Serial.print("\t");
Serial.println(res, BIN);
delay(100);
}
delay(100);
for (int i=128; i>=0; i--)
{
setPot(SS1, REG0, i);
setPot(SS1, REG1, i);
// setLed(SS2, REG0, i);
//setLed(SS2, REG1, i);
delay(100);
}
delay(100);
}