Best Python code snippet using avocado_python
motor_main.py
Source:motor_main.py
...36kDt = 0.537kAlpha = 0.0138kBeta = 0.000139# gets the current time in the form of microseconds - need to revisit this40def get_us():41 now = datetime.datetime.now()42 return (now.minute*60000000)+(now.second*1000000)+(now.microsecond)43# returns the elapsed time by subtracting the timestamp provided by the current time 44def get_elapsed_us(timestamp):45 temp = get_us()46 return (temp - timestamp)47class MotorController(object):48 SO_FILE = os.path.dirname(os.path.realpath(__file__)) + "/ad5592_spi_read.so"49 C_FUNCTIONS = CDLL(SO_FILE)50 INITIAL_US = get_us()51 52 def __init__(self, pwm_pin, motor_pin, mode = GPIO.BOARD, freq = 25000, warnings = False):53 GPIO.setwarnings(warnings)54 GPIO.setmode(mode)55 GPIO.setup(motor_pin, GPIO.OUT)56 self.pwm_pin = pwm_pin57 self.motor_pin = motor_pin58 self.pi = pigpio.pi()59 60 ## Default values61 self.pwm_current = 062 self.pwm_target = 063 self.duration = ""64 self.position_hold_time = 065 self.position_counter = 066 self.data = []67 self.data_single_revolution = []68 self.last_position = 069 self.freq_count = [[],[]]70 self.kX1 = 0.071 self.kV1 = 0.072 self.x = []73 self.v = []74 self.r = []75 def initialize(self):76 print("***********************************")77 print("Initializing spi...")78 msg = ""79 self.pi.hardware_PWM(19, 0, 0)80 GPIO.output(self.motor_pin, 1)81 _self_check = self.C_FUNCTIONS.initialize_motor()82 83 if _self_check:84 ## TODO Raise exception here85 msg = "ERROR: Initialize Failed."86 return 0, msg87 if input("Would you like to view the registers? (y/n): ").lower() == 'y':88 self._read_registers()89 if(input("\nAre Registers correct? (y/n): ").lower() != 'y'):90 msg = "Registers Not Selected to be Correct."91 return 0, msg92 if not self.C_FUNCTIONS.initialize_adc():93 print("ADC Initialized Successfuly")94 else:95 msg = "ERROR: Initialize Failed."96 return 0, msg97 return 1, "Everything Looks Good."98 def pwm_settings(self, duration, pwm_target):99 if duration == "i":100 duration = np.inf101 else:102 try:103 duration = int(duration)104 except ValueError:105 print("invalid duration type")106 return -1107 self.duration = duration108 self.pwm_target = int(pwm_target)109 return 0110 111 def analog_in_initial_send(self):112 self.C_FUNCTIONS.getAnalogInAll_InitialSend()113 # Increases PWM control duty cycle by 1%114 # Gets called by run_main until preferred duty cycle is reached115 def pwm_control(self):116 if(self.pwm_current < self.pwm_target):117 self.pwm_current = self.pwm_current + 1118 print("PWM: {}".format(self.pwm_current))119 self.pi.hardware_PWM(19, 25000, pwm_current * 10000)120 def get_analog_data(self):121 return self.C_FUNCTIONS.getAnalogInAll_Receive()122 123 def analog_terminate(self):124 self.C_FUNCTIONS.getAnalogInAll_Terminate()125 def health_check(self, data):126 code = [0,0,0]127 for i in range(1,4): # Turning Hall sensor channel data into a 3-digit position code128 if(data[i] > 1650): # Set a threshold of 1650mV for the hall pulse129 code[i-1] = 1130 else:131 code[i-1] = 0132 position = self._find_positions(code) # Convert code into a position (1-6)133 if(self.last_position != position): # Check if position is different from the last recorded position134 if(self.last_position != 0):135 freq = self._get_rpm(self.position_hold_time)136 self.running_filter(freq)137 reluctance = self._motor_reluctance(self.x[-1])138 self.position_counter += 1 139 if(self.position_counter == 6):140 rms_val = self._revolution_rms()141 self.position_counter = 0142 else:143 rms_val = 0144 print("Elapsed: {}, ".format(get_elapsed_us(self.INITIAL_US)) + "Position: {}, ".format(position) + "Frequency: {} ".format(round(freq, 2)) + "Filtered freq: {} ".format(x[-1]) +"PWM: {} ".format(pwm_current) + "Freq/PWM = {} ".format(reluctance) + "RMS Current: {}".format(rms_val))145 else:146 print("Incorred position recorded")147 return 0148 self.position_hold_time = get_us()149 self.last_position = position150 else:151 if((get_us() - self.position_hold_time) > 500000):152 print("****WARNING: STALL DETECTED****") 153 return 0154 return 1155 def running_filter(self, data):156 x_k = self.kX1 + kDt * self.kV1157 r_k = data - x_k158 x_k = x_k + kAlpha * r_k159 v_k = self.kV1 + (kBeta/kDt) * r_k160 self.kX1 = x_k161 self.kV1 = v_k162 self.x.append(x_k)163 self.v.append(v_k)164 self.r.append(r_k) 165 def rampdown(self):166 print("Starting rampdown...")167 for duty in range(self.pwm_current, -1, -1):168 self.pi_pwm.ChangeDutyCycle(duty)169 print("PWM: {}".format(duty))170 time.sleep(0.5)171 GPIO.output(self.motor_pin, 0)172 # graph_data()173 return 0174 def shutdown(self):175 # This occurs when there is a danger event like a stall or overcurrent176 # In this case, we want to shut off everything immediately to prevent further damage177 print("Starting Shutdown")178 self.pi.hardware_PWM(19, 0, 0)179 GPIO.output(self.motor_pin, 0)180 # graph_data()181 return 0182 def _read_registers(self):183 # Reads all registers on DRV8343 and prints them184 for i in range(19):185 reg_data = self.C_FUNCTIONS.motor_register_read(i)186 print('Register {}:'.format(i) + ' {}'.format(hex(reg_data)));187 print('\n')188 def _find_positions(self, code):189 # Converts the hall sensor pulse data into a position (1-6)190 # If the hall sensor pulses do not align with one of these positions, a zero is returned at which there will a flag raised191 if code == [1, 0, 1]:192 return 1193 elif code == [0, 0, 1]:194 return 2195 elif code == [0, 1, 1]:196 return 3197 elif code == [0, 1, 0]:198 return 4199 elif code == [1, 1, 0]:200 return 5201 elif code == [1, 0, 0]:202 return 6203 else:204 return 0205 206 def _get_rpm(self, pos_hold_time):207 freq = (1000000/((get_us() - pos_hold_time)*6))208 self.freq_count[0].append(get_elapsed_us(self.INITIAL_US))209 self.freq_count[1].append(freq)210 return freq211 def _motor_reluctance(self, freq):212 return freq/self.pwm_current213 def _revolution_rms(self):214 #TODO: Implement Function here215 return 0216# Processes the raw ADC data by multiplying by factor of 4096/5000 = 0.819217# Also extracts the index from data frame218# Returns both of these219def data_process(data):220 adc_reading = int((data & 0x0FFF) / 0.819)221 index = ((data >> 12) & 0x7)222 return adc_reading, index223# Graphs the current data. This is currently screwed up224def graph_data():225 #filter_data(freq_count[1])226 axs[0].plot(freq_count[0], x)227 axs[1].plot(data[0], data[4])228 axs[2].plot(data[0], data[5])229 axs[3].plot(data[0], data[6])230 plt.show()231# This is the main script which commands the pwm, adc data, and 232# The while loop will keep running until time elapses, a keyboard interrupt, or the motor stalls233def run_main():234 PWM_PIN = 19235 MOTOR_EN_PIN = 15236 237 MC = MotorController(PWM_PIN, MOTOR_EN_PIN)238 resp, msg = MC.initialize()239 print("***********************************")240 if not resp:241 print(msg)242 return -1243 244 resp = MC.pwm_settings(245 input("Enter sample duration (type 'i' for inifinite): "),246 input("Enter target duty cycle % (0-100):"))247 if not resp:248 print("PWM Settings incorrect. Exiting")249 return -1250 print("***********************************")251 temp_data = np.uint32([0,0,0,0,0,0,0,0,0])252 adc_reading = 0x0253 index = 0x0254 pwm_counter = 0255 MC.analog_in_initial_send() # Sends initial command to ADC to start recording all channels repeatedly256 position_hold_time = get_us() # Gets initial timestamp for position time tracking257 while(1):258 if((pwm_counter % 1000) == 0):259 MC.pwm_control() # Adjusts PWM for ramp-up260 pwm_counter = pwm_counter + 1 # Counter allows for a gradual ramp-up261 for i in range(0, ACTIVE_CHANNELS):262 data_16bit = MC.get_analog_data() 263 adc_reading, index = data_process(data_16bit)264 temp_data[index+1] = adc_reading265 data[index+1].append(temp_data[index+1])266 temp_data[0] = get_elapsed_us(MC.INITIAL_US)267 data[0].append(temp_data[0])268 #print('Time Elapsed: {}'.format(temp_data[0]))269 writer = csv.writer(file)270 writer.writerow(temp_data)...
stat.py
Source:stat.py
1from glob import glob2def get_us(line):3 value = line.strip().split(" ")[-1]4 if value[-2:] != "μs":5 raise Exception("cannot parse")6 return int(value[:-2])7benched = ["Homomorphic commitment took",8 "Spend proof took",9 "Output proof took",10 "Commitment checks took",11 "Spend proof verify took",12 "Output proof verify took",13 "Merging signature and tx took",14 "Consistency check took",15 "Randomness aggregation and transaction assembly took"]16def parse_test(file):17 data = {}18 with open(file) as fd:19 for line in fd:20 for parse in benched:21 if parse in line:22 if parse not in data:23 data[parse] = []24 data[parse].append(get_us(line))25 return data26data = {}27for f in glob("data/run*"):28 d = parse_test(f)29 for k,v in d.items():30 if k not in data:31 data[k] = []32 data[k]+=v33med = {}34for k,v in data.items():35 median = sorted(v)[len(v)//2]36 med[k] = (median/1000, (median-min(v))/1000, (max(v)-median)/1000)37 print(k.ljust(55),f"{med[k][0]:8.3f} -{med[k][1]:8.3f} +{med[k][2]:8.3f} ms")38# pgfplots output...
raspi_serial.py
Source:raspi_serial.py
1import serial2import string3import time4try:5 ser = serial.Serial('/dev/ttyACM1', 9600, timeout=1) # open serial port6except:7 ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) # open serial port8ser.reset_input_buffer() # clear the buffers9# All Helper Functions!10def writeArduino(command):11 ser.write(command.encode())12 13def readArduino():14 return ser.readline().decode('utf-8').strip()15def get_US(sensor):16 command = "get_US," + sensor + "\n"17 ser.write(command.encode())18 return readArduino()19def buzz():20 command = "buzz\n"21 ser.write(command.encode())22 time.sleep(0.3)23while True:24 distance = float(get_US("FRONT_LEFT"))25 print(distance)26 if (distance > 10):27 buzz();28 if (ser.in_waiting > 0):29 print(readArduino())30 time.sleep(0.1)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!