I'm new to programming and also arduino. Currently I want to control a DAC using arduino uno's SPI. I think I have trouble writing the code, and I did some research but didn't find any simple code for SPI. Could anyone help me check my code? Thanks in advance!
#include <SPI.h>
int CS = 10; //pin10 chip select
int Data = 11; //pin11 MOSI serial data
int SCLK = 13; //pin13 clock
SPISettings mysetting(25000000, MSBFIRST, SPI_MODE0);
void setup() {
// put your setup code here, to run once:
pinMode(CS,OUTPUT);
pinMode(Data,OUTPUT);
pinMode(SCLK,OUTPUT);
SPI.begin();
}
byte First_byte = 0b11111111;
byte Second_byte = 0b11111100;
void loop() {
// put your main code here, to run repeatedly:
SPI.beginTransaction(mysetting);
digitalWrite(CS,LOW);
SPI.transfer(First_byte);
SPI.transfer(Second_byte);
digitalWrite(CS,HIGH);
}
// format needed is
// (MSB-x-x-x-x-x-x-x)-(x-x-x-x-x-LSB-0-0)
// so shift your 14 bit data 2 bits left before sending it out:
yourDataInt = yourDataInt <<2;
digitalWrite (csPin, LOW); // cs connected to D10
SPI.transfer (highByte (yourDataInt));
SPI.transfer (lowByte (yourDataInt));
digitalWrite (csPin, HIGH);