Combining two codes-Need help

I have two codes. They work fine independently. I want to combine the two codes. As I have combined them, only code 1 responds, not the code 2. What I am missing, could not figure it out. Would appreciate any help!

Below is the combined code (I also marked Code 1 and Code 2)

// Basic demo for configuring the MCP4728 4-Channel 12-bit I2C DAC
#include <MCP4728.h>
#include <Wire.h>
#include <String.h>
#include <avr/wdt.h>
#include <Adafruit_MCP4728.h>

// Code1
int voltageLevel= 0;
String inString = "";    // string to hold input
Adafruit_MCP4728 mcp; // need to setup MCP4728

// Code2
char val1; // variable to receive data from the serial port
int ledpin = 9; // Arduino LED pin 9 
int pin = 10;  // Arduino LED pin 11

void setup() {
 
  Serial.begin(115200);
// Code 1
  if (!mcp.begin()) {
    Serial.println("MCP4728 Not Found");
   while (1) {
      delay(10);
    }
  }
   Serial.println("MCP4728 Found!");
  
  // Code 2
  pinMode(ledpin, OUTPUT); // pin 9 as OUTPUT,Relay channel input1
  digitalWrite(ledpin, HIGH);// Making input1 of 2 channel relay OFF initially
  pinMode(pin, OUTPUT); // pin 10 as OUTPUT, Relay channel input2
  digitalWrite(pin, HIGH);// Making input2 of 2 channel relay OFF initially
}
void loop() {
     // Code 1
  if (Serial.available()>=0) // read the oldest byte in the serial buffer:
  {
     int inChar = Serial.read();
        if (isDigit(inChar)){  // if incoming byte is in digit
            inString += (char)inChar; //convert the incoming byte to a char and add it to String
        }
        if (inChar == '\n'){//if you get a second digit, 
           
            voltageLevel = inString.toInt();// convert the digits received to integer
            mcp.setChannelValue(MCP4728_CHANNEL_A, voltageLevel);

                Serial.print("VoltageLevel:");
                Serial.print(voltageLevel);
                Serial.println(". ");
                inString = ""; // clear the string for new input:
       }
  } 
   
    // Code 2
     else if(Serial.available()>=0) // read the oldest byte in the serial buffer:
      {
         val1 = Serial.read(); // read it and store it in 'val1'
       
          if(val1 == 'A' ) // if 'A' is received
          {
          digitalWrite(ledpin, LOW); // turn ON the pin 9(input 1 of relay)
          Serial.println(val1);
          }                
        
          if(val1 == 'B')// if 'B is received 
          {
          digitalWrite(ledpin, HIGH); // turn it OFF
          Serial.println(val1);
          }    
          
      }       
}

read what Serial.available() is returning

serial/available/

and read about
else / else if

then analyse what it means to use a

else if(Serial.available()>=0)

statement

best regards Stefan

 // Code 1
  if (Serial.available() >= 0) // read the oldest byte in the serial buffer:
  {
  // Code 2
  else if (Serial.available() >= 0) // read the oldest byte in the serial buffer:
  {

The code for the else will never be executed because the if test will have returned true thus preventing execution of the else

Thanks StephenL38 and UKHeliBob! I changed else if to if. Code 2 now responds, but Code 1 sometimes does, sometime not. Is there a better way to combine both the codes?

Well, you can't really have two serial inputs simultaneously. Each code will then receive alternate characters.

again

when and what does Serial.available() return?

and more important what does Serial.read() do?
OK I looked up the reference.

@Arduino-Reference team: the description of the function read needs an addition
that as soon as the function was called the byte that was read is taken out of the buffer
and can't be read in a second time.

That's the reason why your code 1 does not always respond
best regards Stefan

Hi StephenL38, could you please explain, what you meant,

"the description of the function read needs an addition that as soon as the function was called the byte that was read is taken out of the buffer and can't be read in a second time."

I looked at Arduino Reference, here what Serial.read() says:

"The first byte of incoming serial data available (or -1 if no data is available). Data type: int."

Regards,

Stefan is saying that the function description doesn’t explicitly mention that after calling read() the byte read is removed from the incoming buffer.
TBH I would have thought that is fairly self evident. But maybe I’ve been coding too long.

@OP both of your sketches (note that “code” in computer science is never used in the plural) use serial.read().

You can’t have two calls to serial.read() and expect them to get the same character. At best they may get alternate characters, or more likely the second read() will get nothing at all if the first read() has already emptied the incoming buffer.

How are your sketches meant to know which of them is handling the serial input? Or in what way are you going to combine the syntax of the serial input that each sketch accepts individually into a combined “command language”?

Sketch one receives a string of characters and interprets it as a voltage level.
Sketch two accepts single characters and interprets ‘A’/‘B’ as requests to turn a LED ON/OFF.

Perhaps you might consider adding some “else if” clauses to this if...

 if (isDigit(inChar)){

...and checking for ‘A’ and ‘B’.

Good Morning! Thanks pcbbc for clarifying the thing! I am very novice in programming, trying to do a project in Arduino.

As you said, adding some else if. I am also thinking in the same line. For example,

if (Serial.available()>=0){

val1=Serial.read();

if val1 is an digit or integer, follow code 1

else if val1 is a character follow code2

But struggling how to do that.

Would appreciate any input

You've had input, the problem was explained. We're waiting for you to act on it. You just need to read once, store it and use it any number of times until you need another character. It's a little hard to understand why that would be difficult, as there is nothing really subtle about it.

The remarks in reply #7 remind me that you might have missed the step of defining what exactly your program is supposed to do. Nobody can program easily that way, not even an expert.

Sometimes extreme bafflement is just a sign that you are programming way above your level of understanding - there are really only two ways to get past that... you can slow down and learn by doing a lot more basic stuff until you get it, or you can ask other people to code for you.

Please make an attempt after re-reading the replies slowly and carefully, and post the result with any comments about how it behaves, if it doesn't work. This is not a forum where people usually write code for you. It seems like that is what you are fishing for. You posted correct pseudo code in your last reply - that is a good starting point!

Hi aarg, thanks for your feedback! What you stated in your first para of your response, I think I said the same thing, saving the Serial.read() in a variable and develop a logic based on type of data read. My struggle was that how to build that logic.

I make very clear, I am not fishing for any solution. Assuming something like that is inappropriate. I was looking for guidance, not solution. And that guidance was provided by UKHELIBob, why "else if", I should not use, which I used that in my first code posted. Also by pcbbc advised me, "Perhaps you might consider adding some "else if" clauses to this .. if (isDigit(inChar)){"

I don't think simply just stating, "Well, you can't really have two serial inputs simultaneously. Each code will then receive alternate characters." provide any real guidance except one's present felt.

Anyway, I redone the code based on guidance from pcbbc and UKHELIBob, It is working as intended.

/ Basic demo for configuring the MCP4728 4-Channel 12-bit I2C DAC
#include <MCP4728.h>
#include <Wire.h>
#include <String.h>
#include <avr/wdt.h>
#include <Adafruit_MCP4728.h>

// Code1
int voltageLevel= 0;
String inString = "";    // string to hold input
Adafruit_MCP4728 mcp; // need to setup MCP4728
// Code2
char inChar; // variable to receive data from the serial port
int ledpin = 9; // Arduino LED pin 9 
int pin = 10;  // Arduino LED pin 11

void setup() {
 
  Serial.begin(115200);
// Code 1
  if (!mcp.begin()) {
    Serial.println("MCP4728 Not Found");
   while (1) {
      delay(10);
    }
  }
   Serial.println("MCP4728 Found!");
  
  // Code 2
  pinMode(ledpin, OUTPUT); // pin 9 as OUTPUT,Relay channel input1
  digitalWrite(ledpin, HIGH);// Making input1 of 2 channel relay OFF initially
  pinMode(pin, OUTPUT); // pin 10 as OUTPUT, Relay channel input2
  digitalWrite(pin, HIGH);// Making input2 of 2 channel relay OFF initially
}
void loop() {
     
  if (Serial.available()>=0){   // read the oldest byte in the serial buffer:
    
    inChar = Serial.read();    
     //Code 1
      if(isDigit(inChar)) {
            // convert the incoming byte to a char and add it to the string:
            inString += (char)inChar; 
      }
      if (inChar == '\n') {
      voltageLevel = inString.toInt();
      mcp.setChannelValue(MCP4728_CHANNEL_A, voltageLevel);

                 Serial.print("VoltageLevel:");
                Serial.print(voltageLevel);
                Serial.println(". ");
                // clear the string for new input:
                inString = "";
      
       }      
                  
      else  if (!isDigit(inChar)){  // if incoming byte is in digit
            
           if(inChar == 'A' ) // if 'A' is received
          {
          digitalWrite(ledpin, LOW); // turn ON the pin 9(input 1 of relay)
          
          }                
        
          if(inChar == 'B')// if 'B is received 
          {
          digitalWrite(ledpin, HIGH); // turn it OFF
          
          }    
            
        }
  
    }

 }

Thanks to everyone! It's a great forum to learn! Happy Labor Day!

I don't think simply just stating, "Well, you can't really have two serial inputs simultaneously. Each code will then receive alternate characters." provide any real guidance except one's present felt.

Well, it clearly identified the problem. I don't see how you could cast that as unhelpful. It's true I didn't spell out any way you could solve it, but programming is usually done by the programmer. I don't feel that spoon feeding people solutions is usually helpful, and I felt that the solution followed extremely logically from knowledge of the problem (assuming you know how to program).

I don't care that you specifically excluded me from your thank you list, but I think it's pretty rude.