@@ 0,0 1,72 @@
+/*
+ * Copyright (c) 2024 Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef AVR_COMMON_DEVICES_SPI_MCP49X2_H
+#define AVR_COMMON_DEVICES_SPI_MCP49X2_H
+
+#define MCP4922_DAC_BITS 12
+#define MCP4922_DAC_MIN_VAL 0
+#define MCP4922_DAC_MAX_VAL ((1 << MCP4922_DAC_BITS) - 1)
+
+#define MCP4912_DAC_BITS 10
+#define MCP4912_DAC_MIN_VAL 0
+#define MCP4912_DAC_MAX_VAL ((1 << MCP4912_DAC_BITS) - 1)
+
+#define MCP4902_DAC_BITS 8
+#define MCP4902_DAC_MIN_VAL 0
+#define MCP4902_DAC_MAX_VAL ((1 << MCP4902_DAC_BITS) - 1)
+
+#ifndef _ASM
+
+enum mcp49x2_dac {
+ MCP49X2_DAC_A = 0,
+ MCP49X2_DAC_B = 1,
+};
+
+/* generate the 2 control bytes for MCP4922 (12-bit DAC) */
+static inline void mcp4922_mk_write(uint8_t *out, enum mcp49x2_dac dac,
+ bool buffered, bool x2, bool shutdown,
+ uint16_t val)
+{
+ uint8_t bits;
+
+ bits = 0;
+ bits |= dac;
+ bits |= buffered ? 0x40 : 0x00;
+ bits |= x2 ? 0x00 : 0x20;
+ bits |= shutdown ? 0x00 : 0x10;
+
+ out[0] = bits | ((val >> 8) & 0x0f);
+ out[1] = val & 0xff;
+}
+
+/* generate the 2 control bytes for MCP4912 (10-bit DAC) */
+#define mcp4912_mk_write(out, dac, buffered, x2, shutdown, val) \
+ mcp4922_mk_write((out), (dac), (buffered), (x2), (shutdown), (val) << 2)
+
+/* generate the 2 control bytes for MCP4902 (8-bit DAC) */
+#define mcp4902_mk_write(out, dac, buffered, x2, shutdown, val) \
+ mcp4922_mk_write((out), (dac), (buffered), (x2), (shutdown), (val) << 4)
+
+#endif
+
+#endif