How to combine two Arduino sketches
I have two Arduino sketches for two sensors. How to combine two different Arduino sketches to one complete sketch?
Suppose that you have two Arduino code as below
Arduino sketch 1
Arduino sketch 2
How to combine two above sketches
In both sketches, use millis() instead of delay()
Make sure that two sketches do not conflict to each other in using Arduino pin. If conflicted, change the pin in a sketch
Make sure that variable name or user-defined functions in both sketches are not the same. If both sketches have the same variable name or user-defined function, rename the variable name or user-defined function to make it different
Merge two sketches. code will merge as below
※ NOTE THAT:
The combined code might not works. You may need to make more modification based on the combined code.
Buy Arduino
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.
The Best Arduino Starter Kit
See Also
※ OUR MESSAGES
We are AVAILABLE for HIRE. See how to hire us to build your project
If this tutorial is useful for you, please give us motivation to make more tutorials.
DISCLOSURE
ArduinoGetStarted.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com, Amazon.it, Amazon.fr, Amazon.co.uk, Amazon.ca, Amazon.de, Amazon.es, Amazon.nl, Amazon.pl and Amazon.se
Copyright © 2018 — 2024 ArduinoGetStarted.com. All rights reserved.
Terms and Conditions | Privacy Policy
Объединить несколько скетчей?


Чтобы соединить несколько проектов в один, нужно разобраться со всеми возможными конфликтами:
- Проекты построены на одной и той же плате/платформе?
- Да – отлично!
- Нет – нужно убедиться, что “общая” плата сможет работать с железками, которые есть в объединяемых проектах, а также сама обладает нужной периферией.
- Нет – отлично!
- Да, I2C – все железки подключаются на I2C общей платы. Убедитесь, что адреса устройств не совпадают (случается крайне редко)!
- Да, SPI – у шины SPI все пины “общие”, кроме CS (Chip Select), этот пин может быть любым цифровым. Подробнее можно почитать вот тут.
- Да, UART – беда, к UART может быть подключено только одно устройство. Можно повесить одну железку на аппаратный UART, а вторую на SoftwareSerial. Либо заморачиваться с мультиплексорами.
- Нет – отлично!
- Да – разобраться, какую функцию выполняет пин в каждом из проектов и подобрать замену, как в железе, так и в программе:
- Если это обычный цифровой вход-выход, можно заменить на любой другой
- Если это измерение аналогового сигнала – заменить на другой аналоговый пин
- Если это генерация ШИМ, подключить соответственно на другой ШИМ пин и подкорректировать программу
- Если это прерывание – быть внимательным
- Нет – ОТЛИЧНО!
- Да – ситуация требует хорошего опыта работы с Ардуино…
- Используется один и тот же таймер – нельзя одновременно использовать ШИМ на ногах первого таймера и управление сервоприводами при помощи библиотеки Servo.h
- Используется генерация звука при помощи tone() – нельзя использовать ШИМ на ногах второго таймера
- Используются прерывания по таймеру и генерация ШИМ на соответствующем таймере – сложная ситуация
- И т.д., ситуаций может быть бесконечно много…
Можно внести все правки в схемы и программы объединяемых проектов, чтобы они не конфликтовали. Далее приступаем к сборке общей программы:
- Подключаем все библиотеки. Некоторые библиотеки могут конфликтовать, например Servo и Timer1, как обсуждалось выше.
- Сравниваем имена глобальных переменных и дефайны в объединяемых программах: они не должны совпадать. Совпадающие меняем при помощи замены по коду (Правка/Найти) на другие. Далее копипастим все глобальные переменные и дефайны в общую программу
- Объединяем содержимое блока setup()
- Копипастим в общую программу все “пользовательские” функции
- Остаётся у нас только loop() , и это самая сложная задача
Раньше у нас было два (или больше) отдельно работающих проекта. Теперь наша задача как программиста – продумать и запрограммировать работу этих нескольких проектов в одном, и тут ситуаций уже бесконечное множество:
- Основной код (который в loop()) из разных проектов должен выполняться по очереди по таймеру
- Набор действий из разных проектов должен переключаться кнопкой или ещё как-то
- К одному проекту добавляется датчик из другого проекта – данные нужно обработать и запрограммировать их дальнейшее движение (вывод на дисплей, отправку и т.д.)
- Все “проекты” должны работать одновременно на одной Ардуине
- И так далее
В большинстве случаев нельзя просто так взять и объединить содержимое loop() из разных программ, я надеюсь все это понимают. Даже мигалку и пищалку таким образом объединить не получится, если изначально код был написан с задержками или замкнутыми циклами.
Полезные страницы
- Набор GyverKIT – большой стартовый набор Arduino моей разработки, продаётся в России
- Каталог ссылок на дешёвые Ардуины, датчики, модули и прочие железки с AliExpress у проверенных продавцов
- Подборка библиотек для Arduino, самых интересных и полезных, официальных и не очень
- Полная документация по языку Ардуино, все встроенные функции и макросы, все доступные типы данных
- Сборник полезных алгоритмов для написания скетчей: структура кода, таймеры, фильтры, парсинг данных
- Видео уроки по программированию Arduino с канала “Заметки Ардуинщика” – одни из самых подробных в рунете
- Поддержать автора за работу над уроками
- Обратная связь – сообщить об ошибке в уроке или предложить дополнение по тексту ([email protected])
How to combine two codes in arduino? [duplicate]
I didn’t ask if they both worked. I asked if you knew how they both worked. If you don’t know how they work then there is no way you will be able to combine them.
Sep 24, 2020 at 14:13
What exactly is your problem in combining them? With what terms aren’t you familiar? I will gladly answer your questions, but honestly I don’t want to write the code for you. There is no simple answer to your current questions (other than the one I linked), because it is a rather broad question unless we do all your work for you. As Majenko stated, the key in combining 2 sketches is to understand how they work. Then you can decide how the final program should work and write a new code with fitting snippets of the previous codes
Sep 24, 2020 at 14:40
And you should look into the BlinkWithoutDelay example, which comes with the Arduino IDE. It shows how you can use the millis() function to write non-blocking code without delay() calls. It is an important principle to learn and may be really helpful when combining your sketches
Sep 24, 2020 at 14:42
1 Answer 1
While I’d like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary. You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program’s loop. May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).
#include LiquidCrystal lcd(12,11,5,4,3,2); #define sensor A0 #define led 13 #define ledd 8 // d out from mq3 #define buz 9 #define motor 10 void setup1() < Serial.begin(9600); lcd.begin(16,2); lcd.print("ALCOHOL MONITORING"); lcd.setCursor(0,1); lcd.print(" VEHICLE SYSTEM "); delay(2000); pinMode(sensor, INPUT); pinMode(buz, OUTPUT); pinMode(led, OUTPUT); pinMode(ledd, OUTPUT); pinMode(motor, OUTPUT); lcd.clear(); >void loop1() < float adcValue=0; for(int i=0;i<10;i++) < float actualanalogReading = analogRead(sensor); adcValue = adcValue + actualanalogReading; Serial.println("In loop counter >"); // logging Serial.print(i); Serial.print(" input reading : "); Serial.print(actualanalogReading); Serial.print(" cumulative input reading : "); Serial.print(adcValue); delay(10); > float v= (adcValue/10) * (3.0/1024.0); float mgL= 0.67 * v; Serial.println(""); Serial.print("Post calculation v value >" ); Serial.print(v); Serial.print(" mg/L > "); Serial.print(mgL); Serial.println(""); Serial.print("BAC:"); Serial.print(mgL); Serial.print(" mg/L"); lcd.setCursor(0,0); lcd.print("BAC: "); lcd.print(mgL,4); lcd.print(" mg/L "); lcd.setCursor(0,1); if(mgL > 0.8) < lcd.print("Drunk ENGINE OFF "); Serial.println("Drunk ENGINE OFF "); digitalWrite(buz, HIGH); digitalWrite(led, HIGH); digitalWrite(ledd, LOW); digitalWrite(motor, LOW); >else < lcd.print("Normal ENGINE ON "); Serial.println(" Normal ENGINE ON "); digitalWrite(buz, LOW); digitalWrite(led, LOW); digitalWrite(ledd, HIGH); digitalWrite(motor, HIGH); >delay(100); > const int LED = A5; const int DO = 6; void setup() < setup1(); //Serial.begin(9600); pinMode(LED, OUTPUT); pinMode(DO, INPUT); >void loop() < int alarm = 0; float sensor_volt; float RS_gas; float ratio; //-Replace the name "R0" with the value of R0 in the demo of First Test -/ float R0 = 0.10; int sensorValue = analogRead(A1); sensor_volt = ((float)sensorValue / 1024) * 5.0; RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module ratio = RS_gas / R0; // ratio = RS/R0 //------------------------------------------------------------/ Serial.print("sensor_volt = "); Serial.println(sensor_volt); Serial.print("RS_ratio = "); Serial.println(RS_gas); Serial.print("Rs/R0 = "); Serial.println(ratio); Serial.print("\n\n"); alarm = digitalRead(DO); if (alarm == 1) digitalWrite(LED, LOW); else if (alarm == 0) digitalWrite(LED, HIGH); for(int dd = 0; ddHow do you combine 2 different sketches together
(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?
asked Apr 14, 2019 at 14:50
5,672 3 3 gold badges 17 17 silver badges 29 29 bronze badges
Possible duplicate of How to combine two different sensor sketches to one complete sketch?
Apr 25, 2019 at 14:251 Answer 1
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:
- The declarations:
- #includes
- #defines
- global variables
- The setup() function
- The loop() function.
You need to merge those parts separately.
- You should merge the subsections of the declarations together (Put all the #includes together, all the #define s together, and all the global variables together. Remove any duplicate #include s.
If there are any duplicate #define s 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 Serial.begin(. ) ).
- 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.)