Back to the blog

Temperature Sensor Simulation with Python

Simulate in real time the reading from a temperature sensor and plot it as data arrives — the underlying pattern for any SCADA acquisition dashboard, IoT system, or DIY data logger.

The code generates random readings between \(20\,°C\) and \(40\,°C\) every second and updates the graph with matplotlib.animation.FuncAnimation. The same skeleton works for consuming real data from an Arduino/Raspberry via serial port — just replace random.uniform with a call to serial.readline().

import random
from itertools import count
import matplotlib.animation as animation
import matplotlib.pyplot as plt

# 1. Creating the figure and axis
plt.style.use('seaborn')
fig, ax = plt.subplots()
x_values = []
y_values = []
index = count()

# 2. Generate a random temperature value between 20 and 40 degrees Celsius
def read_temperature():
    temperature = round(random.uniform(20.0, 40.0), 2)
    return temperature

# 3. Real-time data plotting function
def plot_sensor_data(i):
    temperature = read_temperature()
    x_values.append(next(index))
    y_values.append(temperature)
    ax.clear()
    ax.plot(x_values, y_values)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Temperature [°C]')
    ax.set_title('Temperature Sensor')

# 4. Running and saving the simulation
animation_temp_sensor = animation.FuncAnimation(fig, plot_sensor_data, interval = 1000)
animation_temp_sensor.save("animation_temperature_sensor.mp4", writer="ffmpeg")
plt.show()

Simulation rendered as GIF:

Temperature sensor simulation

Key points of the code:

  • itertools.count() is an infinite counter that returns \(0, 1, 2, \ldots\) each time next(index) is called. Ideal for the time axis when you don't know in advance how many samples will arrive.
  • ax.clear() + ax.plot(...) in each frame is the simplest way to redraw a growing series. For large volumes it's better to use line.set_data(...) with blit = True — much more efficient.
  • interval = 1000 triggers plot_sensor_data(i) every second. Use a smaller value to emulate high-frequency sensors (gyroscopes, encoders, etc.).

Adapting to real hardware:

import serial
ser = serial.Serial("COM3", 9600)  # or "/dev/ttyUSB0" on Linux/Mac

def read_temperature():
    line = ser.readline().decode().strip()
    return float(line)

With that change the same script plots in real time what your Arduino sends over the serial port.

Installation:

pip install matplotlib
Back to the blog