microrobotics icon

Untitled

microrobotics | PRO | 05/06/23 04:06:34 AM UTC | 0 ⭐ | 2632 👁️ | Never ⏰ | [AD7793, A to D, 24 Bit]
Arduino |

2.32 KB

|

None

|

0 👍

/

0 👎

#include <SPI.h>
 
// AD7793 register addresses
#define AD7793_REG_COMM 0x00
#define AD7793_REG_MODE 0x01
#define AD7793_REG_CONFIG 0x02
#define AD7793_REG_DATA 0x03
 
// AD7793 command codes
#define AD7793_CMD_WRITE 0x10
#define AD7793_CMD_READ 0x20
 
// AD7793 mode codes
#define AD7793_MODE_SINGLE 0x0800
 
// AD7793 configuration codes
#define AD7793_CONFIG_GAIN(x) (((x) & 0x07) << 8)
#define AD7793_CONFIG_REFSEL(x) (((x) & 0x01) << 15)
 
// AD7793 reference selection codes
#define AD7793_REFSEL_INTERNAL 0
#define AD7793_REFSEL_EXTERNAL 1
 
// SPI pin definitions
#define AD7793_CS_PIN 10
 
// Function prototypes
void AD7793_WriteRegister(unsigned char regAddress, unsigned long regValue);
unsigned long AD7793_ReadRegister(unsigned char regAddress);
 
void setup() {
  // Initialize SPI interface
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);
  SPI.setClockDivider(SPI_CLOCK_DIV8);
 
  // Configure AD7793
  AD7793_WriteRegister(AD7793_REG_MODE, AD7793_MODE_SINGLE);
  AD7793_WriteRegister(AD7793_REG_CONFIG, AD7793_CONFIG_GAIN(1) | AD7793_CONFIG_REFSEL(AD7793_REFSEL_INTERNAL));
}
 
void loop() {
  // Read data from AD7793
  unsigned long data = AD7793_ReadRegister(AD7793_REG_DATA);
 
  // Do something with the data
  // ...
 
  // Wait for a bit before reading again
  delay(100);
}
 
void AD7793_WriteRegister(unsigned char regAddress, unsigned long regValue) {
  // Send command byte
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE1));
  digitalWrite(AD7793_CS_PIN, LOW);
  SPI.transfer(AD7793_CMD_WRITE | regAddress);
 
  // Send register value
  SPI.transfer((regValue >> 16) & 0xFF);
  SPI.transfer((regValue >> 8) & 0xFF);
  SPI.transfer(regValue & 0xFF);
 
  digitalWrite(AD7793_CS_PIN, HIGH);
  SPI.endTransaction();
}
 
unsigned long AD7793_ReadRegister(unsigned char regAddress) {
  unsigned long regValue = 0;
 
  // Send command byte
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE1));
  digitalWrite(AD7793_CS_PIN, LOW);
  SPI.transfer(AD7793_CMD_READ | regAddress);
 
  // Read register value
  regValue |= (unsigned long)SPI.transfer(0) << 16;
  regValue |= (unsigned long)SPI.transfer(0) << 8;
  regValue |= (unsigned long)SPI.transfer(0);
 
  digitalWrite(AD7793_CS_PIN, HIGH);
  SPI.endTransaction();
 
  return regValue;
}

Comments