MAX5481 Simple example code

Hi there,
As I struggled just a bit to put my MAX5481 to work as I wanted and because I found a solution a bit based on other codes around, I decided to share a very simple code to control this chip properly.
This code ONLY controls the output wiper in real time using a potentiometer input, for any other function you'll have to research elsewhere.

Enjoy

/*
Code by Nuno Fernandes | nunodlfernandes@gmail.com | 2020
Tested on arduino Nano

This code is using a potentiometer input to control the output of a MAX5481 but you can use any other source you need
just by replacing the potentiometer related lines assigned to "PotValue" which is the variable that is sent to
control the chip within a range of 0 to 1023

You can use an external power source to power the "H" and "L" pins of the chip but keep in mind that the ground
of the external power supply has to be connected to the ground of the arduino circuit

MAX5481 Datasheet link:
https://datasheets.maximintegrated.com/en/ds/MAX5481-MAX5484.pdf

Circuit:
Pin  Name      Connect to what?
1    VDD       +5V (Important: connect a 0.1uF [or larger] ceramic capacitor from VDD to GND
2    GND       GND/0V
3    CS (SS)   Any Arduino pin, let's use D9
4    SCK       Arduino pin D13
5    MOSI      Arduino pin D11
6    SPI/UD    +5V to select SPI mode
7    X
8    X
9    X
10   L         GND/0V; this is the LOW side of the voltage divider
11   W         Vout; this is the wiper on the potentiometer
12   H         +5V; this is the HIGH side of the voltage divider
13   X
14   VSS       GND/0V (make sure to tie this to GND)
*/

#include <SPI.h>
#define CS 9        // CS Pin

const byte WRITE_WIPER = 0x00;

int Pot = A0;   // Assign Focus pot to A0
int PotValue = 0;  // Assign Focus variable

void setup()
{
  SPI.begin();       // Start SPI
  
  pinMode(CS, OUTPUT);       // CS Focus pot
  
  //Serial.begin(9600);         // Only for debug purposes

}

void loop()
{
  
  PotValue = analogRead(Pot);   // Read Focus Pot
  
  if (PotValue > 1023) {              // Focus Output limiter
           PotValue = 1023;
          } 
  
  // MAX5481 chip control
 digitalWrite(CS, LOW);                  //set the SS pin low to select the Focus chip
 SPI.transfer(WRITE_WIPER);               //Byte 1: the command byte
 SPI.transfer(highByte(PotValue << 6)); //Byte 2: the upper 8 bits of the 10-bit command: (D9.D8.D7.D6.D5.D4.D3.D2)
 SPI.transfer(lowByte(PotValue << 6));  //Byte 3: the lower 2 bits of the 10-bit command, with 6 zeros to the right of them: (D1.D0.x.x.x.x.x.x)
 digitalWrite(CS, HIGH);                 //set the SS pin high to deselect the focus chip
  
 //Serial.println(PotValue);       // Print Focus output value to serial
  delay(20);
  
}