def __init__(self): self.tweety = Finch() # Set obstacle sensors self.left_obst, self.right_obst = self.tweety.obstacle() # Setting initial lighting self.myLights = lighting(self.tweety) # Setting initial acceleration settings self.x, self.y, self.z, self.tap, self.shake = self.tweety.acceleration() # Setting initial wheel speed self.left_wheel = 0.0 self.right_wheel = 0.0 self.tweety.wheels(self.left_wheel, self.right_wheel)
def q2(): from time import sleep from finch import Finch # this code won't actually work unless you install the finch package # or you can replace this with the ebot equivalent if you want # to run the code # Whatever the case, the concept is the same finch = Finch() finch.wheels(0.2,0.2) leftObstacle, rightObstacle = finch.obstacle() while leftObstacle == False and rightObstacle == False: finch.wheels(0.2,0.2) finch.halt() finch.close()
def Connect(): for i in range (2): try: newFinch = Finch() return newFinch except: if i == 0: print "Failed to connect to Finch on the first try" Quit(newFinch) newFinch = 0 print "Failed to connect to Finch on the second try" return newFinch
def Connect(): #a function that connects the finch to the python methods for i in range (2): #loop of two try: #first attempt newFinch=Finch() #sets a variable equal to connection return newFinch except: if i==0: print "Failed to connect to Finch on the first try" #prints a statement that the finch failed to connect the first time Quit(newFinch) newFinch=0 #resets newFinch varv - iable to 0 print "Failed to connect to Finch on the second try" #prints a statement that the finch failed to connect the second time return newFinch #returns the value of newFinch
def __init__(self, left, right, inAdjustmentMode=False): self.leftWheel = left self.rightWheel = right self.myBot = Finch() # Keep track of the direction you should try on obstacles self.obstacleDirectionToTry = finchConstants.LEFT self.lastScrapedSide = " " # Keep track of when the last time you moved forward, we use that # to identify sensors self.lastTimeIMovedForward = -1 # Use vars below for logging when self.lastPersistedLeftObstacleState = False self.lastPersistedRightObstacleState = False # Obstacle reading goes haywire... we'll count up readings within # an interval and use the overall score to report self.lastObstacleReading = 0.0 self.lastObstacleReadingLeftScores = [0, 0, 0, 0, 0] self.lastObstacleReadingRightScores = [0, 0, 0, 0, 0] self.scorePosition = 0 self.obstacleNumberOfScores = len(self.lastObstacleReadingLeftScores) self.obstacleState = { "left": False, "leftStateTime": 0.0, "leftElapsedTime": 0.0, "right": False, "rightStateTime": 0.0, "rightElapsedTime": 0.0 } # If true then wheel speed will be adjusted by the constants self.inWheelAdjustmentMode = inAdjustmentMode self.lasttime = time.time() self.update(self.inWheelAdjustmentMode)
# Race track driver, an example program for the Finch # Watch the Finch navigate a square race track from finch import Finch from time import sleep #Main function for the race track driver example program.""" #Initialize the finch finch = Finch() #Set both wheels to one-half forward throttle for 1.5s finch.wheels(0.5,0.5) finch.led(0, 255, 255) sleep(1.5) # Now set the left wheel at half throttle, right wheel off to turn finch.wheels(0.5,0) finch.led(0, 255, 0) sleep(1.28) finch.wheels(0.5,0.5) finch.led(0, 255, 255) sleep(1.5) finch.wheels(0.5,0) finch.led(0, 255, 0) sleep(1.28)
###################################### # Team Awesome # Advanced Topics - Robotics CMPS 367 # demo 2 battery function ###################################### import signal, os from time import sleep from finch import Finch tweety = Finch() # signal handler def batteryHandler(signum, frame): print('alarm triggered! Shutting down', signum) exit() # setup signal signal.signal(signal.SIGALRM, batteryHandler) # test that alarm will continue to count through sleep signal.alarm(7) sleep(5) print("This should print without the alarm going off.") # test alarm being reset signal.alarm(7) - 6 sleep(9)
The Finch is a robot for computer science education. Its design is the result of a four year study at Carnegie Mellon's CREATE lab. http://www.finchrobot.com """ from finch import Finch from time import sleep import notes #Main function for the music player example program""" #Initialize the finch mode = input("What mode, alarm or muysic player?") finch = Finch() x, y, z, tap, shake = finch.acceleration() zAccel = finch.acceleration()[2] timeList = [0.18, 0.1, 0.1, 0.1] if mode != 'a': songList = [ 'E5 C D E C D E F D E F D E F G A GE F C D E G E D C ', 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ' 'E D5 A4 G G5 A4 F5# A4 E D5 A4 G G5 A4 F5# A4 ' 'G D5 A4 G G5 A4 F5# A4 G D5 A4 G G5 A4 F5# A4 ' 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ', 'E5 E E C E G G4 C5 G4 E A BBb A G ' 'E5 G A F G E C D B4 C5 G4 E A BBb A G ' 'E5 G A F G E C D B4 - G5 Gb F D# E G4# A C5 A4 C5 D ' 'G5 Gb F D# E C6 C6 C6 '
"""Let's make the Finch robot dance!""" from finch import Finch from time import sleep finch = Finch() ##### CHANGE CODE BELOW THIS LINE ##### finch.led(0, 255, 0) finch.wheels(0.75, 0.75) sleep(1.5) finch.led(0, 0, 255) finch.wheels(-0.75, -0.75) sleep(1.5) finch.halt()
from finch import Finch from time import sleep #Main function for the race track driver example program.""" #Initialize the finch finch = Finch() finch.led(0, 0, 100) finch.close
#Finch Maze Program #authors: Simon, Juhi, Andrew from finch import Finch from time import sleep, time finch = Finch() finch.led(255, 0, 0) # Turns light red start = time() #Makes Finch drive through track and then celebrate at the end finch.wheels(.8, .87) sleep(5.5) finch.wheels(0, 1) sleep(.6) finch.led(225, 0, 225) finch.wheels(.8, .83) sleep(2.5) finch.wheels(1, 0) sleep(.35) finch.led(0, 150, 150) finch.wheels(.8, .81) sleep(8) finch.wheels(0, 0) finch.wheels(-1,1) sleep(3) finch.wheels(1, -1) sleep(3) finch.wheels(0,0)
# Finch Racetrack Program # authors: Juhi, Simon, Andrew from finch import Finch from time import sleep, time finch = Finch() finch.led(255, 0, 0) finch.wheels(0.5, 0.57) sleep(2.5)
# Finch Testing Script for initiating evasive maneuvers based on ultrasonic # range finder PROXIMITY data # # There will be 2 main test scripts for sonar based colision avoidance, one for # proximity (how far objects are relative to Finch) # speed (how quickly objects are approaching Finch) import ultrasonicRangeRpi from finch import Finch from time import sleep #Instantiate the Finch Object TestFinch = Finch() #Details about the Finch FinchWidth = 20 #Distance between mid points of two tires TireCircumf = 20.797 #Circumference of Finch Wheels l, ril, rel = ultrasonicRangeRpi.lists() #Starting Speed (0.5 on each wheel) TestFinch.wheels(0.5, 0.5) while True: # Find the distances from each sensor sensor1 = ultrasonicRangeRpi.ultrasound(26, 19, 3) #Left Ultrasound sensor2 = ultrasonicRangeRpi.ultrasound(20, 21, 2) #Rear Ultrasound sensor3 = ultrasonicRangeRpi.ultrasound(23, 24, 1) #Right Ultrasound # Enter a number between 0-1, with 0.1 increments (example: 0.2, 0.5, 0.6, 0.9 etc.)
class MyRobot: # Constructor, the polarity is here cause some robots may have the # polarity wrong (i.e. right wheel is going in wrong direction) # The 'adjust' variables are to adjust for different speeds in the wheels # it tries to make them in sync. def __init__(self, left, right, inAdjustmentMode=False): self.leftWheel = left self.rightWheel = right self.myBot = Finch() # Keep track of the direction you should try on obstacles self.obstacleDirectionToTry = finchConstants.LEFT self.lastScrapedSide = " " # Keep track of when the last time you moved forward, we use that # to identify sensors self.lastTimeIMovedForward = -1 # Use vars below for logging when self.lastPersistedLeftObstacleState = False self.lastPersistedRightObstacleState = False # Obstacle reading goes haywire... we'll count up readings within # an interval and use the overall score to report self.lastObstacleReading = 0.0 self.lastObstacleReadingLeftScores = [0, 0, 0, 0, 0] self.lastObstacleReadingRightScores = [0, 0, 0, 0, 0] self.scorePosition = 0 self.obstacleNumberOfScores = len(self.lastObstacleReadingLeftScores) self.obstacleState = { "left": False, "leftStateTime": 0.0, "leftElapsedTime": 0.0, "right": False, "rightStateTime": 0.0, "rightElapsedTime": 0.0 } # If true then wheel speed will be adjusted by the constants self.inWheelAdjustmentMode = inAdjustmentMode self.lasttime = time.time() self.update(self.inWheelAdjustmentMode) # Reset the state of the sensors def resetState(self): self.obstacleState["left"] = False self.obstacleState["leftStateTime"] = 0.0 self.obstacleState["leftElapsedTime"] = 0.0 self.obstacleState["right"] = False self.obstacleState["rightStateTime"] = 0.0 self.obstacleState["rightElapsedTime"] = 0.0 self.lastPersistedLeftObstacleState = False self.lastPersistedRightObstacleState = False self.lastObstacleReading = 0.0 self.lastObstacleReadingLeftScores = [0, 0, 0, 0, 0] self.lastObstacleReadingRightScores = [0, 0, 0, 0, 0] self.scorePosition = 0 # This is common routine to update the dictionary 'state' items associated # with the sensors... we need this because we need the state to persist for # a given amount of time before we think of it as 'real' (the bot sensors are flakey) # NOTE: The state will only be updated when wheels are moving, or you pass in the # forceUpdate indicator def updateMyState(self, forceUpdate=False): if self.leftWheel != 0.0 or self.rightWheel != 0.0 or forceUpdate: stateTime = time.time() leftObst, rightObst = self.myBot.obstacle() # Because obstacle readings are erradic I take last 5 readings, and report that # value if sum of array is > 2 then report True else report false if leftObst == True: leftIntValue = 1 else: leftIntValue = 0 if rightObst == True: rightIntValue = 1 else: rightIntValue = 0 indexPosition = self.scorePosition % 5 self.lastObstacleReadingLeftScores[indexPosition] = leftIntValue self.lastObstacleReadingRightScores[indexPosition] = rightIntValue self.scorePosition = indexPosition + 1 lastReadingElapsed = round(stateTime - self.lastObstacleReading, 3) finchClassLogger.debug( "finchClass-updateMyState, lastReadingElapsed: {0}, leftObst: {1} rightObst{2}" .format(lastReadingElapsed, leftObst, rightObst)) # If reading is less than intervals ignore it if lastReadingElapsed < OBSTACLE_READING_DELAY: return self.lastObstacleReading = stateTime # Calculate the value for each of the obstacle sensors leftIntValue = 0 rightIntValue = 0 indexPosition = 0 while indexPosition < self.obstacleNumberOfScores: leftIntValue += self.lastObstacleReadingLeftScores[ indexPosition] rightIntValue += self.lastObstacleReadingRightScores[ indexPosition] indexPosition += 1 if leftIntValue > 2: leftObstacleReading = True else: leftObstacleReading = False if rightIntValue > 2: rightObstacleReading = True else: rightObstacleReading = False finchClassLogger.debug( "finchClass-updateMyState, leftObstacleReading: {0} rightObstacleReading: {1}" .format(leftObstacleReading, rightObstacleReading)) # State changed or time hasn't been set if self.obstacleState[ "left"] != leftObstacleReading or self.obstacleState[ "leftStateTime"] == 0.0: finchClassLogger.info( "finchClass-updateMyState, STATE Changed, Left was:{0} is:{1}" .format(str(self.obstacleState["left"]), str(leftObstacleReading))) self.obstacleState["left"] = leftObstacleReading self.obstacleState["leftStateTime"] = stateTime self.obstacleState["leftElapsedTime"] = 0.0 else: # Calculate the elapsed time in this state self.obstacleState["leftElapsedTime"] = round( stateTime - self.obstacleState["leftStateTime"], 4) # Same as above but check the right obstacle sensor if self.obstacleState[ "right"] != rightObstacleReading or self.obstacleState[ "rightStateTime"] == 0.0: finchClassLogger.info( "finchClass-updateMyState, STATE Changed, Right was:{0} is:{1}" .format(str(self.obstacleState["right"]), str(rightObstacleReading))) self.obstacleState["right"] = rightObstacleReading self.obstacleState["rightStateTime"] = stateTime self.obstacleState["rightElapsedTime"] = 0.0 else: self.obstacleState["rightElapsedTime"] = round( stateTime - self.obstacleState["rightStateTime"], 4) # Helper to return indicator if an obstacle exists, we did this because we need the obstacle to # persist for an amount of time (thresholdInSecs) before we say it's on # Caller can specify which sensor to check (LEFT/RIGHT, if they don't then it'll return True if # either sensor reports an obstacle) def hasObstacle(self, whichOne, thresholdInSecs=OBSTACLE_PERSIST_TIME_REQUIRED): # Commented out logger... too many messages here, changed 'updateMyState' to report when state changes # finchClassLogger.debug("finchClass-hasObstacle, obstacleState:{0}".format(str(self.obstacleState))) leftObst = False if self.obstacleState["leftElapsedTime"] > thresholdInSecs: leftObst = self.obstacleState["left"] if leftObst != self.lastPersistedLeftObstacleState: finchClassLogger.info( "finchClass-hasObstacle, PERSISTED Left Obstacle State Change old/new: {0}/{1}" .format(self.lastPersistedLeftObstacleState, leftObst)) self.lastPersistedLeftObstacleState = leftObst rightObst = False if self.obstacleState["rightElapsedTime"] > thresholdInSecs: rightObst = self.obstacleState["right"] if leftObst != self.lastPersistedLeftObstacleState: finchClassLogger.info( "finchClass-hasObstacle, PERSISTED Right Obstacle State Change old/new: {0}/{1}" .format(self.lastPersistedRightObstacleState, rightObst)) self.lastPersistedRightObstacleState = rightObst # finchClassLogger.debug("finchClass-hasObstacle, leftObst:{0} rightObst{1}".format(leftObst,rightObst)) if whichOne == finchConstants.LEFT: return leftObst elif whichOne == finchConstants.RIGHT: return rightObst elif leftObst == True or rightObst == True: return True else: return False # Helper function, it returns the wheel speed taking into account what the # wheel adjustment should be, and it's polarity. def wheelHelper(self, whichWheel, logModeOnly=False): # For logging we don't want to show the polarity adjustment... could be # confusing to people analyzing wheel motion :) if logModeOnly == False: rtPol = finchConstants.RIGHTPOLARITY ltPol = finchConstants.LEFTPOLARITY else: rtPol = 1.0 ltPol = 1.0 if whichWheel == "R": if self.inWheelAdjustmentMode: return (self.rightWheel + finchConstants.RIGHTWHEELADJUSTMENT) * rtPol else: return self.rightWheel * rtPol else: if self.inWheelAdjustmentMode: return (self.leftWheel + finchConstants.LEFTWHEELADJUSTMENT) * ltPol else: return self.leftWheel * ltPol # Set the wheel speed (to move, unless both are zero) def update(self, useAdjustment): self.inWheelAdjustmentMode = useAdjustment finchClassLogger.debug( "finchClass-update, left: {0:.2f} right: {1:.2f}".format( self.wheelHelper("L"), self.wheelHelper("R"))) if (self.leftWheel != 0.0 or self.rightWheel != 0.0): # Setting wheel speed, reset the sensors self.resetState() self.myBot.wheels(self.wheelHelper("L"), self.wheelHelper("R")) else: self.myBot.wheels(0.0, 0.0) # Stop moving def stop(self): self.leftWheel = 0.0 self.rightWheel = 0.0 self.update(False) # Turn left, we do this by either increasing the speed of the right wheel # or decreasing the left wheel speed if we're already at max speed def left(self): if self.rightWheel >= finchConstants.RIGHTMAXSPEED: self.leftWheel -= finchConstants.SPEEDINCREMENT else: self.rightWheel += finchConstants.SPEEDINCREMENT self.update(self.inWheelAdjustmentMode) # Turn left for the desired degrees def leftTurn(self, degrees2Turn): self.turnTime = degrees2Turn / 360.0 self.leftWheel = finchConstants.LEFTROTATIONSPEED * -1 self.rightWheel = finchConstants.LEFTROTATIONSPEED self.update(False) time.sleep(finchConstants.LEFTROTATIONTIME * self.turnTime) self.leftWheel = 0 self.rightWheel = 0 self.update(False) # Turn right, basically increase the speed of the left wheel # or decreasing right wheel if left wheel already at max speed def right(self): if self.leftWheel >= finchConstants.LEFTMAXSPEED: self.rightWheel -= finchConstants.SPEEDINCREMENT else: self.leftWheel += finchConstants.SPEEDINCREMENT self.update(self.inWheelAdjustmentMode) # Turn right the specified number of degrees def rightTurn(self, degrees2Turn): self.turnTime = degrees2Turn / 360.0 self.leftWheel = finchConstants.RIGHTROTATIONSPEED self.rightWheel = finchConstants.RIGHTROTATIONSPEED * -1 self.update(False) time.sleep(finchConstants.RIGHTROTATIONTIME * self.turnTime) self.leftWheel = 0 self.rightWheel = 0 self.update(False) # Get the elapsed time def getElapsedTime(self): return round(time.time() - self.lasttime, 4) # Reset the elapsed timer def resetTimer(self): self.lasttime = time.time() # Run... set wheels to max speed def run(self): self.leftWheel = finchConstants.LEFTMAXSPEED self.rightWheel = finchConstants.RIGHTMAXSPEED self.update(self.inWheelAdjustmentMode) # Go faster, we determine the speed increment and increase both wheels by that amount def faster(self): increment = min(finchConstants.SPEEDINCREMENT, finchConstants.LEFTMAXSPEED - self.leftWheel, finchConstants.RIGHTMAXSPEED - self.rightWheel) self.leftWheel += increment self.rightWheel += increment self.update(self.inWheelAdjustmentMode) # Set wheels to be at certain speed def setWheels(self, lftWheel, rtWheel, adJustMode): self.leftWheel = lftWheel self.rightWheel = rtWheel self.inWheelAdjustmentMode = adJustMode self.update(self.inWheelAdjustmentMode) # Shutdown the robot def shutDown(self): self.myBot.close() # Return True if robot can move, false if there is some type of # obstacle def canMove(self, ignoreObstacles): # Add logic for other sensors # If we're going in reverse then don't check sensors if (self.leftWheel <= 0.0 and self.rightWheel <= 0.0) or ignoreObstacles: # print("canMove, ignoring obstacles") return True else: self.updateMyState() rtnValue = (self.hasObstacle("BOTH") == False) # print("canMove returns {0}".format(rtnValue)) return rtnValue # Routine when robot feels a scrap (obstacle on one side of it), pass in the side def getOutOfScrape(self, sideOfScrape): # Motion is rotate SCRAPEANGLE (if left +, right -) # Backup SCRAPEBACKUPDISTANCE # Rotate back to original angle if sideOfScrape == finchConstants.LEFT: return botUtils.calculateScrapeMovement( finchConstants.SCRAPEANGLE, finchConstants.SCRAPEBACKUPDISTANCE) else: return botUtils.calculateScrapeMovement( -finchConstants.SCRAPEANGLE, finchConstants.SCRAPEBACKUPDISTANCE) # Get out of obstacle is similar to the get out of scrap but we use a 45 degree angle and the distance to # move puts us back 1/2 of the robot's width away def getOutOfObstacle(self, directionToMove): # We want to try a position to the left or right that is 1/2 our width away # Calculate the distance we need to backup first, it's 1/2 width divided by sin(45) distanceToBackup = round( (finchConstants.TOTALWIDTH) / botUtils.degreesSin(45), 2) finchClassLogger.info( "finchClass-getOutOfObstacle, directionToMove: {0} distanceToBackup: {1}" .format(directionToMove, str(distanceToBackup))) if directionToMove == finchConstants.LEFT: # Want angle of -45 to turn right then backup return botUtils.calculateScrapeMovement(-45.0, distanceToBackup) else: return botUtils.calculateScrapeMovement(45, distanceToBackup) # Return the direction to try when you hit an obstacle, put logic in here def getObstacleDirectionToTry(self): return self.obstacleDirectionToTry def flipObstacleDirectionToTry(self): if self.obstacleDirectionToTry == finchConstants.LEFT: self.obstacleDirectionToTry = finchConstants.RIGHT else: self.obstacleDirectionToTry = finchConstants.LEFT finchClassLogger.info( "finchClass-flipObstacleDirectionToTry, new direction: {0}".format( self.obstacleDirectionToTry)) # Return the side that was last scraped, since we calculate the direction to move before # this, it's opposite out current direction... down the road see if you can derive it on # accelarator def getLastScrapeSide(self): if self.obstacleDirectionToTry == finchConstants.LEFT: return finchConstants.RIGHT else: return finchConstants.LEFT #return self.lastScrapedSide def isObstacle(self, robotPosition, robotRegionOfTravel): # Return True if you hit an obstacle (both sensors are true), if you # only have one sensor then count that as a scrape and return false # leftObst, rightObst = self.myBot.obstacle() leftObst = self.hasObstacle(finchConstants.LEFT) rightObst = self.hasObstacle(finchConstants.RIGHT) if leftObst == True and rightObst == True: return True elif leftObst == True or rightObst == True: # The robot sensor don't always report true even # when there's an obstacle right in front of it. # If the robot is close to the edge of it's region # of travel then report this as a scrape otherwise # report it as an obstacle if self.isRobotCloseToEdge(robotPosition, robotRegionOfTravel) == True: if leftObst == True: self.lastScrapedSide = finchConstants.LEFT else: self.lastScrapedSide = finchConstants.RIGHT return False else: return True return False # Determines if robot is oriented along the x or y axis (within 10 degree of it) def robotOrientedAlongAxis(self, robotPosition): orientedTowardAxis = " " if (robotPosition[botUtils.POS_OF_ANGLE] < 10 or robotPosition[botUtils.POS_OF_ANGLE] > 350): orientedTowardAxis = "X+" elif (robotPosition[botUtils.POS_OF_ANGLE] > 170 and robotPosition[botUtils.POS_OF_ANGLE] < 190): orientedTowardAxis = "X-" elif (robotPosition[botUtils.POS_OF_ANGLE] > 80 and robotPosition[botUtils.POS_OF_ANGLE] < 100): orientedTowardAxis = "Y+" elif (robotPosition[botUtils.POS_OF_ANGLE] > 260 and robotPosition[botUtils.POS_OF_ANGLE] < 280): orientedTowardAxis = "Y-" return orientedTowardAxis # Determine if robot is close to a particular regions edge def getRobotClosestEdges(self, robotPosition, regionOfTravel, threshold=THRESHOLDTOSIDE): # Calculate the distance from coordinates closeEdges = [] distanceToLeftX = robotPosition[botUtils.POS_OF_X] - regionOfTravel[0] distanceToRightX = regionOfTravel[2] - robotPosition[botUtils.POS_OF_X] distanceFromBottomY = robotPosition[ botUtils.POS_OF_Y] - regionOfTravel[1] distanceFromTopY = regionOfTravel[3] - robotPosition[botUtils.POS_OF_Y] tempString = "finchClass.py, getRobotClosesEdges, robotPosition: {0} regionOfTravel: {1} threshold: {2}" finchClassLogger.debug( tempString.format(str(robotPosition), str(regionOfTravel), threshold)) tempString = " leftXDist: {0} rightXDist: {1}, lowerYDist: {2} upperYDist: {3}" finchClassLogger.debug( tempString.format(distanceToLeftX, distanceToRightX, distanceFromBottomY, distanceFromTopY)) if (distanceToLeftX <= threshold): closeEdges.append("LX") elif (distanceToRightX <= threshold): closeEdges.append("UX") if (distanceFromBottomY <= threshold): closeEdges.append("LY") elif (distanceFromTopY <= threshold): closeEdges.append("UY") return closeEdges def getFinchReference(self): return self.myBot # Revisit this, there's definitely better way to do this... look in to matrix trasnformations def checkAndSetObstacleDirectionToTry(self, robotPosition, regionOfTravel, threshold=THRESHOLDTOSIDE): # Get closest edges finchClassLogger.debug( "finchClass.py, checkAndSetObstacleDirectionToTry, start") myCloseEdges = self.getRobotClosestEdges(robotPosition, regionOfTravel, threshold) newDirection = " " if len(myCloseEdges) > 0: finchClassLogger.debug( "finchClass.py, checkAndSetObstacleDirectionToTry, values below" ) for anEdge in myCloseEdges: finchClassLogger.debug(" {0}".format(str(anEdge))) # We are close to an edge, get the robot orientation to figure out the edges that # are used to set new direction... when in x direction we look at y values, when # pointing in y direction we look at x values robotOrientation = self.robotOrientedAlongAxis(robotPosition) if robotOrientation == "X+": if "UY" in myCloseEdges: newDirection = finchConstants.RIGHT elif "LY" in myCloseEdges: newDirection = finchConstants.LEFT elif robotOrientation == "X-": if "UY" in myCloseEdges: newDirection = finchConstants.LEFT elif "LY" in myCloseEdges: newDirection = finchConstants.RIGHT elif robotOrientation == "Y+": if "UX" in myCloseEdges: newDirection = finchConstants.LEFT elif "LX" in myCloseEdges: newDirection = finchConstants.RIGHT elif robotOrientation == "Y-": if "UX" in myCloseEdges: newDirection = finchConstants.RIGHT elif "LX" in myCloseEdges: newDirection = finchConstants.LEFT finchClassLogger.debug( "finchClass.py, checkAndSetObstacleDirectionToTry, oldDirection: {0} newDirection: {1}" .format(self.obstacleDirectionToTry, newDirection)) if newDirection != self.obstacleDirectionToTry: self.flipObstacleDirectionToTry() finchClassLogger.debug( "finchClass.py, checkAndSetObstacleDirectionToTry, start") # Helper just returns true or false stating that we're close to edge. def isRobotCloseToEdge(self, robotPosition, regionOfTravel, threshold=THRESHOLDTOSIDE): edgesCloseTo = self.getRobotClosestEdges(robotPosition, regionOfTravel, threshold) if len(edgesCloseTo) > 0: return True else: return False # Set the finches nose color :) def setLedColor(self, theColor): if theColor == finchConstants.RED: self.myBot.led(255, 0, 0) elif theColor == finchConstants.GREEN: self.myBot.led(0, 255, 0) elif theColor == finchConstants.BLUE: self.myBot.led(0, 0, 255) # Return status of all robot attributes def status(self): # This returns elapsed time since clock was set and a tuple with the attributes, the wheels, obstacle and lights # are tuples (so it's a tuple of tuples (except for temp)) leftObst, rightObst = self.myBot.obstacle() currStat = (self.getElapsedTime(), (self.wheelHelper("L", True), self.wheelHelper("R", True)), self.myBot.temperature(), (self.myBot.light()), (leftObst, rightObst), (self.myBot.acceleration())) return currStat
# testfinchfunctions, an example program for the Finch # Tests all parts of the Finch: prints all sensor values, changes the led # moves the wheels and beeps the buzzer. from time import sleep from finch import Finch finch = Finch() print('Temperature %5.2f' % finch.temperature()) print() finch.wheels(1.0, -1.0) sleep(0.5) finch.wheels(0.0, 0.0) for count in range(5): finch.led(0, 50*count, 0) x, y, z, tap, shake = finch.acceleration() print ('Acceleration %5.3f, %5.3f %5.3f %s %s' % (x, y, z, tap, shake)) left_light, right_light = finch.light() print ('Lights %5.3f, %5.3f' % (left_light, right_light)) left_obstacle, right_obstacle = finch.obstacle() print('Obstacles %s, %s' % (left_obstacle, right_obstacle)) print() finch.buzzer(0.8, 100*count) sleep(1) finch.led('#FF0000') finch.buzzer(5, 440)
from finch import Finch from time import sleep finch = Finch() print (finch.light()) while (1) : light = finch.light() average = (light[0] + light[1]) / 2 deviation = abs(average - 0.55) #formula using deviation so finch could react appropriately to light #3 is for a stronger reaction because 1 standard deviation not enough finch.led(255 * 3 * deviation, 255 * 3 * (1 - deviation), 0) print (average)
# A simple Finch dance in Python from finch import Finch from time import sleep print("Finch's First Python program.") # Instantiate the Finch object snakyFinch = Finch() # Do a six step dance snakyFinch.led(255,0,0) snakyFinch.wheels(1,1) sleep(1) snakyFinch.led(0,255,0) snakyFinch.wheels(0,1) sleep(1) snakyFinch.led(0,0,255) snakyFinch.wheels(1,0) sleep(1) snakyFinch.led(255,0,255) snakyFinch.wheels(-1,-1) sleep(0.5) snakyFinch.led(0,255,255) snakyFinch.wheels(0.2,-1) sleep(1)
# A simple program that changes the Finch LED based on orientation. from finch import Finch from random import randint # Instantiate the Finch object and connect to Finch tweety = Finch() left, right = tweety.obstacle() # Do the following while no obstacles are detected by Finch while not left and not right: # Get the accelerations x, y, z, tap, shake = tweety.acceleration() # Print the acceleration data print("X is %.2f gees, Y is %.2f gees, Z is %.2f gees, tap is %r shake is %r" % (x, y, z, tap, shake)); # Use the acceleration data to set the LED: # beak up if x < -0.7 and y > -0.3 and y < 0.3 and z > -0.3 and z < 0.3: tweety.led(255,0,0); # beak down elif x > 0.7 and y > -0.3 and y < 0.3 and z > -0.3 and z < 0.3: tweety.led(0,255,0); # level elif x > -0.5 and x < 0.5 and y > -0.5 and y < 0.5 and z > 0.7: tweety.led(0,0,255); # upside down elif x > -0.5 and x < 0.5 and y > -0.5 and y < 0.5 and z < -0.7: tweety.led(0,255,255);
# A simple program that randomly changes the LED when the Finch is tapped or shaken # Try it by setting the Finch on a table and tapping the top from finch import Finch from random import randint # Instantiate the Finch object and connect to Finch tweety = Finch() left, right = tweety.obstacle() # Do the following while no obstacles are detected by Finch while not left and not right: # Get the accelerations x, y, z, tap, shake = tweety.acceleration() # Print the acceleration data print("X is %.2f gees, Y is %.2f gees, Z is %.2f gees, tap is %r shake is %r" % (x, y, z, tap, shake)); # If a tap or shake has been detected recently, set the LED to a random color if tap or shake: tweety.led(randint(0,255), randint(0, 255), randint(0,255)) # Get obstacles to use to exit loop left, right = tweety.obstacle() tweety.close()
# Lap Swimmer, an example program for the Finch # Tell the Finch how many laps to do, set it down on the ground # Finch goes forward until it sees an obstacle # Then goes back the same distance. It'll then repeat this lap as many times # as the user requested from finch import Finch from time import sleep, time # Main function for the lap swimmer example program finch = Finch() # Initialize the finch finch.led(255, 255, 0) laps = 0 # Get the number of laps Finch will swim: while laps <= 0: laps = int(input('Enter number of laps: ')) if laps < 0: print('Cannot swim a negative number of laps!') elif laps == 0: print('Zero laps? I want to swim!') # Move forward until an obstacle is present and measure the time: start = time() finch.wheels(0.5, 0.5) sleep(0.1)
# A simple program that wanders and avoids obstacles from finch import Finch from time import sleep import notes #Main function for the music player example program""" #Initialize the finch finch = Finch() songList = [ 'E5 C D E C D E F D E F D E F G A GE F C D E G E D C ', 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ' 'E D5 A4 G G5 A4 F5# A4 E D5 A4 G G5 A4 F5# A4 ' 'G D5 A4 G G5 A4 F5# A4 G D5 A4 G G5 A4 F5# A4 ' 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ', 'E5 E E C E G ', 'C E5 G' ] timeList = [0.18, 0.1, 0.1] song = 1 #get which song song = 3 if song >= 1 and song <= 3: print("It's GO time!!!") Finch.led(255, 0, 0) notes.sing(finch, songList[song - 1], timeList[song - 1]) else:
class myFinch: # Class Initializer # Synopsis - # self.left_wheel, is the speed of the left wheel, set to 0 # self.right_wheel, is the speed of the right wheel, set to 0 # self.tweety, is the Finch robot object which will be manipulated through this class # # Description - # Initialize the class members to a specific value def __init__(self): self.tweety = Finch() # Set obstacle sensors self.left_obst, self.right_obst = self.tweety.obstacle() # Setting initial lighting self.myLights = lighting(self.tweety) self.myLights.readValues() # Setting initial acceleration settings self.x, self.y, self.z, self.tap, self.shake = self.tweety.acceleration( ) # Setting initial wheel speed self.left_wheel = 0.0 self.right_wheel = 0.0 self.tweety.wheels(self.left_wheel, self.right_wheel) # [FUNCTION]Name - setWheels ( left, right ) # Synopsis - # def setWheels ( left, right ) : # left, an double value for the left wheel speed # right, an double value for the right wheel speed # # Description - # Accelerates each wheel at different speeds to obtain the new speed. This can be # adjusted by small increments and also gives each wheel independent ending # speeds. # # Return - # (none) def setWheels(self, left, right): self.left_wheel = left self.right_wheel = right self.tweety.wheels(self.left_wheel, self.right_wheel) self.printSpeed() return # setWheels ( left, right ) # # [FUNCTION]Name - def printSpeed ( ) # Synopsis - # def printSpeed ( ): # (no parameters) # Description - # Upon changing speed with setWheels this will print the individual wheel speed # or both to the console. # # Return - # (none) def printSpeed(self): if (self.left_wheel == self.right_wheel): print("Current speed : ", self.left_wheel) return print("Left speed : ", self.left_wheel) print("Right speed : ", self.right_wheel) return # printSpeed ( self ) # def isLight(self): current_left, current_right = self.tweety.light() return current_left, current_right def scurryTowardsLights(self): lspeed = 0.3 rspeed = 0.5 clspeed = 0.1 crspeed = 0.5 onCurve = 0 onMax = 0 maxleft, maxright = self.myLights.getMax() tmpmaxleft = maxleft + .25 tmpmaxright = maxright + .25 if (tmpmaxleft) > .75: tmpmaxleft = .75 if (tmpmaxright) > .75: tmpmaxright = .75 while (True): # Check lights, then obstacles left_light, right_light = self.myLights.lightStatus() self.left_obst, self.right_obst = self.tweety.obstacle() if (self.checkForObstacle()): #switch the speeds tmp = lspeed ctmp = clspeed lspeed = rspeed rspeed = tmp clspeed = crspeed clspeed = ctmp if left_light == 0 and right_light == 0: # Just keep swimming print("Just keep swimming") self.delay(0.3, lspeed, rspeed) onCurve += 1 if onCurve == 10: print("Small curve") self.setWheels(0.0, 0.0) self.delay(3.0, clspeed, crspeed) self.setWheels(lspeed, rspeed) # Natural curve speed (testing) onCurve = 0 elif left_light > 0 or right_light > 0: onCurve = 0 # Find "brightest" # stop ... move towards the light self.setWheels(0.0, 0.0) leftval, rightval = self.myLights.getComparison() if leftval > rightval: # Turn towards our left print("Going left") self.turnLeft() else: print("Going right") # Turn towards our right self.turnRight() if ((leftval + maxleft) > (tmpmaxleft)) and ((rightval + maxright) > tmpmaxright): print("Under bright area!") while (True): self.setWheels(0.0, 0.0) self.delay(0.3, 0.5, 0.5) self.setWheels(0.0, 0.0) left, right = self.isLight() print(left, " ", right) print(tmpmaxleft, " ", tmpmaxright) if (left > tmpmaxleft) or (right > tmpmaxright): tmpmaxleft = left tmpmaxright = right sleep(0.5) else: self.delay(0.3, -0.5, -0.5) self.setWheels(0.0, 0.0) break os._exit(0) elif right_light < 0 or right_light < 0: onCurve = 0 print("got darker") def checkForObstacle(self): if self.left_obst == True and self.right_obst == True: print("Obstacle straight ahead") self.setWheels(-(self.left_wheel), -(self.right_wheel)) sleep(0.5) self.setWheels(0.0, 0.0) sleep(0.1) self.setWheels(0.0, 0.5) sleep(0.5) return True elif self.right_obst == True: print("Obstacle on right") self.setWheels(-(self.left_wheel), -(self.right_wheel)) sleep(0.5) self.setWheels(0.0, 0.0) sleep(0.1) self.setWheels(0.5, 0.0) sleep(0.5) return True elif self.left_obst == True: print("Obstacle on left") self.setWheels(-(self.left_wheel), -(self.right_wheel)) sleep(0.5) self.setWheels(0.0, 0.0) sleep(0.1) self.setWheels(0.5, 0.0) sleep(0.5) return True else: print("No obstacle") return False return False def turnRight(self): self.setWheels(.5, .25) def turnLeft(self): self.setWheels(0.25, .5) def straight(self): self.setWheels(0.4, 0.4) def charging(self): self.tweety.led("#00FF00") self.tweety.buzzer(1.0, 800) def discharging(self): self.tweety.led("#FF0000") def delay(self, time, lspeed, rspeed): timer = 0 while (timer < time): self.setWheels(lspeed, rspeed) if (self.checkForObstacle() == True): tmp = lspeed lspeed = rspeed rspeed = tmp self.setWheels(lspeed, rspeed) continue else: timer = timer + 0.1 sleep(0.1) continue
if (finch != "y"): while (see == True): see = pass_gas(True) WASD("shutdown script") else: # A simple program that wanders and avoids obstacles from finch import Finch from time import sleep import notes #Main function for the music player example program""" #Initialize the finch finch = Finch() songList = [ 'E5 C D E C D E F D E F D E F G A GE F C D E G E D C ', 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ' 'E D5 A4 G G5 A4 F5# A4 E D5 A4 G G5 A4 F5# A4 ' 'G D5 A4 G G5 A4 F5# A4 G D5 A4 G G5 A4 F5# A4 ' 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ', 'E5 E E C E G ', 'C E5 G' ] timeList = [0.18, 0.1, 0.1, 0.1, 0.1] song = 1 #get which song song = 3
def mathr(): if (True): WASD("r") WASD("ht") # to = input("if your equation is in ax**2 + bx +c, type 1. If it is in d(x + a)**2 + b = c, type 2. If you want to use the normal calculator, do not type in anything.") a = input() ot = input() b = input() ot = ot.lower() if (ot == "1"): a = (input("What is the A value?")) b = ((input("What is the B value?"))) c = (input("What is the C Value?")) if (type(a) or type(b) or type(c) != float) and (len(a) and len(b) > 0): a = float(a) b = float(b) c = float(c) wer = 0 WASD("st") while (wer < 10): WASD("a") wer = (wer + 1) WASD("ht") dis = str(b**2 - (4 * a * c)) print("The Discriminent is " + dis + ".") v = ((0 - b) / (2 * a)) d = v ve = ((a * (v**2)) + (b * d) + c) print("The axis of symmetry is:") print("x = ") print(v) print("The vertex is ") print(v) print(",") print(ve) anso = (0 - b) ansoer = (b**2 - (4 * a * c)) if (ansoer < 0): print("The answer is no solution") else: anso = (anso + sqrt(ansoer)) anso = (anso / (2 * a)) anst = (0 - b) anst = (anst - sqrt(b**2 - 4 * a * c)) anst = (anst / (2 * a)) print("The answers are:") print(anso) print("and") print(anst) anso = (0 - b) ansoer = (b**2 - (4 * a * c)) ansot = (0 - anso) ansto = (0 - anst) # print ("The factored form is:") # print ("(x + ") # print (ansot) # print (")") # print ("(x + ") # print(ansto) # print (")") qrs = input("do you want to plug in a point?") if (qrs == "y"): v = input("What x value?") WASD("ht") v = float(v) ve = ((a * (v**2)) + (b * v) + c) print(ve) ve = (v**2) ve = (ve * a) xe = (b * v) ve = (ve + xe) ve = (ve + c) print(ve) WASD("st") WASD("r") turtle.setpos(v, ve) WASD("c") vor = input("another?") if (vor == "y"): v = input("What x value?") v = float(v) ve = ((a * (v**2)) + (b * v) + c) print(ve) WASD("st") turtle.pendown() turtle.setpos(v, ve) WASD("ht") input() else: print("OK") else: print("OK") else: s = 1 elif (ot == "How are you?"): print("I am good.") elif (ot == "lines n arrows"): WASD("st") wer = 0 while (wer < 5): WASD("a") wer = (wer + 1) WASD("r") lines_n_arrows() WASD("ht") WASD("r") elif (ot == "ps"): print(perfect_square(a)) elif (ot == "h. asymptote"): n = input("What is the degree of the numerator?") m = input("What is the degree of the denomonator?") if (n < m): print("The horizontal asymptote is at the x-axis.") elif (n == m): a = input("What is a?") b = input("What is b?") print("The horizontal assymtote is") print(a / b) else: print("There is no horizontal assymtote") elif (ot == "trivia"): fo = input("Who is the first compeditor?") ft = input("Who is the second compeditor?") trivia(fo, ft) WASD("r") WASD("ht") elif (ot == "you are a"): print("takes one to know one " + person + ".") elif (ot == "sq"): a = float(a) print(a**2) elif (ot == "dinner"): dinner() elif (ot == "sleep"): WASD("sleep") elif (ot == "2"): a = input("What is the A value?") b = (input("What is the B value?")) c = (input("What is the C Value?")) d = input("What is the d value?") a = int(a) b = int(b) c = int(c) c = (c - b) c = sqrt(c) c = (c / d) anso = (0 - a) anso = (anso + c) anst = (0 - c) anst = (anst - a) print("The answers are:") print(anso) print("and") print(anst) print("and") print(anst) elif (ot == "s.i. linear"): m = float(input("What is m?")) b = float(input("Whar is b?")) again = input("Wanna plug in a point") if (again == "y"): # y = mx + b x = float(input("What to plug in for x?")) y = (m * x) y = (y + b) WASD("st") WASD("r") turtle.setpos(x, y) WASD("c") print(y) again = input("another?") if (again == "y"): x = float(input("What to plug in for x?")) y = (m * x) y = (y + b) print(y) WASD("st") turtle.pendown() turtle.setpos(x, y) again = input("another?") if (again == "y"): x = float(input("What to plug in for x?")) y = (m * x) y = (y + b) print(y) WASD("st") turtle.pendown() turtle.setpos(x, y) again = input("another?") if (again == "y"): x = float(input("What to plug in for x?")) y = (m * x) y = (y + b) print(y) WASD("st") turtle.pendown() turtle.setpos(x, y) WASD("ht") input() elif (ot == "midpoint"): xo = int(input("What is x1?")) yo = int(input("What is y1?")) xt = int(input("What is x2?")) yt = int(input("What is y2?")) anso = (xo + xt) anso = (anso / 2) anst = float(yo + yt) anst = (anst / 2) print("The answer is ") print(anso) print(",") print(anst) elif (ot == "print"): prin = input() pri = input() pr = input() prin = float(prin) pri = float(pri) pr = float(pr) print(prin + pri + pr) elif (ot == "what to do"): doorator() elif (ot == "type"): inp = input() print(type(inp)) elif (ot == "pyg"): pyg() elif (ot == "sqrtfac"): ratfac2(a) elif (ot == "ratfac"): ratfac2(a) elif (ot == "isprime"): if (len(a) > 0): n = a n = int(n) b = (n + 1) for n in range(n, b): for x in range(2, n): n = int(n) if n % x == 0: x = int(x) y = (n // x) n = str(n) x = str(x) y = str(y) print(n + ' equals ' + x + '*' + y) break else: # loop fell through without finding a factor print(n, 'is a prime number') elif (ot == "lines n arrows"): lines_n_arrows() elif (ot == "document"): documents() elif (ot == "tp"): di = int(input("what is the diagonal?")) point = int(input("What is the pointy edge?")) bt = int( input( "What is the leg of the triangle adjasent to the pointy edge?" )) st = int(input("What is the other leg of the triangle?")) ans = (st * bt) answ = (di * point) answe = (bt * point) answer = (st * point) anso = (ans + answ + answe + answer) print(anso) elif (ot == ".1"): a = (input("What is the A value?")) b = ((input("What is the B value?"))) c = (input("What is the C Value?")) if (type(a) or type(b) or type(c) != float) and (len(a) and len(b) > 0): a = float(a) b = float(b) c = float(c) dis = str(b**2 - (4 * a * c)) print("The Discriminent is " + dis + ".") v = ((0 - b) / (2 * a)) d = v ve = ((a * (v**2)) + (b * d) + c) print("The axis of symmetry is:") print("x = ") print(v) print("The vertex is ") print(v) print(",") print(ve) anso = (0 - b) ansoer = (b**2 - (4 * a * c)) if (ansoer < 0): print("The answer is no solution") else: anso = (anso + sqrt(ansoer)) anso = (anso / (2 * a)) anst = (0 - b) anst = (anst - sqrt(b**2 - 4 * a * c)) anst = (anst / (2 * a)) print("The answers are:") print(anso) print("and") print(anst) anso = (0 - b) ansoer = (b**2 - (4 * a * c)) ansot = (0 - anso) ansto = (0 - anst) # print ("The factored form is:") # print ("(x + ") # print (ansot) # print (")") # print ("(x + ") # print(ansto) # print (")") qrs = input("do you want to plug in a point?") if (qrs == "y"): v = input("What x value?") v = float(v) ve = ((a * (v**2)) + (b * v) + c) print(ve) ve = (v**2) ve = (ve * a) xe = (b * v) ve = (ve + xe) ve = (ve + c) print(ve) vor = input("another?") if (vor == "y"): v = input("What x value?") v = float(v) ve = ((a * (v**2)) + (b * v) + c) print(ve) else: print("OK") else: print("OK") else: s = 1 elif (ot == "+"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = int(a) b = int(b) ans = (a + b) print(ans) else: print("invalid #") elif (ot == "thats wrong"): print("No way! I am always right!") elif (ot == "i like pi"): print("Really? so do I!") elif (ot == "no way!"): print("yes way!") elif (ot == "sin"): a = float(a) print(sin(a)) elif (ot == "tan"): a = float(a) print(tan(a)) elif (ot == "cos"): a = float(a) print(cos(a)) elif (ot == "hi"): name = print("Hello, " + person + ", i'm Alcal.") feeling = input("How are you?") feeling = feeling.lower() if (feeling == "good"): print("Happy to hear that, " + person + ".") elif (feeling == "not so good"): print("I hope you feel better soon.") else: print("I don't understand...") elif (ot == ".+"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = float(a) b = float(b) print(a + b) elif (ot == "*"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) if (len(a) and len(b) > 0): a = int(a) b = int(b) print(a * b) else: print("invalid #") elif (ot == "turtle"): q = 1 WASD("st") turtle.forward(1) while (q == 1): WASD(input()) q = WASD(input()) WASD("r") WASD("ht") #elif (ot == "*"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) # a = float(a) # b = float(b) # print (a * b) elif (ot == "shut down"): return (False) elif (ot == "/"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = int(a) b = int(b) print(a / b) elif (ot == "./"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) a = float(a) b = float(b) print(a / b) elif (ot == "factorial"): # a = (input("What factorial?")) if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = int(a) print(factorial(a)) else: print("invalid #") elif (ot == "porportion"): print( "This is the porportion solver #1. Use it only if the second numerator is the only x. (The equasion must look like this: #/# = x/#)" ) num = input("what is the first numerator?") deno = input("What is the first denomonator?") dent = input("What is the 2nd denomonator?") numb = (int(num) * int(dent)) ans = (int(numb) / int(deno)) print("x = " + str(ans)) elif (ot == "-"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = int(a) b = int(b) print(a - b) elif (ot == ".-"): # a = (input("What is the 1st #?")) # b = (input("What is the second #?")) a = float(a) b = float(b) print(a - b) elif (ot == "sqrt"): # a = input("What do you want to square root?") if (type(a) != "float"): a = int(a) print(sqrt(a)) else: print("invalad #") elif (ot == ".sqrt"): # a = input("What do you want to square root?") a = float(a) print(sqrt(a)) elif (ot == "finch"): if (finch == True): q = 1 while q == 1 and zAccel > -0.7: Finch() elif (ot == "**"): # a = input("What is the base?") # b = input("What is the exponent?") if (type(a) or type(b) != float) and (len(a) and len(b) > 0): a = int(a) b = int(b) print(a**b) elif (ot == "who am i?"): print("Why, you are " + person + " of course!") elif (ot == ".**"): # a = input("What is the base?") # b = input("What is the exponent?") a = float(a) b = float(b) print(a**b) elif (ot == "pledge"): print("I plege alligence") print("to the flag") print("of the United States of America") print("and to the republic") print("of which it stands") print("one nation") print("Under God") print("Indivisible") print("With liberty and justice for all.") elif (ot == "document1"): print("SubotomicOffice Character") # print ("Loading...") doc1 = input() print("document1 is " + doc1) ques = input("Woud you like to print that?") if (ques == "y"): print(doc1) else: print("OK") elif (ot == "document2"): print("SubotomicOffice Character") # print ("Loading...") doc2 = input() print("document2 is " + doc2) ques = input("Woud you like to print that?") if (ques == "y"): print(doc1) else: print("OK") elif (ot == "document3"): print("SubotomicOffice Character") # print ("Loading...") doc3 = input() print("document3 is " + doc3) ques = input("Woud you like to print that?") if (ques == "y"): print(doc3) else: print("OK") elif (ot == "dir math"): print(dir(math)) elif (ot == "dir turtle"): print(dir(turtle)) elif (ot == "distance"): xo = int(input("What is x1?")) yo = int(input("What is y1?")) xt = int(input("What is x2?")) yt = int(input("What is y2?")) ans = (xt - xo) ans = (ans**2) anst = (yt - yo) anst = (anst**2) anso = (ans + anst) ansto = (sqrt(anso)) print(ansto) print("or") anso = str(anso) print("the suare root of " + anso) # elif (ot == "sin"): # print sin(a) elif (ot == "slope"): xo = float(input("What is x1?")) yo = float(input("What is y1?")) xt = float(input("What is x2?")) yt = float(input("What is y2?")) slope = (yt - yo) slop = (xt - xo) ans = (slope / slop) print(ans) else: print("invalid answer for the type of equasion.") return (True)
class myFinch: # Class Initializer # Synopsis - # self.left_wheel, is the speed of the left wheel, set to 0 # self.right_wheel, is the speed of the right wheel, set to 0 # self.tweety, is the Finch robot object which will be manipulated through this class def __init__(self): self.tweety = Finch() self.left_wheel = 0.0 self.right_wheel = 0.0 self.tweety.wheels(self.left_wheel, self.right_wheel) self.left_obst, self.right_obst = self.tweety.obstacle() # [FUNCTION]Name - accelerate( speed ) # Synopsis - # def accelerate ( speed ) : # speed, an integer value between (-1) and 1 to accelerate the finch # def changeSpeed ( self, new_speed ): old_speed = self.left_wheel if new_speed == old_speed: print("Same speed") return # Decelerate if old_speed > new_speed: self.__decelerate(2, new_speed) # Accelerate else: self.__accelerate(2, new_speed) #set wheels as last action in case error in accuracy self.setWheels( new_speed, new_speed ) return # [FUNCTION]Name - changeBoth ( left, right ) # Synopsis - # def changeBoth ( left, right ) : # left, an integer value between (-1) and 1 to accelerate the finch # right, an integer value between (-1) and 1 to accelerate the finch # def changeBoth ( self, left, right ) : if left == right: changeSpeed(left) return elif self.left_wheel != left: if left > self.left_wheel: self.__accelerate( 0, left ) else: self.__decelerate( 0, left ) elif self.right_wheel != right: if right > self.right_wheel: self.__accelerate( 1, right ) else: self.__decelerate( 1, right ) else: wheel = 2 return 0 # [PRIV. FUNCTION]Name - __accelerate ( self, wheel, new_speed ) # Synopsis - # def __accelerate ( self, wheel, new_speed ) : # wheel, which wheel[0 for left, 1 for right] or both[any other integer] to change speed for # new_speed, a double value to change the speed to between -1 and 1 def __accelerate ( self, wheel, new_speed ): if ( new_speed > 1.0 or new_speed < -1.0): print ("Invalid Speed") return # Change left wheel speed @ wheel == 0 if wheel == 0: old_speed = self.left_wheel while old_speed < new_speed: self.setWheels ( old_speed, self.right_wheel ) old_speed = old_speed + 0.1 sleep(0.15) self.setWheels (new_speed, self.right_wheel) #Change right wheel speed @ wheel == 1 elif wheel == 1: old_speed = self.right_wheel while old_speed < new_speed: self.setWheels ( self.left_wheel, old_speed ) old_speed = old_speed + 0.1 sleep(0.15) self.setWheels (self.left_wheel, new_speed) # Change speed of both wheels else: old_speed = self.right_wheel while old_speed < new_speed: self.setWheels ( old_speed, old_speed ) old_speed = old_speed + 0.1 sleep(0.15) self.setWheels (new_speed, new_speed) return # [PRIV. FUNCTION]Name - decelerate ( self, wheel, new_speed ) # Synopsis - # def __decelerate ( self, wheel, new_speed ): # wheel, which wheel[0 for left, 1 for right] or both[any other integer] to change speed for # new_speed, a double value to change the speed to between -1 and 1 def __decelerate ( self, wheel, new_speed ): if ( new_speed > 1.0 or new_speed < -1.0): print ("Invalid Speed") return # Change left wheel speed @ wheel == 0 if wheel == 0: old_speed = self.left_wheel while old_speed > new_speed: self.setWheels ( old_speed, self.right_wheel ) old_speed = old_speed - 0.1 sleep(0.15) self.setWheels (new_speed, self.right_wheel) return #Change right wheel speed @ wheel == 1 elif wheel == 1: old_speed = self.right_wheel while old_speed > new_speed: self.setWheels ( self.left_wheel, old_speed ) old_speed = old_speed - 0.1 sleep(0.15) self.setWheels(self.left_wheel, new_speed) return #Change both wheel speed @ wheel == not 1 or 0 else: old_speed = self.right_wheel while old_speed > new_speed: self.setWheels ( old_speed, old_speed ) old_speed = old_speed - 0.1 sleep(0.15) self.setWheels(new_speed, new_speed) return return def setWheels ( self, left, right ): self.left_wheel = left self.right_wheel = right self.tweety.wheels(self.left_wheel, self.right_wheel) self.printSpeed() return def printSpeed ( self ): if (self.left_wheel == self.right_wheel): print ("Current speed : ", self.left_wheel) return print("Left speed : ", self.left_wheel) print("Right speed : ", self.right_wheel) return
from finch import Finch import time import datetime robot = Finch() def temperature_check(): temperature = robot.temperature() print( str(((temperature * 9) / 5) + 32) + " degrees Farenheit at the moment.\nThis program is going to update itself in the next 15 secs" ) print("This is as at " + time.ctime() + "\n\n") time.sleep(15) return temperature_check() print(temperature_check())
def __init__(self): self.tweety = Finch() self.left_wheel = 0.0 self.right_wheel = 0.0 self.tweety.wheels(self.left_wheel, self.right_wheel) self.left_obst, self.right_obst = self.tweety.obstacle()
# Car alarm # The finch sounds an alarm, alternating high pitch sounds and # flashing red abd blue lights, until its nose is turned up from time import sleep from finch import Finch finch = Finch() finch.led("#550000") # set the led to red finch.finch_2_buzzer(3, 880, 60) sleep(1.00) finch.led("#005500") # set the led to blue finch.finch_2_buzzer(3, 493, 60) sleep(1.00) finch.led("#000055") # set the led to red finch.finch_2_buzzer(3, 523, 60) sleep(1.00) finch.led("#550055") # set the led to blue finch.finch_2_buzzer(3, 587, 60) sleep(1.00) finch.led("#555500") # set the led to red finch.finch_2_buzzer(3, 659, 60) sleep(1.00) finch.led("#005555") # set the led to blue finch.finch_2_buzzer(3, 698, 60) sleep(1.00) finch.finch_2_buzzer(3, 880, 60)
from finch import Finch from time import sleep from random import randint tweety = Finch() left, right = tweety.obstacle() while not left and not right: x, y, z, tap, shake = tweety.acceleration() print("X : ", x) print("Y : ", y) print("Z : ", z) left, right = tweety.obstacle() sleep(.5) tweety.close()
# Car alarm # The finch sounds an alarm, alternating high pitch sounds and # flashing red abd blue lights, until its nose is turned up from time import sleep from finch import Finch from msvcrt import getch finch = Finch() def main(): #while(1): key = 0 ultrasound_value = 0 while (1): ultrasound_value = finch.new_obstacle() if (ultrasound_value > 2000): finch.wheels(0.5, 0.5) else: finch.wheels(0, 0.5) sleep(0.1) #print (ultrasound_value #key = ord(getch()) finch.halt() finch.close()
# Car alarm # The finch sounds an alarm, alternating high pitch sounds and # flashing red abd blue lights, until its nose is turned up from time import sleep from finch import Finch finch = Finch() x = 0 while x > -0.5: x, y, z, tap, shake = finch.acceleration() finch.led("#FF0000") # set the led to red finch.buzzer(1.0, 250) sleep(1.05) finch.led("#0000FF") # set the led to blue finch.buzzer(1.0, 400) sleep(1.05) finch.halt() finch.close()
#Michael Lannon from finch import Finch from time import sleep from Finch_project_dance import dance1,dance2,dance3 from Finch_project_loggig import show_log file = open('finchlog.txt', 'a+') logging = open('finchlog.txt', 'r') log = logging.readlines() myFinch = Finch() a = 220 #keeping this here just in case bflat = 233 hbflat=466 asharp = bflat fsharp=370 gflat=fsharp b = 247 c = 262 d = 294 e = 330 f = 349 g = 392 ha=int(2*a) #this is an 'a' note one octave above the other hb=int(2*b) #this is a 'b' note one octave above the other, etc.... hc=int(2*c) hd=int(2*d) he=int(2*e) hf=int(2*f)
from finch import Finch #Here we start using the robot robot = Finch() notes = [880, 988, 523, 587, 659, 698] length = 1.2 #let's use a default length of the note for note in notes: print("Note is", note) #QUESTION: What happens if I *remove* the indentation for the next line? robot.buzzer_with_delay(length, note) print("The last note was ", note) print("All notes played!")
if (side == RIGHT): wheels(0.0, R_INITIAL) else: wheels(L_INITIAL, 0.0) #BREAK OUT OF LOOP IF INFINITE SPINNING? while not left_obst or not right_obst: left_obst, right_obst = finchy.obstacle() if right_obst: return RIGHT else: return LEFT ########################################### # # MAIN # ########################################### #initialize the finch & data finchy = Finch() #MENU #function calls here multithread here startFinch(finchy) finchy.close()
# A simple program that wanders and avoids obstacles from finch import Finch from time import sleep # Instantiate the Finch object and connect to Finch tweety = Finch() # Get the Z-Axis acceleration zAccel = tweety.acceleration()[2] # Do the following while the Finch is not upside down (z value in gees above -0.7) while zAccel > -0.7: left_obstacle, right_obstacle = tweety.obstacle() # If there's an obstacle on the left, back up and arc if left_obstacle: tweety.led(255,0,0) tweety.wheels(-0.3,-1.0) sleep(1.0) # Back up and arc in the opposite direction if there's something on the right elif right_obstacle: tweety.led(255,255,0) tweety.wheels(-1.0, -0.3) sleep(1.0) # Else just go straight else: tweety.wheels(1.0, 1.0) tweety.led(0,255,0) # Keep reading in the Z acceleration zAccel = tweety.acceleration()[2]
from finch import Finch #Here we start using the robot robot = Finch() notes = ['A','a','B','b','C','c','D','d','E','e','F','f','A','a'] for note in notes: print("Note is", note) if (note.isupper()): length = 1.2 # uppercase letters mean long notes else: length = 0.6 # lowercase are short #convert note to lowercase so that we can compare easily current_note = note.lower() if (current_note == 'a'): frequency = 880 elif (current_note == 'b'): frequency = 988 elif (current_note == 'c'): frequency = 523 elif (current_note == 'd'): frequency = 587 elif (current_note == 'e'): frequency = 659 elif (current_note == 'f'): frequency = 698 else: #QUESTION: What happens if I de-indent this and the following lines? print("can't play this frequency!") print("Frequency is", frequency)
class myFinch: # Class Initializer # Synopsis - # self.left_wheel, is the speed of the left wheel, set to 0 # self.right_wheel, is the speed of the right wheel, set to 0 # self.tweety, is the Finch robot object which will be manipulated through this class # # Description - # Initialize the class members to a specific value def __init__(self): self.tweety = Finch() # Set obstacle sensors self.left_obst, self.right_obst = self.tweety.obstacle() # Setting initial lighting self.myLights = lighting(self.tweety) # Setting initial acceleration settings self.x, self.y, self.z, self.tap, self.shake = self.tweety.acceleration() # Setting initial wheel speed self.left_wheel = 0.0 self.right_wheel = 0.0 self.tweety.wheels(self.left_wheel, self.right_wheel) def __del__(self): self.tweety.close() # [FUNCTION]Name - setWheels ( left, right ) # Synopsis - # def setWheels ( left, right ) : # left, an double value for the left wheel speed # right, an double value for the right wheel speed # # Description - # Accelerates each wheel at different speeds to obtain the new speed. This can be # adjusted by small increments and also gives each wheel independent ending # speeds. # # Return - # (none) def setWheels ( self, left, right ): self.left_wheel = left self.right_wheel = right self.tweety.wheels(self.left_wheel, self.right_wheel) self.printSpeed() return # setWheels ( left, right ) # def isLight( self ): current_left, current_right = self.tweety.light() print ("Left reading : ",current_left) print ("Right reading : ", current_right) sleep(1) return current_left, current_right return False return True # [FUNCTION]Name - def printSpeed ( ) # Synopsis - # def printSpeed ( ): # (no parameters) # Description - # Upon changing speed with setWheels this will print the individual wheel speed # or both to the console. # # Return - # (none) def printSpeed ( self ): if (self.left_wheel == self.right_wheel): print ("Current speed : ", self.left_wheel) return print("Left speed : ", self.left_wheel) print("Right speed : ", self.right_wheel) return # printSpeed ( self ) # # [FUNCTION]Name - def detectSingleObstacle ( ) # Synopsis - # def detectSingleObstacle ( ): # (no parameters) # Description - # Function will utilize the finch's right and left sensors to see if there is # an obstacale on the left or right. # # Return - # "Left" upon a left_obst sensor being triggered # "right" upon a right_obst sensor being triggered # False otherwise def detectSingleObstacle(self): #while there is no obstacle continue self.left_obst, self.right_obst = self.tweety.obstacle() if self.left_obst: print ( "Left obstacle" ) return "left" elif self.right_obst: print ( "Right obstacle" ) return "right" return False # detectSingleObstacle(self) # # [FUNCTION]Name - def detectWall ( ) # Synopsis - # def detectWall ( ): # (no parameters) # Description - # Function will utilize the finch's right and left sensors to see if there is # an obstacale directly in front of both sensors. # # Return - # True if obstacle detected on both sides. # False if no obstacle detected / only one side detected def detectWall (self): self.left_obst, self.right_obst = self.tweety.obstacle() if (self.left_obst and self.right_obst): print (self.left_obst, self.right_obst) return True return False # detectWall ( self ) # def detectLight(self): while(True): self.myLights.isDifferent() sleep(2) #################################################### ############## GENERAL MOVEMENT #################### #################################################### def reverseLeft( self, t ): self.tweety.led("#800080") self.setWheels(-1.0, -0.5) sleep ( t ) return def reverseRight( self, t ): self.tweety.led("#800080") self.setWheels(-0.5, -1.0) sleep ( t ) return def forLeft( self, t ): self.tweety.led("#800080") self.setWheels( 0.25, 0.5) sleep ( t ) return def forRight( self, t ): self.tweety.led("#800080") self.setWheels( 1.0, 0.5 ) sleep ( t ) return def straight( self, speed, t ): self.tweety.led("#00FF00") self.setWheels( speed, speed ) sleep ( t ) return def reverse( self, speed, t ): self.tweety.led("#800080") self.setWheels( -speed, -speed ) sleep ( t ) return def stop( self ): self.tweety.led("#800080") self.setWheels(0.0, 0.0) return def forceStop(self): self.tweety.led('#FF0000') self.stop() os._exit(0)
if (finch != "y"): while (see == True): see = pass_gas(True) WASD("shutdown script") else: # A simple program that wanders and avoids obstacles from finch import Finch from time import sleep import notes #Main function for the music player example program""" #Initialize the finch finch = Finch() songList = [ 'E5 C D E C D E F D E F D E F G A GE F C D E G E D C ', 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ' 'E D5 A4 G G5 A4 F5# A4 E D5 A4 G G5 A4 F5# A4 ' 'G D5 A4 G G5 A4 F5# A4 G D5 A4 G G5 A4 F5# A4 ' 'D D5 A4 G G5 A4 F5# A4 D D5 A4 G G5 A4 F5# A4 ', 'E5 E E C E G ', 'C E5 G' ] timeList = [0.18, 0.1, 0.1] song = 1 #get which song song = 3
right_minimum, right_maximum = right_sensor[0], right_sensor[-1] target = open(filename, 'w') target.truncate() s = 'left max: ' + str(left_maximum) + '\n' target.write(str(s)) s = 'left min: ' + str(left_minimum) + '\n' target.write(str(s)) s = 'left diff: ' + str(left_maximum - left_minimum) + '\n' target.write(str(s)) s = 'left avg: ' + str(float(sum(left_sensor) / len(left_sensor))) + '\n\n' target.write(str(s)) s = 'right max: ' + str(right_maximum) + '\n' target.write(str(s)) s = 'right min: ' + str(right_minimum) + '\n' target.write(str(s)) s = 'right diff: ' + str(right_maximum - right_minimum) + '\n' target.write(str(s)) s = 'right avg: ' + str(float( sum(right_sensor) / len(right_sensor))) + '\n\n' target.write(str(s)) target.close() return newFinch = Finch() #calibrateLights(newFinch, "calib.txt") tweety = myFinch(newFinch) tweety.scurryTowardsLights()
# A simple program that randomly changes the LED when the Finch is tapped or shaken # Try it by setting the Finch on a table and tapping the top from finch import Finch from random import randint # Instantiate the Finch object and connect to Finch tweety = Finch() left, right = tweety.obstacle() # Do the following while no obstacles are detected by Finch while not left and not right: # Get the accelerations x, y, z, tap, shake = tweety.acceleration() # Print the acceleration data print( "X is %.2f gees, Y is %.2f gees, Z is %.2f gees, tap is %r shake is %r" % (x, y, z, tap, shake)) # If a tap or shake has been detected recently, set the LED to a random color if tap or shake: tweety.led(randint(0, 255), randint(0, 255), randint(0, 255)) # Get obstacles to use to exit loop left, right = tweety.obstacle() tweety.close()
'Yes.', 'Signs point to yes.', 'Reply hazy try again.', 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.' 'Concentrate and ask again.', 'Don\'t count on it.', 'My reply is no.', 'My sources say no.', 'Outlook not so good.', 'Very doubtful.', ] # Always the first step: Create a Finch object we can use. tweety = Finch() # Tell the user how to use our program. print('I\'m a "Magic 8"-Finch!' '\n\nAsk me a question, shake me, and turn me upside down to get ' 'your answer.') # Create the variables we will use to track our state across multiple # executions of the loop: # Remember if we were upside down the last time the loop ran or not. We # want to print our answer the first moment we detect that the user # flipped us upside down. Then, we don't want to print another answer # until we can tell that the user has flipped us right-side up and then # upside down again. was_upside_down_before = False
from finch import Finch from time import sleep from flask import Flask from flask import render_template, redirect from random import randint app = Flask(__name__) finch = Finch() @app.route('/') def index(): return render_template('index.html') @app.route('/change_color') def change_color(): finch.led(randint(0, 255), randint(0, 255), randint(0, 255)) return redirect('/') @app.route('/halt') def halt(): finch.halt() return redirect('/') @app.route('/sensors') def sensors(): c = finch.temperature() f = ((c * 9)/5 ) + 32 x, y, z, tap, shake = finch.acceleration() left, right = finch.obstacle()