Created
July 23, 2017 15:49
-
-
Save FrankBuss/387382d840e14c295ce4148931bc42d9 to your computer and use it in GitHub Desktop.
quantization test for synthesizer CV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Quantize test: | |
* Arduino Nano pins for the MCP4822 DAC: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). | |
* potentiometer input: A0 | |
*/ | |
#include "SPI.h" | |
// pin numbers | |
const int ledPin = 13; | |
const int csPin = 10; | |
char buf[256]; | |
// send a word to the DAC | |
void sendDacWord(uint16_t word) | |
{ | |
digitalWrite(csPin, LOW); | |
SPI.transfer(word >> 8); | |
SPI.transfer(word & 0xff); | |
digitalWrite(csPin, HIGH); | |
} | |
void setup() | |
{ | |
// init pins | |
pinMode(ledPin, OUTPUT); | |
pinMode(csPin, OUTPUT); | |
digitalWrite(csPin, HIGH); | |
// init SPI | |
SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0)); | |
SPI.begin(); // additional begin is required, otherwise the second call to SPI.transfer hangs | |
// use a 2.5V external analog reference | |
analogReference(EXTERNAL); | |
// for debugging | |
Serial.begin(115200); | |
} | |
// read an anlog input and return it as voltage, assuming an 2.5V external reference | |
float readVolt(uint8_t channel) | |
{ | |
uint16_t in = analogRead(channel); | |
return in / 1024.0f * 2.5f; | |
} | |
void loop() | |
{ | |
// read potentiometer | |
float volt = readVolt(0); | |
// 12 steps per volt for quantization | |
float steps = 12.0f; | |
float quantized = float(int(volt * steps)) / steps; | |
// convert to DAC value (internal 2.048 V reference, 12 bit) | |
uint16_t out = int(quantized / 2.048f * 4096.0f); | |
// limit and send to DAC | |
if (out > 4095) out = 4095; | |
sendDacWord(out & 0x0fff | (1 << 12) | (1 << 13)); | |
// debug output | |
delay(1); | |
// read back DAC output | |
float dac = readVolt(1); | |
sprintf(buf, "%i\t%i\t%i", int(volt * 1000.0f), int(quantized * 1000.0f), int(dac * 1000.0f)); | |
Serial.println(buf); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment