<commit_before>#!/usr/bin/env python
import serial
import time
import pandas as pd
import pyqtgraph as pg
import numpy as np
import sys

class Arduino(object):

    def __init__(self, baud=9600, port=None, timeout=2, sr=None):
        # Check to make sure output data file is closed        
        try:
            myfile = open("OutputFiles/data.xls",'w')
            myfile.close()
        except:
            print('**********************************************************')
            print('***Could not access OutputFiles/data.xls.****')
            print('***Please close data.xls file before starting new run.****')
            print('**********************************************************')
            sys.exit()
        # Connect to serial port
        port = self.findPort()
        print('Opening connection')
        self.s = serial.Serial(port=port, baudrate=115200, timeout=2)
        time.sleep(3)
#        self.s.port = port
#        try:
#            self.s.open()
#        except SerialException:
#            self.s.close()
#            self.s.open()
        self.sr = self.s
        # First transistor and sensor
        self.tempInPin = 0
        self.voltOutPin = 3
        # Second transistor and sensor (for MIMO)
        self.tempInPin2 = 2
        self.voltOutPin2 = 5
        # LED 
        self.ledPin = 9
        print('Arduino connected on port '+port)
        print('Current configuration is:')
        print('Read temperature 1 on analog pin '+ str(self.tempInPin))
        print('Write voltage 1 on digital pin '+ str(self.voltOutPin))
        print('Read temperature 2 on analog pin '+ str(self.tempInPin2))
        print('Write voltage 2 on digital pin '+ str(self.voltOutPin2))
        
    def findPort(self):
        found = False
        for port in list(serial.tools.list_ports.comports()):
            # Arduino Uno
            if port[2].startswith('USB VID:PID=16D0:0613'):
                port = port[0]
                found = True
            # HDuino
            if port[2].startswith('USB VID:PID=1A86:7523'):
                port = port[0]
                found = True                
        if (not found):
            print('Arduino COM port not found')
            print('Please ensure that the USB cable is connected')
            print('--- Printing Serial Ports ---')            
            for port in list(serial.tools.list_ports.comports()):
                print(port[0] + ' ' + port[1] + ' ' + port[2])
            port = 'COM3'
        return port
        
    def initPlots(self):
        # Initialize data array
        # time, v_out 1, temp 1, temp setpoint 1
        self.data = np.array([[0, 0, self.readTemp(), 0]])        
        
        # Create figure window
        self.win = pg.GraphicsWindow()
        self.win.resize(1000,600)
        self.win.setWindowTitle('Arduino Temperature Control Lab')
        pg.setConfigOptions(antialias=True)
        
        # Create temperature plot
        self.plt = self.win.addPlot(title="Temperature vs Time",row=1,col=1)
        self.plt.setRange(yRange=[280,380])
        yaxis = self.plt.getAxis('left')
        labelStyle = {'color': '#FFF', 'font-size': '14pt'}
        yaxis.setLabel('Temperature','K', **labelStyle)
        yaxis.setGrid(150)
        
        # Create voltage plot
        self.plt2 = self.win.addPlot(row=2,col=1)
        self.plt2.setRange(yRange=[0,255])
        xaxis = self.plt2.getAxis('bottom')
        xaxis.setLabel('Time','s', **labelStyle)
        yaxis2 = self.plt2.getAxis('left')
        yaxis2.setLabel('Voltage','mV', **labelStyle)
        yaxis2.setGrid(100)
        return True
        
    def addData(self,newData):
        self.data = np.r_[self.data,newData]
        return True
    
    def updatePlots(self):
        self.plt.plot(self.data[-300:,0],self.data[-300:,2], pen=pg.mkPen('r',width=3),clear=True)
        self.plt2.plot(self.data[-300:,0],self.data[-300:,1], pen=pg.mkPen('b',width=3),clear=True)
        self.plt.addLine(y=self.data[-1,3])
        pg.QtGui.QApplication.processEvents()
        return True
        
    def saveData(self):
        '''
        Outputs collected data to excel file in OutputFiles folder
        '''
        df = pd.DataFrame(self.data)
        C = ['Time (s)', 'Voltage Out (mV)', 'Temperature (K)', 'T Setpoint (K)']
        df.to_excel("OutputFiles/data.xls", header=C, index=False)<commit_msg>Create OutputFiles folder if needed and add timestamp to data file.  Now we don't have to check if it is open at the start.<commit_after>#!/usr/bin/env python
import serial
import time
import pandas as pd
import pyqtgraph as pg
import numpy as np
import sys
import os

class Arduino(object):

    def __init__(self, baud=9600, port=None, timeout=2, sr=None):
        # Connect to serial port
        port = self.findPort()
        print('Opening connection')
        self.s = serial.Serial(port=port, baudrate=115200, timeout=2)
        time.sleep(3)
#        self.s.port = port
#        try:
#            self.s.open()
#        except SerialException:
#            self.s.close()
#            self.s.open()
        self.sr = self.s
        # First transistor and sensor
        self.tempInPin = 0
        self.voltOutPin = 3
        # Second transistor and sensor (for MIMO)
        self.tempInPin2 = 2
        self.voltOutPin2 = 5
        # LED 
        self.ledPin = 9
        print('Arduino connected on port '+port)
        print('Current configuration is:')
        print('Read temperature 1 on analog pin '+ str(self.tempInPin))
        print('Write voltage 1 on digital pin '+ str(self.voltOutPin))
        print('Read temperature 2 on analog pin '+ str(self.tempInPin2))
        print('Write voltage 2 on digital pin '+ str(self.voltOutPin2))
        
    def findPort(self):
        found = False
        for port in list(serial.tools.list_ports.comports()):
            # Arduino Uno
            if port[2].startswith('USB VID:PID=16D0:0613'):
                port = port[0]
                found = True
            # HDuino
            if port[2].startswith('USB VID:PID=1A86:7523'):
                port = port[0]
                found = True                
        if (not found):
            print('Arduino COM port not found')
            print('Please ensure that the USB cable is connected')
            print('--- Printing Serial Ports ---')            
            for port in list(serial.tools.list_ports.comports()):
                print(port[0] + ' ' + port[1] + ' ' + port[2])
            port = 'COM3'
        return port
        
    def initPlots(self):
        # Initialize data array
        # time, v_out 1, temp 1, temp setpoint 1
        self.data = np.array([[0, 0, self.readTemp(), 0]])        
        
        # Create figure window
        self.win = pg.GraphicsWindow()
        self.win.resize(1000,600)
        self.win.setWindowTitle('Arduino Temperature Control Lab')
        pg.setConfigOptions(antialias=True)
        
        # Create temperature plot
        self.plt = self.win.addPlot(title="Temperature vs Time",row=1,col=1)
        self.plt.setRange(yRange=[280,380])
        yaxis = self.plt.getAxis('left')
        labelStyle = {'color': '#FFF', 'font-size': '14pt'}
        yaxis.setLabel('Temperature','K', **labelStyle)
        yaxis.setGrid(150)
        
        # Create voltage plot
        self.plt2 = self.win.addPlot(row=2,col=1)
        self.plt2.setRange(yRange=[0,255])
        xaxis = self.plt2.getAxis('bottom')
        xaxis.setLabel('Time','s', **labelStyle)
        yaxis2 = self.plt2.getAxis('left')
        yaxis2.setLabel('Voltage','mV', **labelStyle)
        yaxis2.setGrid(100)
        return True
        
    def addData(self,newData):
        self.data = np.r_[self.data,newData]
        return True
    
    def updatePlots(self):
        self.plt.plot(self.data[-300:,0],self.data[-300:,2], pen=pg.mkPen('r',width=3),clear=True)
        self.plt2.plot(self.data[-300:,0],self.data[-300:,1], pen=pg.mkPen('b',width=3),clear=True)
        self.plt.addLine(y=self.data[-1,3])
        pg.QtGui.QApplication.processEvents()
        return True
        
    def saveData(self):
        '''
        Outputs collected data to excel file in OutputFiles folder
        '''
        # Create OutputFiles directory if needed
        if not os.path.exists('./OutputFiles'):
            os.makedirs('./OutputFiles') 
        # Save data to excel file
        df = pd.DataFrame(self.data)
        C = ['Time (s)', 'Voltage Out (mV)', 'Temperature (K)', 'T Setpoint (K)']
        t = time.localtime()
        timestamp = time.strftime('%b-%d-%Y_%H%M', t)  # Add timestamp to file
        df.to_excel("OutputFiles/data-"+timestamp+".xls", header=C, index=False)
{'fraction_non_alphanumeric': 0.14161419576416714, 'fraction_numerical': 0.025414997137950774, 'mean_word_length': 2.0556138509968522, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3580963', 'n_tokens_mistral': 2827, 'n_tokens_neox': 2629, 'n_words': 618}