Code:
#include <SPI.h>
// Define the MIDI channel and CC number you want to use for CV output
const int midiChannel = 1; // MIDI channel (1-16)
const int ccNumber = 20; // Control Change (CC) number (0-127)
// Define the CV output pin
const int cvOutputPin = 16; // Digital pin number (0-39) on Teensy 4.1
// Define MCP4822-related pins
const int chipSelectPin = 10; // Chip select (CS) pin
const int dataOutPin = 11; // SPI MOSI pin
const int clockPin = 13; // SPI clock pin
void setup() {
// Initialize the CV output pin
pinMode(cvOutputPin, OUTPUT);
// Initialize MCP4822-related pins
pinMode(chipSelectPin, OUTPUT);
// Initialize SPI communication
SPI.begin();
SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0)); // Adjust the SPI clock speed if needed
// Start USB MIDI communication
usbMIDI.begin();
// Set up MIDI CC callback function
usbMIDI.setHandleControlChange(OnControlChangeWrapper);
}
void loop() {
// Check for incoming USB MIDI messages
usbMIDI.read();
}
void OnControlChangeWrapper(byte channel, byte control, byte value) {
// Convert data types and call the actual OnControlChange function
OnControlChange(channel, control, value);
}
void OnControlChange(byte channel, byte control, byte value) {
// Check if the received MIDI message matches the specified CC number and channel
if (control == ccNumber && channel == midiChannel) {
// Map the CC value (0-127) to the desired CV range (e.g., 0-4095)
uint16_t cvValue = map(value, 0, 127, 0, 4095);
// Output the CV value to the MCP4822 chip
digitalWrite(chipSelectPin, LOW); // Enable MCP4822 communication
// Construct the 16-bit value to be sent to the MCP4822
uint16_t spiData = 0b0111000000000000 | (cvValue & 0b0000111111111111);
// Send the data to the MCP4822
SPI.transfer16(spiData);
digitalWrite(chipSelectPin, HIGH); // Disable MCP4822 communication
}
}
Hi, glad you are making some progress.
In future when you are posting code could you enclose it between CODE tags (can be entered by using the # on the reply form) it makes your code easier to read and help those who might be able to help you.