How to start programming a script on Arduino?
Starting a new project in Arduino may seem daunting, but with a step-by-step approach it becomes much simpler. When starting a project in Arduino IDE, you will always see the basic setup()
and loop()
functions. However, it is key to mark and document your code from the beginning, pointing out relevant details such as dates or an identification system, which help to keep control and reference the project. Here, I'll explain how to successfully start your code.
What initial definitions are necessary?
For any project, it is crucial to define the pins where the sensors will be connected and the type of device you are using. This is done in the definitions section:
How to work with setup
configuration?
The setup
block is executed once at the beginning of the code, so we initialize all necessary configurations in it.
-
Initialization of the DHT sensor:
DHT dht(DHTPIN, DHTTYPE);
- Initializes also the serial connection to be able to monitor and print debug messages:
Serial.begin(9600);dht.begin();
-
Wi-Fi connection:
- Creates a Wi-Fi connection using the supplied credentials and verifies that it is successful before continuing with further processing:
WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(".");}
Why is the loop
block essential?
The loop
function is where the infinite loop of execution takes place, i.e. all persistent work or repetitive actions.
-
Reading sensors in the loop:
- Use the
loop
to read and process data from your sensors:
float h = dht.readHumidity();float t = dht.readTemperature();
- Add any logic you need to process and handle these values, such as validations or conversions.
-
Data update and communication:
- Here you set up any update functions or control logic that runs cyclically, such as sending data via API:
if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!");} else { Serial.print("Humidity: "); Serial.print(h); Serial.print("% Temperature: "); Serial.print(t); Serial.println(" *C ");}
Finally, be sure to constantly check your code for syntax errors, with semicolons and braces being the most frequent problem areas in Arduino programming. Never forget to save and verify your code before uploading it, as this will help prevent potential errors during upload to the device. With these solid foundations, you'll be ready to take the first steps in an IoT project with Arduino.
Want to see more contributions, questions and answers from the community?