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:
- global variables
You need to merge those parts separately.
- 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
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
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
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
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.)