(Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)

This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?


This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.

There are 3 basic parts to the main.ino file of an Arduino sketch:

  1. The declarations:

    • #includes
    • #defines
    • global variables
  2. The setup() function

  3. The loop() function.

You need to merge those parts separately.

  1. You should merge the subsections of the declarations together (Put all the #includes together, all the #defines together, and all the global variables together. Remove any duplicate #includes.

If there are any duplicate #defines or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

  1. The same applies to the two setup()-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like Serial.begin(...)).

  2. Also the two loop()s are combined the same way, but if you make use of delay()s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of delay().

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.

(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)

  • See for example this answer with examples – sempaiscuba Apr 14 '19 at 14:56
  • To isolate some conflicts in the code, you can rename the bits setupLCD(), setupDTH(), loopLCD(), loopDTH() and call and manage the interactions in setup(){setupLCD();setupDTH();} and loop(){loopLCD(); loopDTH();} – Dave X Apr 25 '19 at 15:36
  • 1
    @DaveX, not a bad idea, although that won't help with conflicts in globals. – Duncan C Apr 26 '19 at 10:38
  • @DuncanC -- agree. As you say, conflicts will require analysis and have to be dealt with on a case-by-case basis. – Dave X Apr 26 '19 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.