Practical Example
3. Putting Theory into Practice
Let's say you have a temperature sensor connected to your Arduino Uno, and you want to visualize the temperature data using Python. Here's how you might approach it: First, on the Arduino side, you'd read the temperature sensor value, convert it to degrees Celsius (or Fahrenheit, if you're feeling traditional!), and then format it as a string.
The Arduino code might look something like this (simplified for clarity):
arduinovoid setup() { Serial.begin(9600); // Initialize serial communication}void loop() { int sensorValue = analogRead(A0); // Read the sensor value float temperature = sensorValue * 0.488; // Convert to Celsius (example) String dataString = String(temperature); Serial.println(dataString); // Send the data over serial delay(1000); // Wait 1 second}
Then, on the Python side, you'd use PySerial to connect to the Arduino's serial port and read the incoming data. You'd then parse the string to extract the temperature value and use a plotting library like Matplotlib to create a graph of the temperature over time. The Python code could look something like this (again, simplified):
pythonimport serialimport matplotlib.pyplot as pltimport timeser = serial.Serial('COM3', 9600) # Replace 'COM3' with your Arduino's portplt.ion() # Enable interactive plottingtemperatures = []times = []try: while True: data = ser.readline().decode('utf-8').rstrip() # Read data from serial if data: try: temperature = float(data) temperatures.append(temperature) times.append(time.time()) plt.clf() # Clear the plot plt.plot(times, temperatures) plt.xlabel('Time') plt.ylabel('Temperature (C)') plt.title('Temperature Sensor Data') plt.pause(0.1) # Pause briefly except ValueError: print("Invalid data received:", data)except KeyboardInterrupt: print("Plotting stopped") ser.close()
This example demonstrates how the Arduino acts as a data-gathering device, sending raw temperature readings to the Python script, which then processes and visualizes the data. It's a powerful combination for creating interactive and insightful projects.