def exit(self): self.running = False self.printer.path_planner.force_exit() for name, stepper in self.printer.steppers.iteritems(): stepper.set_disabled() # Commit changes for the Steppers Stepper.commit()
def main(argv): frame = cv2.imread("/home/pi/Downloads/IMG_4644.JPG") frame = imutils.resize(frame, width=400) # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (9, 9), 0) # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) print "Brightest Value:",brightest_value # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out2, threshold2 = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY+cv2.THRESH_OTSU) out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY) thr = threshold.copy() print "out value:",out2 # Resize frame for ease # cv2.resize(thr, (300, 300)) # Find contours in thresholded frame edged = cv2.Canny(threshold, 50, 150) # First one is source image, second is contour retrieval mode, third is contour approximation method. And it outputs # the contours and hierarchy. Contours is a Python list of all the contours in the image. Each individual contour # is a Numpy array of (x,y) coordinates of boundary points of the object. lightcontours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Checking if the list of contours is greater than 0 and if any circles are detected if (len(lightcontours)): # Finding the maxmimum contour, this is assumed to be the light beam maxcontour = max(lightcontours, key=cv2.contourArea) # Avoiding random spots of brightness by making sure the contour is reasonably sized if cv2.contourArea(maxcontour): (x, final_y), radius = cv2.minEnclosingCircle(maxcontour) print "x value:",x,"y value:",final_y t=Stepper(x,final_y) s = Servo(final_y) s.servo_control() t.change_position() cv2.circle(frame, (int(x), int(final_y)), int(radius), (0, 255, 0), 4) cv2.rectangle(frame, (int(x) - 5, int(final_y) - 5), (int(x) + 5, int(final_y) + 5), (0, 128, 255), -1) # Display frames and exit cv2.imshow('frame', frame) cv2.waitKey(0) key = cv2.waitKey(1) cv2.destroyAllWindows()
def execute(self, g): self.printer.path_planner.wait_until_done() for i in range(g.num_tokens()): axis = g.token_letter(i) stepper = self.printer.steppers[axis] stepper.set_microstepping(int(g.token_value(i))) self.printer.path_planner.update_steps_pr_meter() Stepper.commit()
def execute(self, g): for i in range(g.num_tokens()): # Run through all tokens axis = g.token_letter(i) # Get the axis, X, Y, Z or E value = float(g.token_value(i)) if value > 0: self.printer.steppers[axis].set_steps_pr_mm(value) else: logging.error('Steps per milimeter must be grater than zero.') Stepper.commit()
def execute(self, g): self.printer.path_planner.wait_until_done() for i in range(g.num_tokens()): axis = g.token_letter(i) logging.debug("M350 on "+axis) stepper = self.printer.steppers[axis] stepper.set_microstepping(int(g.token_value(i))) Stepper.commit() logging.debug("acceleration tables recreated")
def execute(self, g): self.printer.path_planner.wait_until_done() for i in range(g.num_tokens()): axis = g.token_letter(i) logging.debug("M350 on " + axis) stepper = self.printer.steppers[axis] stepper.set_microstepping(int(g.token_value(i))) Stepper.commit() self.printer.path_planner.make_acceleration_tables() logging.debug("acceleration tables recreated")
def execute(self, g): self.printer.path_planner.wait_until_done() if g.num_tokens() == 0: # If no token is present, do this for all steppers g.set_tokens(["X", "Y", "Z", "E", "H"]) for i in range(g.num_tokens()): # Run through all tokens axis = g.token_letter(i) # Get the axis, X, Y, Z or E self.printer.steppers[axis].set_disabled() Stepper.commit()
def execute(self, g): self.printer.path_planner.wait_until_done() if g.num_tokens() == 0: g.set_tokens(["X", "Y", "Z", "E", "H"]) # If no token is present, do this for all # All steppers for i in range(g.num_tokens()): # Run through all tokens axis = g.token_letter(i) # Get the axis, X, Y, Z or E self.printer.steppers[axis].set_disabled() Stepper.commit()
def execute(self, g): self.printer.path_planner.wait_until_done() self.printer.steppers["E"].set_disabled() self.printer.steppers["H"].set_disabled() Stepper.commit() self.printer.plugins[__PLUGIN_NAME__].head_servo.set_angle(self.printer.plugins[__PLUGIN_NAME__].t1_angle, asynchronous=False) self.printer.path_planner.set_extruder(1) self.printer.current_tool = "H" self.printer.steppers["E"].set_enabled() self.printer.steppers["H"].set_enabled() Stepper.commit()
def execute(self, g): self.printer.path_planner.wait_until_done() self.printer.steppers["E"].set_disabled() self.printer.steppers["H"].set_disabled() Stepper.commit() self.printer.plugins[__PLUGIN_NAME__].head_servo.set_angle( self.printer.plugins[__PLUGIN_NAME__].t1_angle, asynchronous=False) self.printer.path_planner.set_extruder(1) self.printer.current_tool = "H" self.printer.steppers["E"].set_enabled() self.printer.steppers["H"].set_enabled() Stepper.commit()
def __init__(self): self.stepper = Stepper() self.stepper_position_steps = 0 self.servos = Servos() self.servo_channel_left = SERVO_CHANNEL_LEFT self.servo_channel_right = SERVO_CHANNEL_RIGHT self.servo_angles_left = [ LEFT_MIN_VERTICAL_ANGLE, LEFT_MAX_VERTICAL_ANGLE ] self.servo_angles_right = [ RIGHT_MIN_VERTICAL_ANGLE, RIGHT_MAX_VERTICAL_ANGLE ] # [hack:] fine adjust left servo self.servos.servo_kit.servo[SERVO_CHANNEL_LEFT]._duty_range = 5820
def __init__(self, osc_ip='0.0.0.0', osc_port=12000): """Create our stepper object and osc server object""" self.debug = True # listen for OSC messages on port 12000 (Wekinator default) self.stepper_count = 2 #4 # Pin order: [ENB|MS1|MS2|MS3|RST|SLP|STP|DIR] self.stepper_A = Stepper([4, 5, 6, 7, 0, 0, 3, 2], "Stepper A", self.stepper_time_interval_seconds) self.stepper_B = Stepper([10, 11, 12, 13, 0, 0, 9, 26], "Stepper B", self.stepper_time_interval_seconds) self.stepper_C = Stepper([16, 17, 18, 19, 0, 0, 15, 14], "Stepper C", self.stepper_time_interval_seconds) self.stepper_D = Stepper([22, 23, 24, 25, 0, 0, 21, 20], "Stepper D", self.stepper_time_interval_seconds) print "Created 4 steppers" self.OSCServer = OSC.OSCServer((osc_ip, osc_port)) self.OSCServer.addMsgHandler('/wek/outputs', self.wek_outputs_handler) self.OSCServer.addMsgHandler('/tenta_emg', self.tenta_emg_handler) print "Tentacle Control is listening for OSC message /wek/outputs, ip %s port %s" % ( osc_ip, osc_port)
def new_child(conn, params): stepper = Stepper(params) while 1: s = conn.recv() if s=='RUN': runres=stepper.run() conn.send(runres) elif s=='RESET': stepper.reset_params(params) elif s=="DESTROY": return 0 else: param, val = s.split() if param in ('steps_pin', 'dir_pin', 'steps2sync', 'steps', 'dir'): val = int(val) elif param in ('interval'): val = float(val) params[param]=val
class CameraMount: def __init__(self): self.stepper = Stepper() self.stepper_position_steps = 0 self.servos = Servos() self.servo_channel_left = SERVO_CHANNEL_LEFT self.servo_channel_right = SERVO_CHANNEL_RIGHT self.servo_angles_left = [ LEFT_MIN_VERTICAL_ANGLE, LEFT_MAX_VERTICAL_ANGLE ] self.servo_angles_right = [ RIGHT_MIN_VERTICAL_ANGLE, RIGHT_MAX_VERTICAL_ANGLE ] # [hack:] fine adjust left servo self.servos.servo_kit.servo[SERVO_CHANNEL_LEFT]._duty_range = 5820 def __del__(self): del self.stepper del self.servos def rotateHorizontal(self, angle): angle = min(MAX_HORIZONTAL_ANGLE, max(MIN_HORIZONTAL_ANGLE, angle)) steps_target = angle * STEPPER_STEPS_PER_ANGLE steps_diff = steps_target - self.stepper_position_steps self.stepper.step(int(abs(steps_diff)), steps_diff < 0) self.stepper_position_steps = steps_target def rotateVerticalLeft(self, angle): self.rotateVertical(self.servo_channel_left, angle, self.servo_angles_left) def rotateVerticalRight(self, angle): self.rotateVertical(self.servo_channel_right, angle, self.servo_angles_right) def rotateVertical(self, channel, angle, servo_angles): angle = min(MAX_VERTICAL_ANGLE, max(MIN_VERTICAL_ANGLE, angle)) ratio = (angle - MIN_VERTICAL_ANGLE) / (MAX_VERTICAL_ANGLE - MIN_VERTICAL_ANGLE) servo_angle = servo_angles[0] + ratio * (servo_angles[1] - servo_angles[0]) self.servos.rotate(channel, servo_angle)
def __init__(self, serial, first_id, num_steppers, is_mono=False): self.serial = serial self.numNotes = 0 self.numOldNotes = 0 self.oldNotesStack = [None] * NOTES_BUFFER_SZ self.oldVolumesStack = [None] * NOTES_BUFFER_SZ self.isMono = is_mono self.numSteppers = num_steppers self.steppers = [] for i in range(first_id, first_id + self.numSteppers): self.steppers.append(Stepper(i, serial))
def exit(self): logging.info("Redeem starting exit") self.running = False self.printer.path_planner.wait_until_done() self.printer.path_planner.force_exit() # Stops plugins self.printer.plugins.exit() for name, stepper in self.printer.steppers.iteritems(): stepper.set_disabled() Stepper.commit() for name, heater in self.printer.heaters.iteritems(): logging.debug("closing "+name) heater.disable() for name, comm in self.printer.comms.iteritems(): logging.debug("closing "+name) comm.close() self.printer.enable.set_disabled() logging.info("Redeem exited")
class StepperController(object): def __init__(self): self.faces = ['F', 'R', 'B', 'L', 'U', 'D'] self.slice_turns= { "M" : ("X'", ["R", "L'"]), "M'": ("X", ["R'", "L"]), "M2": ("X2", ["R2", "L2"]), "E" : ("Y'", ["U", "D'"]), "E'": ("Y", ["U'", "D"]), "E2": ("Y2", ["U2", "D2"]), "S" : ("Z", ["F'", "B"]), "S'": ("Z'", ["F", "B'"]) "S2": ("Z2", ["F2", "B2"]) } self.whole_cube_rotations = { "X" : [["F", "D", "B", "U"]], "X'": [["F", "U", "B", "D"]], "X2": [["F", "B"], ["U", "D"]], "Y" : [["F", "R", "B", "L"]], "Y'": [["F", "L", "B", "R"]], "Y2": [["F", "B"], ["L", "R"]], "Z" : [["U", "L", "D", "R"]] "Z'": [["U", "R", "D", "L"]], "Z2": [["U", "D"], ["R", "L"]], } self.steppers = { 'F' : Stepper([20, 21, 16], default_cw = False), #4 'R' : Stepper([ 7, 12, 8], default_cw = False), #6 'B' : Stepper([23, 24, 25], default_cw = False), #5 'L' : Stepper([19, 26, 13], default_cw = False), #3 'U' : Stepper([17, 27, 3], default_cw = False), #1 'D' : Stepper([ 5, 6, 22], default_cw = False) #2 }
def __init__(self): logging.info("Redeem initializing "+version) self.printer = Printer() # Parse the config self.printer.config = CascadingConfigParser(['/etc/redeem/default.cfg', '/etc/redeem/local.cfg']) # Get the revision from the Config file self.revision = self.printer.config.get('System', 'revision', "A4") logging.info("Replicape revision "+self.revision) # Init the end stops EndStop.callback = self.end_stop_hit EndStop.inputdev = self.printer.config.get("Endstops","inputdev"); if self.revision == "A4": self.printer.end_stops["X1"] = EndStop("GPIO3_21", 112, "X1", self.printer.config.getboolean("Endstops", "invert_X1")) self.printer.end_stops["X2"] = EndStop("GPIO0_30", 113, "X2", self.printer.config.getboolean("Endstops", "invert_X2")) self.printer.end_stops["Y1"] = EndStop("GPIO1_17", 114, "Y1", self.printer.config.getboolean("Endstops", "invert_Y1")) self.printer.end_stops["Y2"] = EndStop("GPIO1_19", 115, "Y2", self.printer.config.getboolean("Endstops", "invert_Y2")) self.printer.end_stops["Z1"] = EndStop("GPIO0_31", 116, "Z1", self.printer.config.getboolean("Endstops", "invert_Z1")) self.printer.end_stops["Z2"] = EndStop("GPIO0_4" , 117, "Z2", self.printer.config.getboolean("Endstops", "invert_Z2")) else: self.printer.end_stops["X1"] = EndStop("GPIO0_14", 112, "X1", self.printer.config.getboolean("Endstops", "invert_X1")) self.printer.end_stops["X2"] = EndStop("GPIO3_21", 113, "X2", self.printer.config.getboolean("Endstops", "invert_X2")) self.printer.end_stops["Y1"] = EndStop("GPIO2_2", 114, "Y1", self.printer.config.getboolean("Endstops", "invert_Y1")) self.printer.end_stops["Y2"] = EndStop("GPIO0_31", 115, "Y2", self.printer.config.getboolean("Endstops", "invert_Y2")) self.printer.end_stops["Z1"] = EndStop("GPIO0_30", 116, "Z1", self.printer.config.getboolean("Endstops", "invert_Z1")) self.printer.end_stops["Z2"] = EndStop("GPIO0_4", 117, "Z2", self.printer.config.getboolean("Endstops", "invert_Z2")) if self.revision == "A3": Stepper.revision = "A3" Stepper.ENABLED = 6 Stepper.SLEEP = 5 Stepper.RESET = 4 Stepper.DECAY = 0 # Init the 5 Stepper motors (step, dir, fault, DAC channel, name) self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X", self.printer.end_stops["X1"], 0,0) self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y", self.printer.end_stops["Y1"], 1,1) self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z", self.printer.end_stops["Z1"], 2,2) self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1", None,3,3) self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2", None,4,4) # Enable the steppers and set the current, steps pr mm and microstepping for name, stepper in self.printer.steppers.iteritems(): stepper.set_current_value(self.printer.config.getfloat('Steppers', 'current_'+name)) if self.printer.config.getboolean('Steppers', 'enabled_'+name): stepper.set_enabled() else: stepper.set_disabled() stepper.set_steps_pr_mm(self.printer.config.getfloat('Steppers', 'steps_pr_mm_'+name)) stepper.set_microstepping(self.printer.config.getint('Steppers', 'microstepping_'+name)) stepper.direction = self.printer.config.getint('Steppers', 'direction_'+name) stepper.set_decay(self.printer.config.getboolean("Steppers", "slow_decay_"+name)) # Commit changes for the Steppers Stepper.commit() # Find the path of the thermistors path = "/sys/bus/iio/devices/iio:device0/in_voltage" # init the 3 thermistors therm_ext1 = Thermistor(path+"4_raw", "MOSFET Ext 1", self.printer.config.get('Heaters', "ext1_temp_chart")) therm_hbp = Thermistor(path+"6_raw", "MOSFET HBP", self.printer.config.get('Heaters', "hbp_temp_chart")) therm_ext2 = Thermistor(path+"5_raw", "MOSFET Ext 2", self.printer.config.get('Heaters', "ext2_temp_chart")) path = self.printer.config.get('Cold-ends', 'path', 0) if os.path.exists(path): self.printer.cold_ends.append(ColdEnd(path, "Cold End 1")) logging.info("Found Cold end on "+path) else: logging.info("No cold end present in path: "+path) # Init the 3 heaters. Argument is channel number if self.revision == "A3": mosfet_ext1 = Mosfet(3) mosfet_ext2 = Mosfet(4) mosfet_hbp = Mosfet(5) else: mosfet_ext1 = Mosfet(5) mosfet_ext2 = Mosfet(3) mosfet_hbp = Mosfet(4) # Make extruder 1 self.printer.heaters['E'] = Extruder(self.printer.steppers["E"], therm_ext1, mosfet_ext1, "Ext1", self.printer.config.getboolean('Heaters', 'ext1_onoff_control')) self.printer.heaters['E'].set_p_value(self.printer.config.getfloat('Heaters', "ext1_pid_p")) self.printer.heaters['E'].set_d_value(self.printer.config.getfloat('Heaters', "ext1_pid_d")) self.printer.heaters['E'].set_i_value(self.printer.config.getfloat('Heaters', "ext1_pid_i")) self.printer.heaters['E'].ok_range = self.printer.config.getfloat('Heaters', "ext1_ok_range") # Make Heated Build platform self.printer.heaters['HBP'] = HBP( therm_hbp, mosfet_hbp, self.printer.config.getboolean('Heaters', 'hbp_onoff_control')) self.printer.heaters['HBP'].set_p_value(self.printer.config.getfloat('Heaters', "hbp_pid_p")) self.printer.heaters['HBP'].set_d_value(self.printer.config.getfloat('Heaters', "hbp_pid_i")) self.printer.heaters['HBP'].set_i_value(self.printer.config.getfloat('Heaters', "hbp_pid_d")) self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat('Heaters', "hbp_ok_range") # Make extruder 2. self.printer.heaters['H'] = Extruder(self.printer.steppers["H"], therm_ext2, mosfet_ext2, "Ext2", self.printer.config.getboolean('Heaters', 'ext2_onoff_control')) self.printer.heaters['H'].set_p_value(self.printer.config.getfloat('Heaters', "ext2_pid_p")) self.printer.heaters['H'].set_d_value(self.printer.config.getfloat('Heaters', "ext2_pid_i")) self.printer.heaters['H'].set_i_value(self.printer.config.getfloat('Heaters', "ext2_pid_d")) self.printer.heaters['H'].ok_range = self.printer.config.getfloat('Heaters', "ext2_ok_range") # Init the three fans. Argument is PWM channel number self.printer.fans=[] if self.revision == "A3": self.printer.fans.append(Fan(1)) self.printer.fans.append(Fan(2)) self.printer.fans.append(Fan(0)) else: self.printer.fans.append(Fan(8)) self.printer.fans.append(Fan(9)) self.printer.fans.append(Fan(10)) Fan.set_PWM_frequency(100) for f in self.printer.fans: f.set_value(0) # Make a queue of commands self.commands = Queue.Queue(10) # Set up USB, this receives messages and pushes them on the queue self.usb = USB(self.commands) # Virtual TTY self.pipe = Pipe(self.commands) #self.pipe.set_send_reponse(False) self.ethernet = Ethernet(self.commands) # Init the path planner Path.axis_config = int(self.printer.config.get('Geometry', 'axis_config')) Path.max_speed_x = float(self.printer.config.get('Steppers', 'max_speed_x')) Path.max_speed_y = float(self.printer.config.get('Steppers', 'max_speed_y')) Path.max_speed_z = float(self.printer.config.get('Steppers', 'max_speed_z')) Path.max_speed_e = float(self.printer.config.get('Steppers', 'max_speed_e')) Path.max_speed_h = float(self.printer.config.get('Steppers', 'max_speed_h')) Path.home_speed_x = float(self.printer.config.get('Steppers', 'home_speed_x')) Path.home_speed_y = float(self.printer.config.get('Steppers', 'home_speed_y')) Path.home_speed_z = float(self.printer.config.get('Steppers', 'home_speed_z')) Path.home_speed_e = float(self.printer.config.get('Steppers', 'home_speed_e')) Path.home_speed_h = float(self.printer.config.get('Steppers', 'home_speed_h')) dirname = os.path.dirname(os.path.realpath(__file__)) # Create the firmware compiler pru_firmware = PruFirmware(dirname+"/../firmware/firmware_runtime.p",dirname+"/../firmware/firmware_runtime.bin",dirname+"/../firmware/firmware_endstops.p",dirname+"/../firmware/firmware_endstops.bin",self.revision,self.printer.config,"/usr/bin/pasm") self.printer.path_planner = PathPlanner(self.printer.steppers, pru_firmware) self.printer.path_planner.set_acceleration(float(self.printer.config.get('Steppers', 'acceleration'))) travel={} offset={} for axis in ['X','Y','Z']: travel[axis] = self.printer.config.getfloat('Geometry', 'travel_'+axis.lower()) offset[axis] = self.printer.config.getfloat('Geometry', 'offset_'+axis.lower()) self.printer.path_planner.set_travel_length(travel) self.printer.path_planner.set_center_offset(offset) self.printer.processor = GCodeProcessor(self.printer); # After the firmwares are loaded, the endstop states can be updated. for k, endstop in self.printer.end_stops.iteritems(): logging.debug("Endstop "+endstop.name+" hit? : "+ str(endstop.read_value())) self.running = True # Signal everything ready logging.info("Redeem ready")
def execute(self, g): for i in range(g.num_tokens()): self.printer.steppers[g.token_letter(i)].\ set_current_value(float(g.token_value(i))) Stepper.commit()
def __init__(self): logging.info("Replicape initializing "+version) self.config = ConfigParser.ConfigParser() self.config.readfp(open('config/default.cfg')) # Make a list of steppers self.steppers = {} # Init the 5 Stepper motors (step, dir, fault, DAC channel, name) self.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X") self.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y") self.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z") self.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1") self.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2") # Enable the steppers and set the current, steps pr mm and microstepping for name, stepper in self.steppers.iteritems(): stepper.setCurrentValue(self.config.getfloat('Steppers', 'current_'+name)) stepper.setEnabled(self.config.getboolean('Steppers', 'enabled_'+name)) stepper.set_steps_pr_mm(self.config.getfloat('Steppers', 'steps_pr_mm_'+name)) stepper.set_microstepping(self.config.getint('Steppers', 'microstepping_'+name)) stepper.set_decay(0) # Commit changes for the Steppers Stepper.commit() # Find the path of the thermostors path = "/sys/bus/iio/devices/iio:device0/in_voltage" # init the 3 thermistors self.therm_ext1 = Thermistor(path+"4_raw", "MOSFET Ext 1", "B57561G0103F000") # Epcos 10K self.therm_hbp = Thermistor(path+"6_raw", "MOSFET HBP", "B57560G104F") # Epcos 100K self.therm_ext2 = Thermistor(path+"5_raw", "MOSFET Ext 2", "B57561G0103F000") # Epcos 10K if os.path.exists("/sys/bus/w1/devices/28-000002e34b73/w1_slave"): self.cold_end_1 = W1("/sys/bus/w1/devices/28-000002e34b73/w1_slave", "Cold End 1") # init the 3 heaters self.mosfet_ext1 = Mosfet(5) # Argument is channel number self.mosfet_ext2 = Mosfet(3) self.mosfet_hbp = Mosfet(4) # Make extruder 1 self.ext1 = Extruder(self.steppers["E"], self.therm_ext1, self.mosfet_ext1, "Ext1") self.ext1.setPvalue(0.1) self.ext1.setDvalue(0.3) self.ext1.setIvalue(0.0) # Make Heated Build platform self.hbp = HBP( self.therm_hbp, self.mosfet_hbp) # Make extruder 2. self.ext2 = Extruder(self.steppers["H"], self.therm_ext2, self.mosfet_ext2, "Ext2") self.ext1.setPvalue(0.1) self.ext1.setDvalue(0.3) self.ext1.setIvalue(0.0) self.current_tool = "E" # Init the three fans self.fan_1 = Fan(8) self.fan_2 = Fan(9) self.fan_3 = Fan(10) self.fans = {0: self.fan_1, 1:self.fan_2, 2:self.fan_3 } self.fan_1.setPWMFrequency(100) # Init the end stops self.end_stops = {} self.end_stops["X1"] = EndStop("GPIO3_21", self.steppers, 112, "X1") self.end_stops["X2"] = EndStop("GPIO0_30", self.steppers, 113, "X2") self.end_stops["Y1"] = EndStop("GPIO1_17", self.steppers, 114, "Y1") self.end_stops["Y2"] = EndStop("GPIO1_19", self.steppers, 115, "Y2") self.end_stops["Z1"] = EndStop("GPIO0_31", self.steppers, 116, "Z1") self.end_stops["Z2"] = EndStop("GPIO0_4", self.steppers, 117, "Z2") # Make a queue of commands self.commands = Queue.Queue(10) # Set up USB, this receives messages and pushes them on the queue #self.usb = USB(self.commands) self.pipe = Pipe(self.commands) self.ethernet = Ethernet(self.commands) # Init the path planner self.movement = "RELATIVE" self.feed_rate = 3000.0 self.current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0,"H":0.0} self.acceleration = 0.3 Path.axis_config = int(self.config.get('Geometry', 'axis_config')) Path.max_speed_x = float(self.config.get('Steppers', 'max_speed_x')) Path.max_speed_y = float(self.config.get('Steppers', 'max_speed_y')) Path.max_speed_z = float(self.config.get('Steppers', 'max_speed_z')) Path.max_speed_e = float(self.config.get('Steppers', 'max_speed_e')) Path.max_speed_h = float(self.config.get('Steppers', 'max_speed_h')) self.path_planner = Path_planner(self.steppers, self.current_pos) self.path_planner.set_acceleration(self.acceleration) # Signal everything ready logging.info("Replicape ready") print "Replicape ready"
class Osc2Steppers: """Class that listens for OSC messages, and forwards them as target positions for stepper motors""" stepper_time_interval_seconds = 0.02 def __init__(self, osc_ip='0.0.0.0', osc_port=12000): """Create our stepper object and osc server object""" self.debug = True # listen for OSC messages on port 12000 (Wekinator default) self.stepper_count = 2 #4 # Pin order: [ENB|MS1|MS2|MS3|RST|SLP|STP|DIR] self.stepper_A = Stepper([4, 5, 6, 7, 0, 0, 3, 2], "Stepper A", self.stepper_time_interval_seconds) self.stepper_B = Stepper([10, 11, 12, 13, 0, 0, 9, 26], "Stepper B", self.stepper_time_interval_seconds) self.stepper_C = Stepper([16, 17, 18, 19, 0, 0, 15, 14], "Stepper C", self.stepper_time_interval_seconds) self.stepper_D = Stepper([22, 23, 24, 25, 0, 0, 21, 20], "Stepper D", self.stepper_time_interval_seconds) print "Created 4 steppers" self.OSCServer = OSC.OSCServer((osc_ip, osc_port)) self.OSCServer.addMsgHandler('/wek/outputs', self.wek_outputs_handler) self.OSCServer.addMsgHandler('/tenta_emg', self.tenta_emg_handler) print "Tentacle Control is listening for OSC message /wek/outputs, ip %s port %s" % ( osc_ip, osc_port) def go(self): """Start steppers self-updating, and start our OSC server listening""" #self.stepper_A.go() self.stepper_B.go() self.stepper_C.go() self.stepper_D.go() self.OSCServer.serve_forever() def tenta_emg_handler(self, addr, tags, data, client_address): emg_avg = data[0] if emg_avg < 125: self.stepper_D.move_to_position(0) #position of closed elif emg_avg < 300: pos_interp = 0 - ((emg_avg - 125) / float(300 - 125)) * 200 self.stepper_D.move_to_position(pos_interp) #in between else: self.stepper_D.move_to_position(-200) #position of closed def wek_outputs_handler(self, addr, tags, data, client_address): """Callback that is called when we receive an osc message with path '/wek/outputs'""" # 0 controls back and front # 1 controls side to side data[0] *= 200 data[1] *= 200 if self.debug: print "OSCMessage '%s' from %s: %s" % (addr, client_address, data) if (len(data) != self.stepper_count): print "Error: Expected %s OSC values, got %s" % ( self.stepper_count, len(data)) return # HERE'S THE MAGIC! # Pass on values to our stepper motors #self.stepper_A.move_to_position(data[0]) self.stepper_B.set_delay() self.stepper_B.move_to_position(data[0]) #self.stepper_C.move_to_position(data[2]) self.stepper_C.set_delay() self.stepper_C.move_to_position(data[1])
time.sleep(1) systemData = SystemData() time.sleep(1) weather = Weather() time.sleep(1) #Actuators outsideFan = TimedDigitalActuator(20) time.sleep(1) insideFan = TimedDigitalActuator(21) time.sleep(1) humidifier = TimedDigitalActuator(16) time.sleep(1) hatch = Hatch() time.sleep(1) stepper = Stepper() time.sleep(1) #picture picture = Picture("Plant1") #silencer GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP) timeToSilence = 0 alloff = False while True: if not GPIO.input(12):
def execute(self,g): for i in range(g.num_tokens()): # Run through all tokens axis = g.tokenLetter(i) # Get the axis, X, Y, Z or E self.printer.steppers[axis].set_steps_pr_mm(float(g.token_value(i))) Stepper.commit()
def execute(self, g): for i in range(g.num_tokens()): self.printer.steppers[g.token_letter(i)].set_microstepping(int(g.token_value(i))) Stepper.commit()
return configFile_0 if __name__ == '__main__': from Printer import Printer from EndStop import EndStop from Stepper import Stepper, Stepper_00A3, Stepper_00A4, Stepper_00B1, Stepper_00B2, Stepper_00B3 from CascadingConfigParser import CascadingConfigParser printer = Printer() # Parse the config files. printer.config = CascadingConfigParser(['/etc/redeem/default.cfg']) # Init the 5 Stepper motors (step, dir, fault, DAC channel, name) printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, 0, "X") printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, 1, "Y") printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, 2, "Z") printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, 3, "E") printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, 4, "H") printer.steppers["A"] = Stepper("GPIO2_2", "GPIO1_18", "GPIO0_14", 5, 5, "A") printer.steppers["B"] = Stepper("GPIO1_16", "GPIO0_5", "GPIO0_14", 6, 6, "B") printer.steppers["C"] = Stepper("GPIO0_3", "GPIO3_19", "GPIO0_14", 7, 7, "C")
def execute(self, g): self.printer.path_planner.wait_until_done() for name, stepper in self.printer.steppers.iteritems(): if self.printer.config.getboolean('Steppers', 'in_use_' + name): stepper.set_enabled() Stepper.commit()
def main(argv): print argv while True: frame = vs.read() # creates CV2 frame frame = imutils.resize(frame, width=400) # frame resolution = 400x400 # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (9, 9), 0) # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) print "Brightest Value:", brightest_value # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out2, threshold2 = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY + cv2.THRESH_OTSU) out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY) thr = threshold.copy() print "out value:", out2 # Find contours in thresholded frame edged = cv2.Canny(threshold, 50, 150) # First one is source image, second is contour retrieval mode, third is contour approximation method. And it outputs # the contours and hierarchy. Contours is a Python list of all the contours in the image. Each individual contour # is a Numpy array of (x,y) coordinates of boundary points of the object. lightcontours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Checking if the list of contours is greater than 0 and if any circles are detected if (len(lightcontours)): # Finding the maxmimum contour, this is assumed to be the light beam maxcontour = max(lightcontours, key=cv2.contourArea) # Avoiding random spots of brightness by making sure the contour is reasonably sized if cv2.contourArea(maxcontour): (x, final_y), radius = cv2.minEnclosingCircle(maxcontour) print "x value:", x, "y value:", final_y # printing location of spot # Stepper class is responsible for determining if the current location of the brightest spot is # too far from the center and determines how far the stepper should move to accomodate for # finding the brightest spot t = Stepper( x, final_y) # imports current location into Stepper class t.change_position() cv2.circle(frame, (int(x), int(final_y)), int(radius), (0, 255, 0), 4) # draws a circle cv2.rectangle( frame, (int(x) - 5, int(final_y) - 5), (int(x) + 5, int(final_y) + 5), (0, 128, 255), -1) # determining the size f the frame space of frame # Display frames and exit # cv2.imshow('light', thr) cv2.imshow('frame', frame) # shows frame with newly imposed circle cv2.waitKey(4) key = cv2.waitKey(1) if cv2.waitKey(1) & 0xFF == ord( 'q'): # command to quit from current viewing of frame break cap.release() cv2.destroyAllWindows() # KILLS PROGRAM
from PIL import Image from Trainer import DataTrainer, ImageSequencer from Stepper import Stepper trainer = DataTrainer() stepper = Stepper() raw_file = open("data/training/wikipedia_cassettes.txt", 'r') raw_data = raw_file.read() raw_file.close() x = trainer.train_text_data( raw_text=raw_data, order=2, ) phrase = stepper.new_phrase(model=x, eol='EOL', punc=['!', '.', '?']) print(phrase)
def _execute(self, g): if g.code() == "G1": # Move (G1 X0.1 Y40.2 F3000) if g.hasLetter("F"): # Get the feed rate self.feed_rate = float(g.getValueByLetter("F"))/60000.0 # Convert from mm/min to SI unit m/s g.removeTokenByLetter("F") smds = {} # All steppers for i in range(g.numTokens()): # Run through all tokens axis = g.tokenLetter(i) # Get the axis, X, Y, Z or E smds[axis] = float(g.tokenValue(i))/1000.0 # Get the value, new position or vector if g.hasLetter("E") and self.current_tool != "E": # We are using a different tool, switch.. smds[self.current_tool] = smds["E"] del smds["E"] path = Path(smds, self.feed_rate, self.movement, g.is_crc())# Make a path segment from the axes self.path_planner.add_path(path) # Add the path. This blocks until the path planner has capacity #logging.debug("Moving to: "+' '.join('%s:%s' % i for i in smds.iteritems())) elif g.code() == "G21": # Set units to mm self.factor = 1.0 elif g.code() == "G28": # Home the steppers if g.numTokens() == 0: # If no token is given, home all g.setTokens(["X0", "Y0", "Z0"]) smds = {} # All steppers for i in range(g.numTokens()): # Run through all tokens axis = g.tokenLetter(i) # Get the axis, X, Y, Z or E smds[axis] = float(g.tokenValue(i)) # Get tha value, new position or vector path = Path(smds, self.feed_rate, "ABSOLUTE", False) # Make a path segment from the axes #logging.debug("moving to "+str(smds)) self.path_planner.add_path(path) # Add the path. This blocks until the path planner has capacity elif g.code() == "G90": # Absolute positioning self.movement = "ABSOLUTE" elif g.code() == "G91": # Relative positioning self.movement = "RELATIVE" elif g.code() == "G92": # Set the current position of the following steppers #self.path_planner.wait_until_done() if g.numTokens() == 0: logging.debug("Adding all to G92") g.setTokens(["X0", "Y0", "Z0", "E0", "H0"]) # If no token is present, do this for all #for i in range(g.numTokens()): # axis = g.tokenLetter(i) # val = float(g.tokenValue(i)) # self.path_planner.set_pos(axis, val) pos = {} # All steppers for i in range(g.numTokens()): # Run through all tokens axis = g.tokenLetter(i) # Get the axis, X, Y, Z or E pos[axis] = float(g.tokenValue(i))/1000.0 # Get the value, new position or vector logging.debug(pos) path = Path(pos, self.feed_rate, "G92") # Make a path segment from the axes self.path_planner.add_path(path) elif g.code() == "M17": # Enable all steppers self.path_planner.wait_until_done() for name, stepper in self.steppers.iteritems(): stepper.setEnabled() Stepper.commit() elif g.code() == "M19": # Reset all steppers self.path_planner.wait_until_done() for name, stepper in self.steppers.iteritems(): stepper.reset() elif g.code() == "M30": # Set microstepping (Propietary to Replicape) for i in range(g.numTokens()): self.steppers[g.tokenLetter(i)].set_microstepping(int(g.tokenValue(i))) Stepper.commit() elif g.code() == "M31": # Set stepper current limit (Propietery to Replicape) for i in range(g.numTokens()): self.steppers[g.tokenLetter(i)].setCurrentValue(float(g.tokenValue(i))) Stepper.commit() elif g.code() == "M84": # Disable all steppers self.path_planner.wait_until_done() for name, stepper in self.steppers.iteritems(): stepper.setDisabled() Stepper.commit() elif g.code() == "M92": # M92: Set axis_steps_per_unit for i in range(g.numTokens()): # Run through all tokens axis = g.tokenLetter(i) # Get the axis, X, Y, Z or E self.steppers[axis].set_steps_pr_mm(float(g.tokenValue(i))) Stepper.commit() elif g.code() == "M101": # Deprecated pass elif g.code() == "M103": # Deprecated pass elif g.code() == "M104": # Set extruder temperature if g.hasLetter("P"): if int(g.getValueByLetter("P")) == 0: self.ext1.setTargetTemperature(float(g.getValueByLetter("S"))) elif int(g.getValueByLetter("P")) == 1: logging.debug("setting ext 2 temp to "+str(g.getValueByLetter("S"))) self.ext2.setTargetTemperature(float(g.getValueByLetter("S"))) else: logging.debug("setting ext 1 temp to "+str(g.tokenValue(0))) self.ext1.setTargetTemperature(float(g.tokenValue(0))) elif g.code() == "M105": # Get Temperature answer = "ok T:"+str(self.ext1.getTemperature()) if hasattr(self, "hbp"): answer += " B:"+str(int(self.hbp.getTemperature())) if hasattr(self, "ext2"): answer += " T1:"+str(int(self.ext2.getTemperature())) if hasattr(self, "cold_end_1"): answer += " T2:"+str(int(self.cold_end_1.getTemperature())) g.setAnswer(answer) elif g.code() == "M106": # Fan on if g.hasLetter("P"): fan = self.fans[int(g.getValueByLetter("P"))] fan.set_value(float(g.getValueByLetter("S"))/255.0) # According to reprap wiki, the number is 0..255 else: # if there is no fan-number present, do it for the first fan self.fan_1.set_value(float(g.tokenValue(0))/255.0) elif g.code() == "M108": # Deprecated pass elif g.code() == "M109": self.hbp.setTargetTemperature(float(g.getValueByLetter("S"))) elif g.code() == "M110": # Reset the line number counter Gcode.line_number = 0 elif g.code() == "M114": g.setAnswer("ok C: "+' '.join('%s:%s' % i for i in self.current_pos.iteritems())) elif g.code() == "M130": # Set PID P-value, Format (M130 P0 S8.0) pass #if int(self.tokens[0][1]) == 0: # self.ext1.setPvalue(float(self.tokens[1][1::])) elif g.code() == "M131": # Set PID I-value, Format (M131 P0 S8.0) pass #if int(self.tokens[0][1]) == 0: # self.p.ext1.setPvalue(float(self.tokens[1][1::])) elif g.code() == "M132": # Set PID D-value, Format (M132 P0 S8.0) pass #if int(self.tokens[0][1]) == 0: # self.p.ext1.setPvalue(float(self.tokens[1][1::])) elif g.code() == "M140": # Set bed temperature self.hbp.setTargetTemperature(float(g.tokenValue(0))) elif g.code() == "M141": fan = self.fans[int(g.getValueByLetter("P"))] fan.setPWMFrequency(int(g.getValueByLetter("F"))) fan.set_value(float(g.getValueByLetter("S"))) elif g.code() == "M190": self.hbp.setTargetTemperature(float(g.getValueByLetter("S"))) elif g.code() == "T0": # Select tool 0 self.current_tool = "E" elif g.code() == "T1": # select tool 1 self.current_tool = "H" else: logging.warning("Unknown command: "+g.message)
from Stepper import Stepper # TEST FILE FOR DETERMINING IF IT WORKS # ONLY RUN THIS FILE t = Stepper(0, 0) #print t.x_raw #print t.y_raw #t.change_position() #t.forward(4,40) t.run() #t.forward(19,4) #steps = raw_input("How many steps forward? ") # Testing (The delay value has to be divided by 1000 to achieve the desired delay) #t.backwards(int(Stepper.delay) / 1000.0, int(steps))
def execute(self,g): self.printer.path_planner.wait_until_done() for name, stepper in self.printer.steppers.iteritems(): if self.printer.config.getboolean('Steppers', 'enabled_'+name): stepper.set_enabled() Stepper.commit()
steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y",1,None,1,1) steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z",1,None,2,2) steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1",-1,None,3,3) steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2",-1,None,4,4) config = ConfigParser.ConfigParser() config.readfp(open('config/default.cfg')) for name, stepper in steppers.iteritems(): stepper.setCurrentValue(config.getfloat('Steppers', 'current_'+name)) stepper.setEnabled(config.getboolean('Steppers', 'enabled_'+name)) stepper.set_steps_pr_mm(config.getfloat('Steppers', 'steps_pr_mm_'+name)) stepper.set_microstepping(config.getint('Steppers', 'microstepping_'+name)) stepper.set_decay(1) # Commit changes for the Steppers Stepper.commit() Path.axis_config = int(config.get('Geometry', 'axis_config')) Path.max_speed_x = float(config.get('Steppers', 'max_speed_x')) Path.max_speed_y = float(config.get('Steppers', 'max_speed_y')) Path.max_speed_z = float(config.get('Steppers', 'max_speed_z')) Path.max_speed_e = float(config.get('Steppers', 'max_speed_e')) Path.max_speed_h = float(config.get('Steppers', 'max_speed_h')) current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0} pp = Path_planner(steppers, current_pos) pp.set_acceleration(0.3) nb = 10
circles = cv2.HoughCircles(threshold, cv2.cv.CV_HOUGH_GRADIENT, 1.0, 20, param1=10, param2=15, minRadius=20, maxRadius=100, ) # Checking if the list of contours is greater than 0 and if any circles are detected if (len(lightcontours)): # Finding the maxmimum contour, this is assumed to be the light beam maxcontour = max(lightcontours, key=cv2.contourArea) # Avoiding random spots of brightness by making sure the contour is reasonably sized if cv2.contourArea(maxcontour): (x, final_y), radius = cv2.minEnclosingCircle(maxcontour) print "x value:",x,"y value:",final_y t=Stepper(x,final_y) t.change_position() cv2.circle(frame, (int(x), int(final_y)), int(radius), (0, 255, 0), 4) cv2.rectangle(frame, (int(x) - 5, int(final_y) - 5), (int(x) + 5, int(final_y) + 5), (0, 128, 255), -1) # Display frames and exit cv2.imshow('light', thr) cv2.imshow('frame', frame) cv2.waitKey(4) key = cv2.waitKey(1) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
from Stepper import Stepper from time import sleep EN_PIN = 23 STP_PIN = 27 DIR_PIN = 22 stepper = Stepper(23, 27, 22) def main(): print("Setting Up...") stepper.step('left', 90) sleep(1) stepper.step('right', 180) print("Ran...") stepper.cleanupPins() if __name__ == "__main__": try: main() except KeyboardInterrupt: stepper.cleanupPins() print("interrupted...") pass
# Initiate IO GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) def registerGPIO(pins): for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, False) HPins = [17, 27, 22, 23] VPins = [6, 13, 19, 26] Hori = Stepper(HPins) Vert = Stepper(VPins) steppers = [Hori, Vert] registerGPIO(HPins) registerGPIO(VPins) # Breathe time.sleep(0.5) # Main program createThread(Hori.moveTo, -300) createThread(Vert.moveTo, 150) startAllThreads() clearThreads()
def main(argv): bright_values = {} # creates an array of the brightest values count = 0 while True: if count == 7: # looks for 7 different spots break frame = vs.read() # reads the frame from the OpenCV object frame = imutils.resize( frame, width=400 ) # resizing the frame in case frame was changed previously # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (9, 9), 0) # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY + cv2.THRESH_OTSU) time.sleep(1) if os.path.isfile('mem.txt'): # finds txt file fp = open("mem.txt", 'r') current_val = [int(n) for n in fp.read().split() ] # reads current position print "current_val", current_val[0], "out", out bright_values[int( current_val[0])] = out # found the brightest value and storing else: bright_values[257] = out count = count + 1 # counter to happen 7 times t = Stepper(0, 0) t.change_position_scan() # moves stepper to scan print bright_values i = 0 for w in sorted(bright_values, key=bright_values.get, reverse=True): # sorts the 7 brightest values if i > 0: break print w, bright_values[w] # prints all values required_pos = w i = i + 1 print "required_pos", required_pos t.return_to_bright_spot(required_pos) # found required spot while True: frame = vs.read() frame = imutils.resize(frame, width=400) # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (9, 9), 0) # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) print "Brightest Value:", brightest_value # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out2, threshold2 = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY + cv2.THRESH_OTSU) out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY) thr = threshold.copy() print "out value:", out2 # Resize frame for ease # cv2.resize(thr, (300, 300)) # Find contours in thresholded frame edged = cv2.Canny(threshold, 50, 150) # First one is source image, second is contour retrieval mode, third is contour approximation method. And it outputs # the contours and hierarchy. Contours is a Python list of all the contours in the image. Each individual contour # is a Numpy array of (x,y) coordinates of boundary points of the object. lightcontours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Checking if the list of contours is greater than 0 and if any circles are detected if (len(lightcontours)): # Finding the maxmimum contour, this is assumed to be the light beam maxcontour = max(lightcontours, key=cv2.contourArea) # Avoiding random spots of brightness by making sure the contour is reasonably sized if cv2.contourArea(maxcontour): (x, final_y), radius = cv2.minEnclosingCircle( maxcontour) # drawing circle print "x value:", x, "y value:", final_y t = Stepper(x, final_y) t.change_position() cv2.circle(frame, (int(x), int(final_y)), int(radius), (0, 255, 0), 4) cv2.rectangle(frame, (int(x) - 5, int(final_y) - 5), (int(x) + 5, int(final_y) + 5), (0, 128, 255), -1) # creating frame # Display frames and exit # cv2.imshow('light', thr) cv2.imshow('frame', frame) # showing frame cv2.waitKey(4) key = cv2.waitKey(1) if cv2.waitKey(1) & 0xFF == ord('q'): # q TERMINATES PROGRAM break cap.release() cv2.destroyAllWindows() # KILLS ALL WINDOWS
if __name__ == '__main__': from Stepper import Stepper from Path import Path import cProfile import ConfigParser logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M') print "Making steppers" steppers = {} steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X", -1, None, 0, 0) steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y", 1, None, 1, 1) steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z", 1, None, 2, 2) steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1", -1, None, 3, 3) steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2", -1, None, 4, 4) config = ConfigParser.ConfigParser() config.readfp(open('config/default.cfg')) for name, stepper in steppers.iteritems(): stepper.setCurrentValue(config.getfloat('Steppers', 'current_' + name)) stepper.setEnabled(config.getboolean('Steppers', 'enabled_' + name)) stepper.set_steps_pr_mm(
import argparse, os, pickle from PIL import Image from Trainer import DataTrainer, ImageSequencer from Stepper import Stepper trainer = DataTrainer() stepper = Stepper() img_sequencer = ImageSequencer() parser = argparse.ArgumentParser(description='Collect and curate a dataset of images.') parser.add_argument('directory', nargs=1) parser.add_argument('--size', nargs=2, type=int) parser.add_argument('--norder', nargs=1, type=int) parser.add_argument('--pickle', nargs=1, type=bool) args = parser.parse_args() directory = args.directory[0] im_width, im_height = args.size norder = args.norder[0] try: should_pickle = args.pickle[0] except: should_pickle = False pickle_file_name = "{width}-{height}-{norder}.pickle".format(width=im_width, height=im_height, norder=norder) pickled_data = {} preexisting_pickle = False # checks for and loads pickle if should_pickle:
def main(argv): bright_values = {} # creates an array of the brightest values count = 0 while True: if count == 7: # looks for 7 different spots break frame = vs.read() # reads the frame from the OpenCV object frame = imutils.resize( frame, width=400 ) # resizing the frame in case frame was changed previously # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (9, 9), 0) # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY + cv2.THRESH_OTSU) time.sleep(1) if os.path.isfile('mem.txt'): # finds txt file fp = open("mem.txt", 'r') current_val = [int(n) for n in fp.read().split() ] # reads current position print "current_val", current_val[0], "out", out bright_values[int( current_val[0])] = out # found the brightest value and storing else: bright_values[257] = out count = count + 1 # counter to happen 7 times t = Stepper(0, 0) t.change_position_scan() # moves stepper to scan print bright_values i = 0 for w in sorted(bright_values, key=bright_values.get, reverse=True): # sorts the 7 brightest values if i > 0: break print w, bright_values[w] # prints all values required_pos = w i = i + 1 print "required_pos", required_pos t.return_to_bright_spot(required_pos) # found required spot while True: frame = vs.read() frame = imutils.resize(frame, width=400) # Converting captured frame to monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Blurring the image using the GaussianBlur() method of the opencv object blur = cv2.GaussianBlur(gray, (39, 39), 0) cv2.imshow("blur", blur) # copy = frame.copy() # Using an opencv method to identify the threshold intensities and locations (darkest_value, brightest_value, darkest_loc, brightest_loc) = cv2.minMaxLoc(blur) #print "brightest Value:", brightest_value-200 # Threshold the blurred frame accordingly # First argument is the source image, which is the grayscale image. Second argument is the threshold value # which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given # if pixel value is more than (sometimes less than) the threshold value out, threshold = cv2.threshold(blur, brightest_value - 10, 230, cv2.THRESH_BINARY) # print "Threshold:", out2 thr = threshold.copy() # Resize frame for ease # cv2.resize(thr, (300, 300)) # Find contours in thresholded frame edged = cv2.Canny(threshold, 50, 150) # First one is source image, second is contour retrieval mode, third is contour approximation method. And it outputs # the contours and hierarchy. contours is a Python list of all the contours in the image. Each individual contour # is a Numpy array of (x,y) coordinates of boundary points of the object. # Possible second parameter options # RETR_EXTERNAL # retrieves only the extreme outer contours. It sets hierarchy[i][2]=hierarchy[i][3]=-1 for all the contours. # RETR_LIST # retrieves all of the contours without establishing any hierarchical relationships. # RETR_CCOMP # retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level. # RETR_TREE # retrieves all of the contours and reconstructs a full hierarchy of nested contours. # RETR_FLOODFILL # Possible 3 parameter options # CHAIN_APPROX_NONE # stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, max(abs(x1-x2),abs(y2-y1))==1. # CHAIN_APPROX_SIMPLE # compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points. # CHAIN_APPROX_TC89_L1 # applies one of the flavors of the Teh-Chin chain approximation algorithm [151] # CHAIN_APPROX_TC89_KCOS # applies one of the flavors of the Teh-Chin chain approximation algorithm [151] lightcontours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contour = [] # print contour # print "length of lightcontours:", len(lightcontours) # print "length of contour:", len(contour) # print "Number of contours:", len(lightcontours) # # Checking if the list of contours is greater than 0 and if any circles are detected # print "range(len(con)):", range(len(lightcontours)) for i in range(len(lightcontours)): (x, final_y), radius = cv2.minEnclosingCircle(lightcontours[i]) print "First Time-----", "x value:", x, "y value", final_y, "radius", radius if radius < 20: print "Inside special if statement" contour.append(lightcontours[i]) else: continue print "Length of numpy array containing all light contours:", len( lightcontours) print "Length of list containing contours with specified radius:", len( contour) print contour if (len(contour) > 0): # Finding the maxmimum contour, this is assumed to be the light beam maxcontour = max(contour, key=cv2.contourArea) # Avoiding random spots of brightness by making sure the contour is reasonably sized if cv2.contourArea(maxcontour): (x, final_y), radius = cv2.minEnclosingCircle(maxcontour) print "x value:", x, "y value:", final_y t = Stepper(x, final_y) s = Servo(final_y) s.servo_control() # t.change_position() cv2.circle(frame, (int(x), int(final_y)), int(radius + 20), (0, 255, 0), 4) cv2.rectangle(frame, (int(x) - 5, int(final_y) - 5), (int(x) + 5, int(final_y) + 5), (0, 128, 255), -1) # Display frames and exit # cv2.imshow('light', thr) cv2.imshow('frame', frame) cv2.waitKey(4) key = cv2.waitKey(1) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
def __init__(self): """ Init """ logging.info("Redeem initializing " + version) self.printer = Printer() # Parse the config files. self.printer.config = CascadingConfigParser( ['/etc/redeem/default.cfg', '/etc/redeem/printer.cfg', '/etc/redeem/local.cfg']) # Get the revision and loglevel from the Config file self.revision = self.printer.config.get('System', 'revision', "A4") level = self.printer.config.getint('System', 'loglevel') if level > 0: logging.getLogger().setLevel(level) logging.info("Replicape revision " + self.revision) # Init the end stops EndStop.callback = self.end_stop_hit EndStop.inputdev = self.printer.config.get("Endstops", "inputdev"); if self.revision == "A4" or self.revision == "A4A": self.printer.end_stops["X1"] = EndStop("GPIO3_21", 112, "X1", self.printer.config.getboolean( "Endstops", "invert_X1")) self.printer.end_stops["X2"] = EndStop("GPIO0_30", 113, "X2", self.printer.config.getboolean( "Endstops", "invert_X2")) self.printer.end_stops["Y1"] = EndStop("GPIO1_17", 114, "Y1", self.printer.config.getboolean( "Endstops", "invert_Y1")) self.printer.end_stops["Y2"] = EndStop("GPIO1_19", 115, "Y2", self.printer.config.getboolean( "Endstops", "invert_Y2")) self.printer.end_stops["Z1"] = EndStop("GPIO0_31", 123, "Z1", self.printer.config.getboolean( "Endstops", "invert_Z1")) self.printer.end_stops["Z2"] = EndStop("GPIO0_4", 117, "Z2", self.printer.config.getboolean( "Endstops", "invert_Z2")) else: self.printer.end_stops["X1"] = EndStop("GPIO0_14", 112, "X1", self.printer.config.getboolean( "Endstops", "invert_X1")) self.printer.end_stops["X2"] = EndStop("GPIO3_21", 113, "X2", self.printer.config.getboolean( "Endstops", "invert_X2")) self.printer.end_stops["Y1"] = EndStop("GPIO2_2", 114, "Y1", self.printer.config.getboolean( "Endstops", "invert_Y1")) self.printer.end_stops["Y2"] = EndStop("GPIO0_31", 115, "Y2", self.printer.config.getboolean( "Endstops", "invert_Y2")) self.printer.end_stops["Z1"] = EndStop("GPIO0_30", 123, "Z1", self.printer.config.getboolean( "Endstops", "invert_Z1")) self.printer.end_stops["Z2"] = EndStop("GPIO0_4", 117, "Z2", self.printer.config.getboolean( "Endstops", "invert_Z2")) if self.revision == "A3": Stepper.revision = "A3" Stepper.ENABLED = 6 Stepper.SLEEP = 5 Stepper.RESET = 4 Stepper.DECAY = 0 # Init the 5 Stepper motors (step, dir, fault, DAC channel, name) self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X", self.printer.end_stops["X1"], 0, 0) self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y", self.printer.end_stops["Y1"], 1, 1) self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z", self.printer.end_stops["Z1"], 2, 2) self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "E", None, 3, 3) self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "H", None, 4, 4) # Enable the steppers and set the current, steps pr mm and # microstepping for name, stepper in self.printer.steppers.iteritems(): stepper.set_current_value( self.printer.config.getfloat('Steppers', 'current_' + name)) stepper.in_use = self.printer.config.getboolean('Steppers', 'in_use_' + name) stepper.set_steps_pr_mm(self.printer.config.getfloat('Steppers', 'steps_pr_mm_' + name)) stepper.set_microstepping(self.printer.config.getint('Steppers', 'microstepping_' + name)) stepper.direction = self.printer.config.getint('Steppers', 'direction_' + name) stepper.set_decay(self.printer.config.getboolean("Steppers", "slow_decay_" + name)) stepper.has_endstop = self.printer.config.getboolean('Endstops', 'has_' + name) # Commit changes for the Steppers Stepper.commit() # Find the path of the thermistors path = "/sys/bus/iio/devices/iio:device0/in_voltage" # init the 3 thermistors therm_ext1 = Thermistor(path + "4_raw", "MOSFET Ext 1", self.printer.config.get('Heaters', "ext1_temp_chart")) therm_hbp = Thermistor(path + "6_raw", "MOSFET HBP", self.printer.config.get('Heaters', "hbp_temp_chart")) therm_ext2 = Thermistor(path + "5_raw", "MOSFET Ext 2", self.printer.config.get('Heaters', "ext2_temp_chart")) path = self.printer.config.get('Cold-ends', 'path', 0) if os.path.exists(path): self.printer.cold_ends.append(ColdEnd(path, "Cold End 0")) logging.info("Found Cold end on " + path) else: logging.info("No cold end present in path: " + path) # Init the 3 heaters. Argument is channel number if self.revision == "A3": mosfet_ext1 = Mosfet(3) mosfet_ext2 = Mosfet(5) mosfet_hbp = Mosfet(4) else: mosfet_ext1 = Mosfet(5) mosfet_ext2 = Mosfet(3) mosfet_hbp = Mosfet(4) # Make extruder 1 self.printer.heaters['E'] = Extruder(self.printer.steppers["E"], therm_ext1, mosfet_ext1, "Ext1", self.printer.config.getboolean( 'Heaters', 'ext1_onoff_control')) self.printer.heaters['E'].P = self.printer.config.getfloat('Heaters', "ext1_pid_p") self.printer.heaters['E'].I = self.printer.config.getfloat('Heaters', "ext1_pid_i") self.printer.heaters['E'].D = self.printer.config.getfloat('Heaters', "ext1_pid_d") self.printer.heaters['E'].ok_range = self.printer.config.getfloat( 'Heaters', "ext1_ok_range") # Make Heated Build platform self.printer.heaters['HBP'] = HBP(therm_hbp, mosfet_hbp, self.printer.config.getboolean( 'Heaters', 'hbp_onoff_control')) self.printer.heaters['HBP'].P = self.printer.config.getfloat('Heaters', "hbp_pid_p") self.printer.heaters['HBP'].I = self.printer.config.getfloat('Heaters', "hbp_pid_i") self.printer.heaters['HBP'].D = self.printer.config.getfloat('Heaters', "hbp_pid_d") self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat( 'Heaters', "hbp_ok_range") # Make extruder 2. self.printer.heaters['H'] = Extruder(self.printer.steppers["H"], therm_ext2, mosfet_ext2, "Ext2", self.printer.config.getboolean( 'Heaters', 'ext2_onoff_control')) self.printer.heaters['H'].P = self.printer.config.getfloat('Heaters', "ext2_pid_p") self.printer.heaters['H'].I = self.printer.config.getfloat('Heaters', "ext2_pid_i") self.printer.heaters['H'].D = self.printer.config.getfloat('Heaters', "ext2_pid_d") self.printer.heaters['H'].ok_range = self.printer.config.getfloat( 'Heaters', "ext2_ok_range") # Init the three fans. Argument is PWM channel number self.printer.fans = [] if self.revision == "A3": self.printer.fans.append(Fan(0)) self.printer.fans.append(Fan(1)) self.printer.fans.append(Fan(2)) else: self.printer.fans.append(Fan(8)) self.printer.fans.append(Fan(9)) self.printer.fans.append(Fan(10)) Fan.set_PWM_frequency(100) for f in self.printer.fans: f.set_value(0) # Connect the cold end 0 to fan 2 # This is very "Thing" specific, should be configurable somehow. if len(self.printer.cold_ends): self.printer.coolers.append( Cooler(self.printer.cold_ends[0], self.printer.fans[2], "Cooler0", False)) self.printer.coolers[0].ok_range = 4 self.printer.coolers[0].set_target_temperature(60) self.printer.coolers[0].enable() # Make a queue of commands self.printer.commands = JoinableQueue(10) # Make a queue of commands that should not be buffered self.printer.unbuffered_commands = JoinableQueue(10) # Init the path planner Path.axis_config = int( self.printer.config.get('Geometry', 'axis_config')) Path.max_speeds[0] = float( self.printer.config.get('Steppers', 'max_speed_x')) Path.max_speeds[1] = float( self.printer.config.get('Steppers', 'max_speed_y')) Path.max_speeds[2] = float( self.printer.config.get('Steppers', 'max_speed_z')) Path.max_speeds[3] = float( self.printer.config.get('Steppers', 'max_speed_e')) Path.max_speeds[4] = float( self.printer.config.get('Steppers', 'max_speed_h')) Path.home_speed[0] = float( self.printer.config.get('Steppers', 'home_speed_x')) Path.home_speed[1] = float( self.printer.config.get('Steppers', 'home_speed_y')) Path.home_speed[2] = float( self.printer.config.get('Steppers', 'home_speed_z')) Path.home_speed[3] = float( self.printer.config.get('Steppers', 'home_speed_e')) Path.home_speed[4] = float( self.printer.config.get('Steppers', 'home_speed_h')) Path.steps_pr_meter[0] = self.printer.steppers[ "X"].get_steps_pr_meter() Path.steps_pr_meter[1] = self.printer.steppers[ "Y"].get_steps_pr_meter() Path.steps_pr_meter[2] = self.printer.steppers[ "Z"].get_steps_pr_meter() Path.steps_pr_meter[3] = self.printer.steppers[ "E"].get_steps_pr_meter() Path.steps_pr_meter[4] = self.printer.steppers[ "H"].get_steps_pr_meter() dirname = os.path.dirname(os.path.realpath(__file__)) # Create the firmware compiler pru_firmware = PruFirmware( dirname + "/../firmware/firmware_runtime.p", dirname + "/../firmware/firmware_runtime.bin", dirname + "/../firmware/firmware_endstops.p", dirname + "/../firmware/firmware_endstops.bin", self.revision, self.printer.config, "/usr/bin/pasm") self.printer.maxJerkXY = float( self.printer.config.get('Steppers', 'maxJerk_xy')); self.printer.maxJerkZ = float( self.printer.config.get('Steppers', 'maxJerk_z')); self.printer.maxJerkEH = float( self.printer.config.get('Steppers', 'maxJerk_eh')); self.printer.path_planner = PathPlanner(self.printer, pru_firmware) travel = {} offset = {} i = 0 for axis in ['X', 'Y', 'Z', 'E', 'H']: travel[axis] = self.printer.config.getfloat('Geometry', 'travel_' + axis.lower()) offset[axis] = self.printer.config.getfloat('Geometry', 'offset_' + axis.lower()) self.printer.acceleration[i] = self.printer.config.getfloat('Steppers', 'acceleration_' + axis.lower()) i += 1 self.printer.path_planner.travel_length = travel self.printer.path_planner.center_offset = offset self.printer.processor = GCodeProcessor(self.printer) # Set up communication channels self.printer.comms["USB"] = USB(self.printer) self.printer.comms["Eth"] = Ethernet(self.printer) self.printer.comms["octoprint"] = Pipe(self.printer, "octoprint") # Pipe for Octoprint self.printer.comms["toggle"] = Pipe(self.printer, "toggle") # Pipe for Toggle self.printer.comms["testing"] = Pipe(self.printer, "testing") # Pipe for testing self.printer.comms["testing_noret"] = Pipe(self.printer, "testing_noret") # Pipe for testing self.printer.comms["testing_noret"].send_response = False self.running = True # Start the two processes p0 = Thread(target=self.loop, args=(self.printer.commands, "buffered")) p1 = Thread(target=self.loop, args=(self.printer.unbuffered_commands, "unbuffered")) p0.daemon = True p1.daemon = True p0.start() p1.start() # Signal everything ready logging.info("Redeem ready") # Wait for exit signal p0.join() p1.join()
from Stepper import Stepper import time stepper_time_interval_seconds = 0.1 # Pin order: [ENB|MS1|MS2|MS3|RST|SLP|STP|DIR] stepper_A = Stepper([4, 7, 6, 5, 0, 0, 3, 2], "Stepper A", stepper_time_interval_seconds) stepper_B = Stepper([10, 11, 12, 13, 0, 0, 9, 8], "Stepper B", stepper_time_interval_seconds) stepper_C = Stepper([16, 17, 18, 19, 0, 0, 15, 14], "Stepper C", stepper_time_interval_seconds) stepper_D = Stepper([22, 23, 24, 25, 0, 0, 21, 20], "Stepper D", stepper_time_interval_seconds) print "Created 4 steppers" stepper_A.go() # stepper_B.go() # stepper_C.go() # stepper_D.go() time.sleep(2) # Sleep 5 seconds stepper_A.move_to_position(32.0) print("Moved goal to 32") time.sleep(4) # Sleep 5 seconds stepper_B.move_to_position(-26.0) print("Moved goal to 32")
from Stepper import Stepper #stepper variables #[stepPin, directionPin, enablePin] testStepper = Stepper([22, 17, 23]) #test stepper testStepper.step(3200, "right") #steps, dir, speed, stayOn