In arduino mega 2560 , I have total 16 bit inputs, 14 for data and 1 for direction and 1 for data validity. directionPin is 14, validityPin is 15, while from 22 to 35 is the data input in form on high or low (5v or gnd), similar to binary. These 14 bit should be bind to 9 or 10Volt reference.
I am facing some issues with getting the output.
I placed an external battery 9V , common the gnd with Mega ground, on +VE terminal connected a resistor (around 1K) , on the other end of resistor connected the pwm pin (9), and testing the output from second end of resistor to gnd.
is it the correct setting? I am not getting the output properly, while showing correctly on Serial Monitor
here is the code.
const int referenceVoltage = 10; // Reference voltage
const int directionPin = 14; // direction (15th bit)
const int validityPin = 15; // data validity (16th bit)
const int pwmPin = 9;
void setup() {
Serial.begin(9600);
pinMode(pwmPin, OUTPUT);
}
void loop() {
int data = 0;
for (int i = 22; i < 36; i++) {
int bit = digitalRead(i);
data |= bit << (i - 22);
}
int direction = digitalRead(directionPin);
int validity = digitalRead(validityPin);
if (validity == HIGH) {
float outputVoltage = (float)data / 16383.0 * referenceVoltage;
// Set PWM duty cycle based on the output voltage
int pwmValue = map(outputVoltage, 0, referenceVoltage, 0, 255);
analogWrite(pwmPin, pwmValue);
Serial.print("Received data: ");
Serial.print(data);
Serial.print("Received data (binary): ");
for (int i = 13; i >= 0; i--) {
Serial.print((data >> i) & 0x01);
}
Serial.print(", Direction: ");
Serial.print(direction == LOW ? "Forward" : "Reverse");
Serial.print(", Data Validity: ");
Serial.print(validity == HIGH ? "Valid" : "Invalid");
Serial.print(", Analog Output Voltage: ");
Serial.print(outputVoltage);
Serial.print("PWM Value:");
Serial.println(pwmValue);
} else {
analogWrite(pwmPin, 0);
Serial.println("Invalid data received.");
}
}
should we understand that you need to read in the 14 data bits (GND / 5V) from pins 22 to 35 and build a PWM signal cycling between GND and 9 or 10V output from pin 9?
pin 9 cannot be at anything other than GND or 5V - so you'll need to drive some sort of power circuit from that pin, a mosfet / transistor or may be just an optocoupler that is fast enough for your needs
Yes, if required, as it become input for a machine that will operates based on these bit, if more current required then it will be adjusted through transistor or optocouplers. but first basic requirements need to be achieved.
OK, now I see what you want to do.
Basically, you are designing a 16 bit DAC (Digital to Analog Converter) by using PWM to generate a 0 to 10V analog output.
You can do that but you will need a good opamp, a 12V supply, and a few resistors and capacitors.
I’ll see if I can find an opamp that will work.
OR
You can buy a DAC module and just use an opamp the increase the voltage to 10V
OR a 10V DAC module