Skip to content

Instantly share code, notes, and snippets.

@mages
Last active May 24, 2022 01:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mages/2d29d7abaab95ecccfd8 to your computer and use it in GitHub Desktop.
Save mages/2d29d7abaab95ecccfd8 to your computer and use it in GitHub Desktop.
Reading temperature from Arduino
# Based on code by Paul McWhorter:
# http://www.toptechboy.com/tutorial/python-with-arduino-lesson-11-plotting-and-graphing-live-data-from-arduino-with-matplotlib/
import serial
import re
import csv
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *
# Set path to my Arduino device
portPath = "/dev/tty.usbmodemfa411"
baud = 9600
sample_time = 0.1
sim_time = 10
# Initializing Lists
# Data Collection
data_log = []
line_data = []
# Establishing Serial Connection
connection = serial.Serial(portPath,baud)
# Calculating the length of data to collect based on the
# sample time and simulation time (set by user)
max_length = sim_time/sample_time
plt.ion() #Tell matplotlib you want interactive mode to plot live data
# Create a function that makes our desired plot
def makeFig():
plt.ylim(15,35)
plt.title('Temperatur Sensor Data')
plt.grid(True)
plt.ylabel('Temperatur C')
plt.plot(data_log, 'ro-', label='Degrees C')
# Collecting the data from the serial port
while True:
line = connection.readline()
line_data = re.findall('\d*\.\d*',str(line))
line_data = filter(None,line_data)
line_data = [float(x) for x in line_data]
if len(line_data) > 0:
print(line_data[0])
if float(line_data[0]) > 0.0:
drawnow(makeFig)
plt.pause(.000001)
data_log.append(line_data)
if len(data_log) > max_length - 1:
break
# Storing data_log in data.csv
with open('data.csv','w', newline='') as csvfile:
for line in data_log:
csvwrite = csv.writer(csvfile)
csvwrite.writerow(line)
//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
//the resolution is 10 mV / degree centigrade with a
//500 mV offset to allow for negative temperatures
void setup()
{
Serial.begin(9600); //Start the serial connection with the computer
//to view the result open the serial monitor
}
void loop() // run over and over again
{
//getting the voltage reading from the temperature sensor
int reading = analogRead(sensorPin);
// converting that reading to voltage, for 3.3v arduino use 3.3
float voltage = reading * 5.0;
voltage /= 1024.0;
// now print out the temperature
float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset
//to degrees ((voltage - 500mV) times 100)
Serial.println(temperatureC); //Serial.println(" degrees C");
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment