Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Python is a versatile programming language widely used in various fields, including web development, data analysis, artificial intelligence, and more. Its simplicity and readability make it an excellent choice for beginners and professionals alike. When it comes to electronics and microcontroller projects, Python can be used in conjunction with Arduino to create powerful and interactive systems.
In the context of Arduino, Python can be used to communicate with the Arduino board via serial communication. This allows for real-time data monitoring, control of actuators, and integration with other software systems. By leveraging Python's extensive libraries and Arduino's hardware capabilities, we can create sophisticated projects that are both functional and educational.
Project: In this article, we will create a project to monitor temperature and humidity using a DHT11 sensor connected to an Arduino board. The data will be sent to a computer via serial communication, where a Python script will read and display the data in real-time. The objectives of this project are:
Components List:
Examples:
Arduino Code:
#include <DHT.h>
#define DHTPIN 2 // Pin where the DHT11 is connected
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000); // Wait a few seconds between measurements
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the results to the serial monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
}
Python Code:
import serial
import time
# Set up the serial line
ser = serial.Serial('COM3', 9600) # Adjust 'COM3' to your port
time.sleep(2) # Wait for the serial connection to initialize
while True:
try:
line = ser.readline() # Read a line from the serial port
line = line.decode('utf-8') # Convert the byte string to a unicode string
print(line.strip()) # Print the line, stripping any extra whitespace
except KeyboardInterrupt:
print("Program interrupted by user")
break
ser.close() # Close the serial connection
Explanation: