From 6a9fe5814919d3b1fb89faa413dbd0923c698268 Mon Sep 17 00:00:00 2001 From: Vikram Rajput Date: Thu, 31 Oct 2024 10:58:00 +0530 Subject: [PATCH] Final code --- Lab_9.c | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Lab_9.c b/Lab_9.c index 3e83868..b677c98 100644 --- a/Lab_9.c +++ b/Lab_9.c @@ -1,6 +1,50 @@ #include -#include #include "tm4c123gh6pm.h" +#define I2C0_MSA_R (*((volatile uint32_t *)0x40020000)) +#define I2C0_MDR_R (*((volatile uint32_t *)0x40020008)) +#define I2C0_MCS_R (*((volatile uint32_t *)0x40020004)) +#define MCP4725_ADDR 0x60 // MCP4725 I2C Address +void I2C0_Init(void) { + SYSCTL_RCGCI2C_R |= 0x01; // Enable I2C0 module + SYSCTL_RCGCGPIO_R |= 0x02; // Enable GPIOB for I2C + while ((SYSCTL_PRGPIO_R & 0x02) == 0) {}; // Wait for port B to be ready + + GPIO_PORTB_AFSEL_R |= 0x0C; // Enable alternate function for PB2, PB3 + GPIO_PORTB_ODR_R |= 0x08; // Enable open-drain on PB3 (SDA) + GPIO_PORTB_DEN_R |= 0x0C; // Enable digital I/O on PB2, PB3 + GPIO_PORTB_PCTL_R = (GPIO_PORTB_PCTL_R & 0xFFFF00FF) + 0x00003300; // Configure PB2, PB3 for I2C + + I2C0_MCR_R = 0x10; // Master mode + I2C0_MTPR_R = 24; // Set SCL to ~100kHz +} + +void I2C0_Send(uint8_t slave_addr, uint16_t data) { + I2C0_MSA_R = (slave_addr << 1) & 0xFE; // Transmit to MCP4725 + I2C0_MDR_R = (data >> 8); // Send upper 8 bits + I2C0_MCS_R = 0x03; // Start and run + + while (I2C0_MCS_R & 0x01) {}; // Wait until done + I2C0_MDR_R = data & 0xFF; // Send lower 8 bits + I2C0_MCS_R = 0x05; // Stop and run + + while (I2C0_MCS_R & 0x01) {}; // Wait until done +} + +void DAC_Write(uint16_t value) { + uint16_t data = (value & 0x0FFF) << 4; // Left align 12-bit value + I2C0_Send(MCP4725_ADDR, data); +} + +int main(void) { + I2C0_Init(); + + uint16_t value = 0; + while (1) { + DAC_Write(value); + value = (value + 1) % 4096; // Increment and wrap around at 12-bit limit for sawtooth + for (volatile int delay = 0; delay < 5000; delay++); // Delay for waveform frequency + } +}