Here is something I come up with to get the Robomaster S1 to automatically return fire when hit while at the same time allowing it to be controlled by the user. Copying and pasting this code to the DYI programming lab should work:
# Turn to the side a hit came from. It should be called when a hit is detected. def user_defined_turn_to_hit_side(): if (armor_ctrl.check_condition(rm_define.cond_armor_bottom_right_hit)) or (armor_ctrl.check_condition(rm_define.cond_armor_top_right_hit)): # Hit on the right side. Turn right. gimbal_ctrl.rotate_with_degree(rm_define.gimbal_right,90) else if (armor_ctrl.check_condition(rm_define.cond_armor_bottom_left_hit)) or (armor_ctrl.check_condition(rm_define.cond_armor_top_left_hit)): # Hit on the left side. Turn left. gimbal_ctrl.rotate_with_degree(rm_define.gimbal_left,90) else if armor_ctrl.check_condition(rm_define.cond_armor_bottom_back_hit): # Hit on the back side. Turn back. gimbal_ctrl.rotate_with_degree(rm_define.gimbal_right,180)
# Program entry point. This is the start of our code and is implicitly called by the actual main function. def start(): # Gimbal lead mode. Chassis follow the direction of the gimbal. robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
# Set rotation speed to 360 degrees per second. gimbal_ctrl.set_rotate_speed(360)
# Allows controlling the gimbal with the controller in autonomous mode. gimbal_ctrl.enable_stick_overlay()
# Allows controlling the chassis with the controller in autonomous mode. chassis_ctrl.enable_stick_overlay()
# This keeps the autonomous program running otherwise it would exit. We sleep here so not to hog the CPU. # 3600 seconds is an arbitrarily large time to sleep but even a second should be ok. Our main code runs on a # callback anyway so the large sleep time does not matter. while True: time.sleep(3600)
# This is an API provided callback and called automatically whenever a hit is detected. def armor_hit_detection_all(msg): # Turn to the side we got hit from. user_defined_turn_to_hit_side()
# TODO: Use S1 detection to find and center on the attacking robomaster before firing. # Fire once. Note this does not appear to really work in autonomous mode. Looks like a bug to me. gun_ctrl.fire_once()
# TODO: Move back to the original position (easy, just need to keep track of the direction we turned. Might not # be desirable as we might be contantly hit from that side.
|