I am new to the Arduino world and I hope I can find a solution here. The code below functionally works ok. The problem I have is, at line 45 I've inserted an if statement to change dac_value. It is very slow while serial and all that is outside if works fast/fine... What would be a solution to make it fast? Tried if - else if and also while... result is the same. Hope someone can help. Thank you.
{
#include <Arduino.h>
#include <Wire.h>
// #include <LiquidCrystal_I2C.h>
#define MCP4725 0x61
#define MCP4725B 0x60
unsigned int val;
byte buffer[3];
byte buff[3];
int ClockPinV = PB1;
int ClockPinA = PA6;
const int currsensPin = PA3;
const int voltsensPin = PA2;
void setup()
{
Serial.begin(115200);
pinMode(currsensPin , INPUT_ANALOG);
pinMode(voltsensPin , INPUT_ANALOG);
pinMode(ClockPinV , INPUT);
pinMode(ClockPinA , INPUT);
Wire.begin();
}
int val0 = 1024;
int val1 = 4096;
volatile int dac_value = 0;
void loop()
{
analogReadResolution(12);
volatile int svolt = analogRead(ClockPinV);
volatile int scurr = analogRead(ClockPinA);
volatile int set_voltage = (3.3/4096)svolt;
volatile int set_curr = (3.3/4096)scurr;
volatile int securr = analogRead(currsensPin);
volatile int real_curr = (3.3/4096)securr;
volatile int sevolt= analogRead(voltsensPin);
volatile int real_output2 = (3.3/4096)sevolt;
if(real_curr < set_curr){
if(set_voltage > real_output2)
{
dac_value = dac_value + 1;
}
if(set_voltage < real_output2)
{
dac_value = dac_value - 1;
}
}
else if(real_curr > set_curr)
{
dac_value --;
}
dac_value = constrain(dac_value, 0, 2673);
buffer[0] = 0b01000000; //control byte
buffer[1] = dac_value >> 4; //MSB 11-4 shift right 4 places
buffer[2] = dac_value << 4; //LSB 3-0 shift left 4 places
Wire.beginTransmission(MCP4725); //address device
Wire.write(buffer[0]); //pointer
Wire.write(buffer[1]); //8 MSB
Wire.write(buffer[2]); //4 LSB
Wire.endTransmission();
// val1 = constrain(val1, 0, 2673);
buff[0] = 0b01000000; //control byte
buff[1] = svolt >> 4; //MSB 11-4 shift right 4 places
buff[2] = svolt << 4; //LSB 3-0 shift left 4 places
Wire.beginTransmission(MCP4725B); //address device
Wire.write(buff[0]); //pointer
Wire.write(buff[1]); //8 MSB
Wire.write(buff[2]); //4 LSB
Wire.endTransmission();
Serial.println("=============================");
Serial.println("=============================");
Serial.println("========= Volt Test =========");
Serial.println("test: " + String(set_voltage));
Serial.println(" " + String(real_output2));
Serial.println("======== Current Test =======");
Serial.println("test: " + String(set_curr));
Serial.println(" " + String(real_curr));
Serial.println("=============================");
Serial.println("=============================");
}
}