├── .github
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── demo
├── Client.py
├── Mercury_A1_demo
│ └── README.md
├── README.md
├── SOCT_REMADE.md
├── Server.py
├── Server_260.py
├── Server_270.py
├── Server_280.py
├── Server_280_RDKX5.py
├── Server_280_RISCV.py
├── Server_320.py
├── Server_A1.py
├── Server_A1_2.py
├── Server_Pro630.py
├── Server_X1_close_loop.py
├── basic.py
├── change_pid.py
├── drag_trial_teaching.py
├── drag_trial_teaching_cobotx.py
├── drag_trial_teaching_myArm.py
├── get_port.py
├── gripper.py
├── gripper_set.py
├── handle_control
│ ├── README.md
│ ├── arm_profile
│ │ └── mycobot_280.json
│ ├── handle.jpg
│ ├── joy_control.py
│ ├── myCobot280_handle_control.py
│ ├── myarm_handle_control.py
│ └── requirements.txt
├── loop.py
├── myArm_M
├── myArm_M&C_demo
│ ├── README.md
│ ├── README_ZH.md
│ ├── get_date.py
│ ├── main.py
│ ├── myarm_c.py
│ ├── myarm_m.py
│ ├── requirement.txt
│ ├── resources
│ │ ├── app.png
│ │ ├── app_1.png
│ │ ├── app_2.png
│ │ └── mystudio.ico
│ ├── ui
│ │ ├── bt.py
│ │ ├── tool.ui
│ │ └── tool_ui.py
│ └── utils.py
├── myArm_M&C_demo_v1.1
│ ├── README.md
│ ├── README_ZH.md
│ ├── get_date.py
│ ├── main.py
│ ├── myarm_c.py
│ ├── myarm_m.py
│ ├── requirement.txt
│ ├── resources
│ │ ├── app.png
│ │ ├── app_1.png
│ │ ├── app_2.png
│ │ └── mystudio.ico
│ └── ui
│ │ ├── bt.py
│ │ ├── tool.ui
│ │ └── tool_ui.py
├── myArm_demo
│ ├── .xiaqi.py.swp
│ ├── all_run_test.py
│ ├── dexterous_hands.py
│ ├── four_piece_chess.py
│ ├── gripper_aikit_v2.py
│ ├── hand_gripper.py
│ ├── myarm_agv_demo.py
│ ├── myarm_handle_control.py
│ ├── pump_aikit_v2.py
│ ├── pump_test.py
│ ├── rgb_led.py
│ ├── rgb_test.py
│ ├── space_arm_angle.py
│ ├── start_run_demo.py
│ ├── wave_hand.py
│ └── xiaqi.py
├── myCobot_280_demo
│ ├── 280_draw_gcode.py
│ ├── five_point_star.nc
│ ├── square.nc
│ └── triangle.nc
├── myCobot_320_demo
│ ├── drag_trial_teaching_myCobot_320.py
│ ├── myCobot_320_servo_info.py
│ ├── myCobot_320_testtool_M5version_v1.0_20220623.py
│ └── myCobot_320_testtool_PIversion_v1.0_20220623.py
├── mybuddy_demo
│ ├── drag_trial_teaching_mubuddy.py
│ ├── drag_trial_teaching_sync_mubuddy.py
│ ├── emoticon.md
│ ├── emoticon.zip
│ ├── gpio_test.py
│ ├── myBuddy_Action
│ │ ├── ChewingGum.py
│ │ ├── ChewingGum.txt
│ │ ├── ChewingGum_2.txt
│ │ ├── ChewingGum_3.txt
│ │ ├── README.md
│ │ ├── catch_the_ball.py
│ │ ├── catch_the_ball.txt
│ │ ├── comeOn.py
│ │ ├── comeOn.txt
│ │ ├── dack.py
│ │ ├── dance.py
│ │ ├── myBuddy_conductor.json
│ │ ├── pass_the_ball.py
│ │ ├── pass_the_ball.txt
│ │ ├── petCat.py
│ │ ├── petCat.txt
│ │ ├── piano.py
│ │ ├── play_ball_cooperatively.py
│ │ ├── play_ball_cooperatively.txt
│ │ ├── praise.py
│ │ ├── praise.txt
│ │ ├── reject.py
│ │ ├── reject.txt
│ │ ├── symphony.py
│ │ ├── symphony.txt
│ │ ├── thanHeart.py
│ │ └── thanHeart.txt
│ ├── myBuddy_gpio_test.py
│ ├── mybuddy_change_pid.py
│ ├── mybuddy_emoticon_demo.py
│ ├── mybuddy_encoders_test.py
│ └── mybuddy_send_angles_auto.py
├── mybuddy_emo.py
├── mycobot_pi_bluetooth
│ ├── README.md
│ ├── __init__.py
│ ├── app.py
│ ├── bt.py
│ ├── bt_client.py
│ ├── example-gatt-client.py
│ ├── example_advertisement.py
│ ├── example_gatt_server.py
│ ├── timezone.py
│ └── uart_peripheral_serial.py
├── pid_read_write.py
├── port_setup.py
├── reader.py
├── send_angle.py
├── server_400.py
├── server_A1_close_loop.py
├── sync.py
├── tools
│ ├── pump_demo_M5.py
│ └── pump_demo_PI.py
└── ultraArm_P340_demo
│ ├── 3-angles_control.py
│ ├── 4-coords_control.py
│ ├── 5-Palletizing_handling.py
│ ├── 6-laser_use.py
│ ├── 8-gripper_use.py
│ └── 9-pump_use.py
├── docs
├── MechArm_270_en.md
├── MechArm_270_zh.md
├── Mercury_API.md
├── Mercury_X1_Chassis_en.md
├── Mercury_X1_Chassis_zh.md
├── MyAGVPro_en.md
├── MyAGVPro_zh.md
├── MyBuddy_en.md
├── MyBuddy_zh.md
├── MyCobot_280_RDKX5_en.md
├── MyCobot_280_RDKX5_zh.md
├── MyCobot_280_en.md
├── MyCobot_280_zh.md
├── MyCobot_320_en.md
├── MyCobot_320_zh.md
├── MyPalletizer_260_en.md
├── MyPalletizer_260_zh.md
├── README.md
├── myAGV_en.md
├── myAGV_zh.md
├── myArm_M&C_en.md
├── myArm_M&C_zh.md
├── mybuddy_emoticon_en.md
├── mybuddy_emoticon_zh.md
├── pro630_esp32_en.md
├── pro630_esp32_zh.md
├── ultraArm_P340_en.md
└── ultraArm_P340_zh.md
├── f3-min2.jpg
├── pymycobot
├── Interface.py
├── __init__.py
├── bluet.py
├── close_loop.py
├── common.py
├── conveyor_api.py
├── dualcobotx.py
├── elephantrobot.py
├── end_control.py
├── error.py
├── exoskeleton.py
├── exoskeletonsocket.py
├── generate.py
├── genre.py
├── log.py
├── mecharm.py
├── mecharm270.py
├── mecharmsocket.py
├── mercury.py
├── mercury_api.py
├── mercury_arms_socket.py
├── mercury_ros_api.py
├── mercurychassis.py
├── mercurychassis_api.py
├── mercurysocket.py
├── myagv.py
├── myagvapi.py
├── myagvpro.py
├── myagvpro_bluetooth.py
├── myagvpro_socket.py
├── myarm.py
├── myarm_api.py
├── myarmc.py
├── myarmm.py
├── myarmm_control.py
├── myarmsocket.py
├── mybuddy.py
├── mybuddybluetooth.py
├── mybuddyemoticon.py
├── mybuddysocket.py
├── mycobot.py
├── mycobot280.py
├── mycobot280rdkx5.py
├── mycobot280socket.py
├── mycobot320.py
├── mycobot320socket.py
├── mycobotpro630.py
├── mycobotsocket.py
├── mypalletizer.py
├── mypalletizer260.py
├── mypalletizersocket.py
├── pro400.py
├── pro400client.py
├── pro630.py
├── pro630client.py
├── pro630common.py
├── progripper.py
├── protocol_packet_handler.py
├── public.py
├── robot_info.py
├── sms.py
├── tool_coords.py
├── ultraArm.py
├── ultraArmP340.py
└── utils.py
├── requirements.txt
├── setup.py
└── tests
├── __init__.py
├── conftest.py
├── rasp_myArm_test_gui.py
├── rasp_mycobot_test_gui.py
├── rasp_mypall_test_gui.py
├── special_angles.py
├── test_api.py
├── test_generator.py
├── test_socket.py
└── test_utils.py
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | dist/
3 | pymycobot.egg-info/
4 |
5 | log
6 | pymycobot/__pycache__/
7 | tests/__pycache__/
8 |
9 | test*.py
10 | record.txt
11 | test_test.py
12 |
13 | .DS_Store
14 | .history
15 | *.bat
16 | .VSCodeCounter
17 | .vscode/
18 | *.sh
19 |
20 | *.pyc
21 | __pycache__/port.cpython-39.pyc
22 | demo/__pycache__/port.cpython-39.pyc
23 | demo/__pycache__/port_setup.cpython-39.pyc
24 | .idea
25 | .vscode
26 | *.log
27 | .venv/
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | MIT License
3 |
4 | Copyright () 2020 Elephant Robotics
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
23 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include *.txt
2 | include LICENSE
3 | include README.md
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # This is Python API for ElephantRobotics product
2 |
3 | 
4 | 
5 | [](https://pypi.org/project/pigit)
6 |
7 | This is a python API for serial communication with mycobot and controlling it.
8 |
9 | [](https://www.elephantrobotics.com/en/myCobot-en/)
10 |
11 | ## Installation
12 |
13 | **Notes**:
14 |
15 | > Make sure that `Atom` is flashed into the top Atom, `Transponder` is flashed into the base Basic.
16 | > The firmware `Atom` and `Transponder` download address: [https://github.com/elephantrobotics/myCobot/tree/main/Software](https://github.com/elephantrobotics/myCobot/tree/main/Software)
17 | > You also can use myStudio to flash them, myStudio address: [https://github.com/elephantrobotics/myStudio/releases](https://github.com/elephantrobotics/myStudio/releases)
18 |
19 | ### Pip
20 |
21 | ```bash
22 | pip install pymycobot --upgrade
23 | ```
24 |
25 |
34 |
35 | ### Source code
36 |
37 | ```bash
38 | git clone https://github.com/elephantrobotics/pymycobot.git
39 | cd /pymycobot
40 | # Install
41 | [sudo] python2 setup.py install
42 | # or
43 | [sudo] python3 setup.py install
44 | ```
45 |
46 | Or the more modern form:
47 |
48 | ```bash
49 | # Install
50 | pip install .
51 | # Uninstall
52 | pip uninstall .
53 | ```
54 |
55 | ## Usage:
56 |
57 | ```python
58 | # for mycobot 280 machine
59 | from pymycobot import MyCobot280
60 | from pymycobot import MyCobot280Socket
61 | # for mycobot 320 machine
62 | from pymycobot import MyCobot320
63 | from pymycobot import MyCobot320Socket
64 | # for mecharm 270 machine
65 | from pymycobot import MechArm270
66 | from pymycobot import MechArmSocket
67 | # for mypalletizer 260 machine
68 | from pymycobot import MyPalletizer260
69 | from pymycobot import MyPalletizerSocket
70 | # for ultraArm P340 machine
71 | from pymycobot import ultraArmP340
72 | ```
73 |
74 | The [`demo`](./demo) directory stores some test case files.
75 |
76 | You can find out which interfaces pymycobot provides in `pymycobot/README.md`.
77 |
78 | Please go to [here](./docs/README.md).
79 |
80 |
81 | > Note: Version v3.6.0 differentiates interfaces by model. Starting from this version, the MyCobot class will no longer be maintained. For new usage, please refer to the document:
82 |
83 |  
84 |
85 | [MyCobot 280 API说明](./docs/MyCobot_280_zh.md) | [MyCobot 280 API Description](./docs/MyCobot_280_en.md)
86 |
87 | [MyCobot 320 API说明](./docs/MyCobot_320_zh.md) | [MyCobot 320 API Description](./docs/MyCobot_320_en.md)
88 |
89 | [MechArm 270 API说明](./docs/MechArm_270_zh.md) | [MechArm 270 API Description](./docs/MechArm_270_en.md)
90 |
91 | [MyPalletizer 260 API说明](./docs/MyPalletizer_260_zh.md) | [MyPalletizer 260 API Description](./docs/MyPalletizer_260_en.md)
92 |
93 | [myAGV API说明](./docs/myAGV_zh.md) | [myAGV API Description](./docs/myAGV_en.md)
94 |
95 | [myArm_M&C API说明](./docs/myArm_M&C_zh.md) | [myArm_M&C API Description](./docs/myArm_M&C_en.md)
96 |
97 | [ultraArm P340 API说明](./docs/ultraArm_P340_zh.md) | [ultraArm P340 API Description](./docs/ultraArm_P340_en.md)
98 |
99 | [MyBuddy API说明](./docs/MyBuddy_zh.md) | [MyBuddy API Description](./docs/MyBuddy_en.md)
100 |
101 | [MyBuddyEmoticon API说明](./docs/mybuddy_emoticon_zh.md) | [MyBuddyEmoticon API Description](./docs/mybuddy_emoticon_en.md)
--------------------------------------------------------------------------------
/demo/Client.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyCobot280Socket
2 |
3 | m = MyCobot280Socket("192.168.10.10", "9000")
4 | # connect pi
5 | # m.connect()
6 | print(m.get_coords())
7 |
--------------------------------------------------------------------------------
/demo/Mercury_A1_demo/README.md:
--------------------------------------------------------------------------------
1 |
2 | The A1 mouse control example has been moved to a new project address: https://github.com/elephantrobotics/mercury_A1_case
3 |
4 |
5 |
--------------------------------------------------------------------------------
/demo/README.md:
--------------------------------------------------------------------------------
1 | There are some demo files of **pymycobot**.
2 |
3 |
4 |
--------------------------------------------------------------------------------
/demo/SOCT_REMADE.md:
--------------------------------------------------------------------------------
1 | # 使用说明
2 | ## 使用说明
3 | * "Client.py"是客户端的样例,使用在你的电脑中运行
4 | * "Servo.py"是服务器端的执行文件,在机械臂中运行
5 | ## 参考内容
6 | * [Socket 使用解析](https://blog.csdn.net/pashanhu6402/article/details/96428887?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162392592016780357215629%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=162392592016780357215629&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-96428887.first_rank_v2_pc_rank_v29&utm_term=socket&spm=1018.2226.3001.4187)
7 |
8 | * [mycobot 使用说明](https://www.elephantrobotics.com/docs/myCobot/)
9 |
10 | * [Scoket 函数解析](https://www.runoob.com/python/python-socket.html)
--------------------------------------------------------------------------------
/demo/basic.py:
--------------------------------------------------------------------------------
1 | import time
2 | import os
3 | import sys
4 | from pymycobot.mycobot280 import MyCobot280
5 | from pymycobot.genre import Angle, Coord
6 |
7 | sys.path.append(os.path.dirname(__file__))
8 | from port_setup import setup
9 |
10 | reset = [153.19, 137.81, -153.54, 156.79, 87.27, 13.62]
11 |
12 |
13 | def test(mycobot):
14 | print("\nStart check basic options\n")
15 |
16 | mycobot.set_color(255, 255, 0)
17 | print("::set_color() ==> color {}\n".format("255 255 0"))
18 | time.sleep(3)
19 |
20 | angles = [0, 0, 0, 0, 0, 0]
21 | mycobot.send_angles(angles, 100)
22 | print("::send_angles() ==> angles {}, speed 100\n".format(angles))
23 | time.sleep(3)
24 |
25 | print("::get_angles() ==> degrees: {}\n".format(mycobot.get_angles()))
26 | time.sleep(1)
27 |
28 | mycobot.send_angle(Angle.J1.value, 90, 50)
29 | print("::send_angle() ==> angle: joint1, degree: 90, speed: 50\n")
30 | time.sleep(4)
31 |
32 | radians = [1, 1, 1, 1, 1, 1]
33 | mycobot.send_radians(radians, 100)
34 | print("::send_radians() ==> set radians {}, speed 100\n".format(radians))
35 | time.sleep(3)
36 |
37 | print("::get_radians() ==> radians: {}\n".format(mycobot.get_radians()))
38 | time.sleep(1)
39 |
40 | coords = [160, 160, 160, 0, 0, 0]
41 | mycobot.send_coords(coords, 70, 0)
42 | print("::send_coords() ==> send coords {}, speed 70, mode 0\n".format(coords))
43 | time.sleep(3)
44 |
45 | print("::get_coords() ==> coords {}\n".format(mycobot.get_coords()))
46 | time.sleep(0.5)
47 |
48 | mycobot.send_coord(Coord.X.value, -40, 70)
49 | print("::send_coord() ==> send coord id: X, coord value: -40, speed: 70\n")
50 | time.sleep(2)
51 |
52 | print("::set_free_mode()\n")
53 | mycobot.send_angles(reset, 100)
54 | time.sleep(5)
55 | mycobot.release_all_servos()
56 |
57 | print("=== check end ===\n")
58 |
59 |
60 | if __name__ == "__main__":
61 | print(
62 | """
63 | --------------------------------------------
64 | | This file will test basic option method: |
65 | | set_led_color() |
66 | | send_angles() |
67 | | get_angles() |
68 | | send_angle() |
69 | | send_radians() |
70 | | get_radians() |
71 | | send_coords() |
72 | | get_coords() |
73 | | send_coord() |
74 | --------------------------------------------
75 | """
76 | )
77 | time.sleep(3)
78 | # port = subprocess.check_output(['echo -n /dev/ttyUSB*'],
79 | # shell=True).decode()
80 | # with open(os.path.dirname(__file__) + "/port.txt") as f:
81 | # port = f.read().strip().replace("\n", "")
82 | # print(port)
83 | mycobot = setup()
84 | test(mycobot)
85 |
--------------------------------------------------------------------------------
/demo/change_pid.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | import time
3 | from turtle import goto
4 | from pymycobot.mycobot280 import MyCobot280
5 | import serial.tools.list_ports
6 |
7 | data_id = [21, 22, 23, 24, 26, 27]
8 | mc = []
9 | ports = []
10 |
11 | def setup(): #机械臂检测函数,选择正确的串口
12 | global mc
13 | print("")
14 |
15 | plist = list(serial.tools.list_ports.comports())
16 | idx = 0
17 | for port in plist:
18 | print("{} : {}".format(idx, port))
19 | idx += 1
20 | if idx == 0:
21 | print("The connected device was not detected. Please try reconnecting.")
22 | exit(1)
23 | _in = input("\nPlease input 0 - {} to choice, you can choice many like: '2,1,3':".format(idx))
24 | idxes = _in.split(',')
25 | try:
26 | idxes = [int(i) for i in idxes]
27 | except Exception:
28 | print('Error: Input format error.')
29 | exit(1)
30 |
31 | ports = [str(plist[i]).split(' - ')[0].strip() for i in idxes]
32 |
33 | print(ports)
34 | print("")
35 |
36 | baud = 115200
37 | _baud = input("Please input baud(default:115200):")
38 | try:
39 | baud = int(_baud)
40 | except Exception:
41 | pass
42 | print(baud)
43 | print("")
44 |
45 | for port in ports:
46 | try:
47 | mycobot = MyCobot280(port, baud)
48 | except Exception as e:
49 | print(e)
50 | exit(1)
51 | mc.append(mycobot)
52 |
53 | def change():
54 | global mc
55 | mode = 1
56 | _mode = input("Please input mode, 1 = high precision, 2 = stabilize (default: 1 ):")
57 | try:
58 | mode = int(_mode)
59 | except Exception:
60 | pass
61 | print(mode)
62 | print("")
63 |
64 | for _mycbot in mc:
65 | print(_mycbot)
66 | for i in range(1,7):
67 | if mode == 1:
68 | data = [10, 0, 1, 0, 3, 3]
69 | elif mode == 2:
70 | if i < 4 :
71 | data = [5, 15, 0, 0, 3, 3]
72 | else:
73 | data = [8, 24, 0, 0, 3, 3]
74 | else:
75 | print("Please set the parameter mode !!!")
76 | goto(change())
77 |
78 | for j in range(len(data_id)):
79 | _mycbot.set_servo_data(i, data_id[j], data[j])
80 | time.sleep(0.2)
81 | _data = _mycbot.get_servo_data(i, data_id[j])
82 | time.sleep(0.2)
83 | if _data == data[j]:
84 | print("Servo motor :" + str(i) + " data_id : " + str(data_id[j]) + " data: " + str(_data) + " modify successfully ")
85 | else:
86 | print("Servo motor :" + str(i) + " data_id : " + str(data_id[j]) + " data: " + str(_data) + " modify error ")
87 |
88 | if __name__ == "__main__": #主函数
89 | setup()
90 | print(mc)
91 | try:
92 | change()
93 | except Exception as e:
94 | print(e)
95 |
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/demo/get_port.py:
--------------------------------------------------------------------------------
1 | import serial
2 | import serial.tools.list_ports
3 | import os
4 |
5 | if __name__ == "__main__":
6 | """
7 | result:
8 | /dev/cu.wlan-debug - n/a
9 | /dev/cu.debug-console - n/a
10 | /dev/cu.Bluetooth-Incoming-Port - n/a
11 | /dev/cu.usbserial-0213245D - CP2104 USB to UART Bridge Controller
12 |
13 | port='/dev/cu.usbserial-0213245D'
14 | """
15 | plist = list(serial.tools.list_ports.comports())
16 | idx = 1
17 | for port in plist:
18 | print("{} : {}".format(idx, port))
19 | idx += 1
20 |
21 | _in = input("\nPlease input 1 - {} to choice:".format(idx - 1))
22 | port = str(plist[int(_in) - 1]).split(" - ")[0].strip()
23 | print(port)
24 | with open(os.path.dirname(__file__) + "/port.txt", "w") as f:
25 | f.write(port + "\n")
26 |
--------------------------------------------------------------------------------
/demo/gripper.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | import sys
4 | from pymycobot import MyCobot280
5 |
6 | sys.path.append(os.path.dirname(__file__))
7 | from port_setup import setup
8 |
9 |
10 | def gripper_test(mc):
11 | print("Start check IO part of api\n")
12 | # print()
13 |
14 | flag = mc.is_gripper_moving()
15 | print("Is gripper moving: {}".format(flag))
16 | time.sleep(1)
17 |
18 | # Set the current position to (2048).
19 | # Use it when you are sure you need it.
20 | # Gripper has been initialized for a long time. Generally, there
21 | # is no need to change the method.
22 | # mc.set_gripper_ini()
23 |
24 | mc.set_encoder(7, 2048)
25 | time.sleep(3)
26 | mc.set_encoder(7, 1300)
27 | time.sleep(3)
28 |
29 | # set_gripper_value has some bug, just can close.
30 | mc.set_gripper_value(2048, 70)
31 | time.sleep(5)
32 | mc.set_gripper_value(1500, 70)
33 | time.sleep(5)
34 |
35 | mc.set_gripper_state(0, 70)
36 | time.sleep(5)
37 | mc.set_gripper_state(1, 70)
38 | time.sleep(5)
39 |
40 | print("")
41 | print(mc.get_gripper_value())
42 |
43 |
44 | if __name__ == "__main__":
45 | mycobot = setup()
46 | gripper_test(mycobot)
47 |
--------------------------------------------------------------------------------
/demo/gripper_set.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | from pymycobot import MyCobot280
3 | import time
4 |
5 | # 需要将串口号更改为电脑实际的串口号,将夹爪张开到最大,再运行此脚本
6 | port = 'com8'
7 |
8 | mc = MyCobot280(port)
9 |
10 | print("零位矫正前当前所在位置: ",mc.get_gripper_value())
11 | time.sleep(0.1)
12 | mc.set_gripper_calibration()
13 | time.sleep(0.1)
14 | print("零位矫正后当前所在位置(矫正成功夹爪会锁住,并且位置接近100): ",mc.get_gripper_value())
15 | time.sleep(0.1)
16 | print("开始夹爪参数更新...")
17 | datas = [10, 0, 1, 150]
18 | address = [21, 22, 23, 16]
19 | current_datas = []
20 | new_datas = []
21 | for addr in address:
22 | current_datas.append(mc.get_servo_data(7, addr))
23 | time.sleep(0.1)
24 | print("当前夹爪参数为: ",current_datas)
25 | for addr in range(len(address)):
26 | mc.set_servo_data(7, address[addr], datas[addr])
27 | time.sleep(0.1)
28 | for addr in address:
29 | new_datas.append(mc.get_servo_data(7, addr))
30 | time.sleep(0.1)
31 | print("更新后夹爪参数为: ",new_datas)
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/demo/handle_control/README.md:
--------------------------------------------------------------------------------
1 | # instructions
2 |
3 | ## 1.Connecting devices
4 |
5 | Connect the MyCobot and handle to the computer.
6 |
7 | ## 2.Install required libraries
8 |
9 | Open the terminal, switch the path to this folder, and run the following command。
10 |
11 | ```bash
12 | pip3 install -r requirements.txt
13 | ```
14 |
15 | ## 3.Modify port number
16 |
17 | Edit the handle_control.py file
18 |
19 | ```python
20 | import pygame
21 | import time
22 | from pymycobot import MyCobot280
23 | import threading
24 | # Change com7 to the port number detected by your computer
25 | mc = MyCobot280("com7")
26 | ...
27 | ```
28 |
29 | Finally. run the program.
30 |
31 | ```bash
32 | python3 handle_control.py
33 | ```
34 |
35 | > Note: After running the program, first click the **14** button to check the machine connection status, the machine connection status is normal (if it is abnormal, you will not be able to perform other operations, please solve the abnormal connection problem first), and then click **Right 1** button, other operations can only be performed after the machine reaches the initial point.
36 |
37 | 
38 |
39 | The corresponding functions of the handle buttons are as follows:
40 |
41 | - **1**: RX direction coordinate value increases
42 | - **2**: RX direction coordinate value decreases
43 | - **3**: RY direction coordinate value decreases
44 | - **4**: RY direction coordinate value increases
45 | - **5**: X direction coordinate value increases
46 | - **6**: X direction coordinate value decreases
47 | - **7**: Y direction coordinate value decreases
48 | - **8**: Y direction coordinate value increases
49 | - **9**: Z direction coordinate value increases
50 | - **10**: Z direction coordinate value decreases
51 | - **11**: RZ direction coordinate value decreases
52 | - **12**: RZ direction coordinate value increases
53 | - **13**: Wake up the handle. After the handle is not used for a long time after connection, it will enter sleep mode. You need to press this button to wake up.
54 | - **14**: Check the connection status of the machine. The atom LED flashes green three times to indicate that the machine is normal; flashes red three times to indicate that the state is abnormal.
55 | - **X**: Press and hold the button, the jaws continue to open
56 | - **Y**: Press and hold the button, the jaws continue to close
57 | - **A**: open suction pump
58 | - **B**: Shut down the suction pump
59 | - **Left 1**: Press and hold for 2s to initialize the robot to the joint zero state.
60 | - **Left 2**: Press and hold for 2s, the robot stops torque output and relaxes all joints.
61 | - **Right 1**: Press and hold for 2s to initialize the robot to move to the initial point.
62 | - **Right 2**: Press and hold for 2s, the robot turns on the torque output, and all joints are locked
63 |
64 | # 使用说明
65 |
66 | ## 1.连接设备
67 |
68 | 将MyCobot和手柄连接到电脑。
69 |
70 | ## 2.安装所需的包
71 |
72 | 打开终端,切换路径到此文件夹,运行如下指令:
73 |
74 | ```bash
75 | pip3 install -r requirements.txt
76 | ```
77 |
78 | ## 3.修改端口号
79 |
80 | 编辑 handle_control.py 文件
81 |
82 | ```python
83 | import pygame
84 | import time
85 | from pymycobot import MyCobot280
86 | import threading
87 | # 将com7修改为你的电脑检测到的实际端口号
88 | mc = MyCobot280("com7")
89 | ...
90 | ```
91 |
92 | 最后,运行程序即可。
93 |
94 | ```bash
95 | python3 handle_control.py
96 | ```
97 |
98 | > 注意:在运行程序以后,首先要先点击**14**按钮,检查机器连接状态,机器连接状态正常(若为异常,将无法进行其他的操作,请先解决连接异常问题),再点击**Right 1**按钮,机器到达初始点位以后,才可以进行其他的操作。
99 |
100 | 手柄按钮对应功能如下:
101 |
102 | - **1**: RX方向坐标值增加
103 | - **2**: RX方向坐标值减小
104 | - **3**: RY方向坐标值减小
105 | - **4**: RY方向坐标值增大
106 | - **5**: X方向坐标值增加
107 | - **6**: X方向坐标值减小
108 | - **7**: Y方向坐标值减小
109 | - **8**: Y方向坐标值增加
110 | - **9**: Z方向坐标值增加
111 | - **10**: Z方向坐标值减小
112 | - **11**: RZ方向坐标值减小
113 | - **12**: RZ方向坐标值增加
114 | - **13**: 唤醒手柄,手柄连接以后长时间不使用会进入休眠,需要按下此键来唤醒
115 | - **14**: 检测机器连接状态,atom LED闪烁绿灯三次表示机器正常,闪烁红灯三次表示状态异常。
116 | - **X**: 夹爪累加张开
117 | - **Y**: 夹爪累加关闭
118 | - **X**: 打开吸泵
119 | - **X**: 关闭吸泵
120 | - **Left 1**: 长按2s,初始化机器人至关节零位状态。
121 | - **Left 2**: 长按2s,机器人停止力矩输出,放松所有关节。
122 | - **Right 1**: 长按2s,初始化机器人至移动初始点位。
123 | - **Right 2**: 长按2s,机器人打开力矩输出,所有关节锁定。
124 |
--------------------------------------------------------------------------------
/demo/handle_control/arm_profile/mycobot_280.json:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/handle_control/arm_profile/mycobot_280.json
--------------------------------------------------------------------------------
/demo/handle_control/handle.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/handle_control/handle.jpg
--------------------------------------------------------------------------------
/demo/handle_control/requirements.txt:
--------------------------------------------------------------------------------
1 | pyserial
2 | pymycobot
3 | pygame
--------------------------------------------------------------------------------
/demo/loop.py:
--------------------------------------------------------------------------------
1 | import time
2 | import os
3 | import sys
4 | from pymycobot import MyCobot280
5 |
6 | sys.path.append(os.path.dirname(__file__))
7 | from port_setup import setup
8 |
9 |
10 | if __name__ == "__main__":
11 | cobot = setup()
12 | cobot.send_angles([0, 0, 0, 0, 0, 0], 100)
13 | time.sleep(10)
14 | print("start")
15 | for count in range(50):
16 | time.sleep(0.05)
17 | cobot.send_angle(1, (-30), 100)
18 | time.sleep(0.05)
19 | cobot.send_angle(2, 70, 100)
20 | time.sleep(0.05)
21 | cobot.send_angle(3, (-110), 100)
22 | time.sleep(0.05)
23 | cobot.send_angle(4, (-100), 100)
24 | time.sleep(0.05)
25 | cobot.send_angle(5, 0, 100)
26 | time.sleep(0.05)
27 | cobot.send_angle(6, 0, 100)
28 | time.sleep(1)
29 | cobot.send_angle(2, 0, 100)
30 | time.sleep(0.05)
31 | cobot.send_angle(6, 0, 100)
32 | time.sleep(0.05)
33 | cobot.send_angle(5, 0, 100)
34 | time.sleep(0.05)
35 | cobot.send_angle(4, 0, 100)
36 | time.sleep(0.05)
37 | cobot.send_angle(3, 0, 100)
38 | time.sleep(0.05)
39 | cobot.send_angle(1, 0, 100)
40 | time.sleep(1)
41 | cobot.send_angle(1, 60, 100)
42 | time.sleep(0.05)
43 | cobot.send_angle(2, 70, 100)
44 | time.sleep(0.05)
45 | cobot.send_angle(3, (-100), 100)
46 | time.sleep(0.05)
47 | cobot.send_angle(4, (-100), 100)
48 | time.sleep(0.05)
49 | cobot.send_angle(5, 0, 100)
50 | time.sleep(0.05)
51 | cobot.send_angle(6, 0, 100)
52 | time.sleep(1)
53 | cobot.send_angle(2, 0, 100)
54 | time.sleep(0.05)
55 | cobot.send_angle(6, 0, 100)
56 | time.sleep(0.05)
57 | cobot.send_angle(5, 0, 100)
58 | time.sleep(0.05)
59 | cobot.send_angle(4, 0, 100)
60 | time.sleep(0.05)
61 | cobot.send_angle(3, 0, 100)
62 | time.sleep(0.05)
63 | cobot.send_angle(1, 0, 100)
64 | time.sleep(1)
65 | print("time")
66 |
--------------------------------------------------------------------------------
/demo/myArm_M:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/README.md:
--------------------------------------------------------------------------------
1 | # myArm M&C control case
2 |
3 | [中文](./README_ZH.md)
4 |
5 | ## Installation dependency
6 |
7 | ```shell
8 | pip install -r requirement.txt
9 | ```
10 |
11 | ## Run the program
12 |
13 | ```shell
14 | python main.py
15 | ```
16 |
17 | ## Program instructions
18 |
19 | There is a sequence requirement for opening the serial port: first open the serial port connection of myArmM, then open the serial port connection of myArmC.
20 |
21 | 
22 | 
23 |
24 | After both serial ports are opened, you can control the movement of myArmM by moving myArmC.
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/README_ZH.md:
--------------------------------------------------------------------------------
1 |
2 | # myArm M&C 控制案例
3 |
4 | [English](./README.md)
5 |
6 | ## 安装依赖
7 |
8 | ```shell
9 | pip install -r requirement.txt
10 | ```
11 |
12 | ## 运行程序
13 |
14 | ```shell
15 | python main.py
16 | ```
17 |
18 | ## 程序使用说明
19 |
20 | 串口的打开有顺序要求:先开启myArmM的串口连接,再开启myArmC的串口连接。
21 |
22 | 
23 | 
24 |
25 | 两个串口都开启以后就可以通过移动myArmC来控制myArmM运动。
26 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/get_date.py:
--------------------------------------------------------------------------------
1 |
2 | from pymycobot import MyArmC, MyArmM
3 |
4 | import time
5 | from PySide6.QtCore import QThread, Signal
6 |
7 | class CreateSerial(QThread):
8 | progress = Signal(dict)
9 |
10 | def __init__(self, port, index, parent_serial=None):
11 | super().__init__()
12 | if index in [1,2]:
13 | self.serial = MyArmC(port)
14 | else:
15 | self.serial = MyArmM(port)
16 | self.index = index
17 | self.parent_serial = parent_serial
18 | self.serial_type = self.serial.__class__.__name__
19 |
20 | def close(self):
21 | self.serial._serial_port.close()
22 |
23 |
24 | def open(self):
25 | self.serial._serial_port.open()
26 |
27 |
28 | def run(self) -> None:
29 | data = {"angle":[1,2,3,4,5,6,7,8], "speed":[1,2,3,4,5,6,7,8] , "acc": [1,2,3,4,5,6,7,8]}
30 | while True:
31 |
32 | try:
33 | if self.serial._serial_port.isOpen():
34 |
35 |
36 | if (self.index == 1 or self.index == 2) and self.parent_serial is not None and data["angle"] and data["speed"]:
37 | data["angle"] = self.serial.get_servos_encoder()
38 | data["speed"] = self.serial.get_servos_speed()
39 | data["angle"][3] = 4096 - data["angle"][3]
40 | data["angle"][-1] *= 1.1
41 | data["angle"][-1] = int(data["angle"][-1])
42 | if data["angle"][-1] > 2048:
43 | data["angle"][-1] = 2048
44 | # self.parent_serial.set_servos_encoder_drag(data["angle"], data["speed"])
45 | self.parent_serial.serial.set_servos_encoder(data["angle"], 100)
46 | else:
47 | data["angle"] = self.serial.get_servos_encoder()
48 | data["speed"] = self.serial.get_servos_speed()
49 | time.sleep(1)
50 | if data["angle"] and data["speed"]:
51 | self.progress.emit({str(self.index):data})
52 | except:
53 | pass
54 | time.sleep(0.0001)
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/requirement.txt:
--------------------------------------------------------------------------------
1 | PySide6==6.7.0
2 | pymycobot==3.4.6b1
3 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/resources/app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo/resources/app.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/resources/app_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo/resources/app_1.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/resources/app_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo/resources/app_2.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/resources/mystudio.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo/resources/mystudio.ico
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/ui/bt.py:
--------------------------------------------------------------------------------
1 | from PySide6.QtCore import *
2 | from PySide6.QtWidgets import *
3 | from PySide6.QtGui import *
4 |
5 |
6 | class SwitchButton(QCheckBox):
7 | status_button = Signal(bool)
8 |
9 | def __init__(
10 | self,
11 | width=60,
12 | bg_color="#777",
13 | circle_color="#ddd",
14 | active_color="#409eff",
15 | animation_curve=QEasingCurve.OutQuint
16 |
17 | ):
18 | QCheckBox.__init__(self)
19 |
20 | self.setFixedSize(width, 28)
21 | self.setCursor(Qt.PointingHandCursor)
22 |
23 | self._bg_corlor = bg_color
24 | self._circle_color = circle_color
25 | self._active_color = active_color
26 |
27 | self.stateChanged.connect(self.start_transition)
28 |
29 | self._circle_position = 3
30 | self.animation = QPropertyAnimation(self, b"circle_position", self)
31 | self.animation.setEasingCurve(animation_curve)
32 | self.animation.setDuration(500)
33 |
34 | @Property(float)
35 | def circle_position(self):
36 | return self._circle_position
37 |
38 | @circle_position.setter
39 | def circle_position(self, pos):
40 | self._circle_position = pos
41 | self.update()
42 |
43 | def reset_state(self):
44 | self.setChecked(False)
45 | self.animation.setEndValue(3)
46 |
47 | def start_transition(self, value):
48 | # print(f'status:{self.isChecked()}')
49 |
50 | # print(value, "value")
51 |
52 | self.animation.stop()
53 |
54 | if value:
55 | self.animation.setEndValue(self.width()-25)
56 | self.status_button.emit(True)
57 | else:
58 | self.animation.setEndValue(3)
59 | self.status_button.emit(False)
60 |
61 | self.animation.start()
62 |
63 | def hitButton(self, pos: QPoint):
64 | return self.contentsRect().contains(pos)
65 |
66 | def paintEvent(self, e):
67 | # pass
68 | p = QPainter(self)
69 | p.setRenderHint(QPainter.Antialiasing)
70 |
71 | p.setPen(Qt.NoPen)
72 |
73 | rect = QRect(0, 0, self.width(), self.height())
74 |
75 | if self.isChecked():
76 |
77 | p.setBrush(QColor(self._active_color))
78 | p.drawRoundedRect(0, 0, rect.width(), self.height(),
79 | self.height()/2, self.height()/2)
80 |
81 | p.setBrush(QColor(self._circle_color))
82 | p.drawEllipse(self._circle_position, 3, 22, 22)
83 |
84 | else:
85 |
86 | p.setBrush(QColor(self._bg_corlor))
87 | p.drawRoundedRect(0, 0, rect.width(), self.height(),
88 | self.height()/2, self.height()/2)
89 |
90 | p.setBrush(QColor(self._circle_color))
91 |
92 | p.drawEllipse(self.circle_position, 3, 22, 22)
93 |
94 | p.end()
95 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo/utils.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | import socket
4 | import typing as T
5 | from serial.tools import list_ports
6 | _T = T.TypeVar("_T")
7 |
8 |
9 | def select(
10 | message: str,
11 | options: T.List[_T],
12 | default: int = None,
13 | level: int = 1,
14 | echo: T.Callable = lambda msg: msg,
15 | start: int = 1
16 | ) -> T.Optional[_T]:
17 | print(f"{message}\r\n")
18 | p = " " * level
19 | for ordinal, option in enumerate(options, start=start):
20 | print(f"{p}{ordinal}. {echo(option)}")
21 | else:
22 | print()
23 |
24 | tips = f" # (Info) Select ({echo(options[default - 1])}) >" if default is not None else f" # (Info) Select: "
25 |
26 | while True:
27 | try:
28 | user_input = input(f"{tips}").lower().strip()
29 | if len(user_input) == 0 and (default is not None or len(options) == 1):
30 | return options[default - 1]
31 |
32 | if user_input.isdigit():
33 | return options[int(user_input) - 1]
34 |
35 | if user_input in options:
36 | return user_input
37 |
38 | if user_input in ("q", "quit"):
39 | return None
40 |
41 | raise ValueError
42 | except ValueError:
43 | print(f" * Invalid input, please enter a number.")
44 |
45 | except IndexError:
46 | print(f" * Invalid input, please enter a valid number.")
47 |
48 |
49 | def get_local_serial_port(): # 获取所有串口号
50 | return [comport.device for comport in list_ports.comports()]
51 |
52 |
53 | def get_local_host():
54 | hostname = socket.gethostname()
55 | ip_address = socket.gethostbyname(hostname)
56 | return ip_address
57 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/README.md:
--------------------------------------------------------------------------------
1 | # myArm M&C control case
2 |
3 | [中文](./README_ZH.md)
4 |
5 | ## Installation dependency
6 |
7 | ```shell
8 | pip install -r requirement.txt
9 | ```
10 |
11 | ## Run the program
12 |
13 | ```shell
14 | python main.py
15 | ```
16 |
17 | ## Program instructions
18 |
19 | There is a sequence requirement for opening the serial port: first open the serial port connection of myArmM, then open the serial port connection of myArmC.
20 |
21 | 
22 | 
23 |
24 | After both serial ports are opened, you can control the movement of myArmM by moving myArmC.
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/README_ZH.md:
--------------------------------------------------------------------------------
1 |
2 | # myArm M&C 控制案例
3 |
4 | [English](./README.md)
5 |
6 | ## 安装依赖
7 |
8 | ```shell
9 | pip install -r requirement.txt
10 | ```
11 |
12 | ## 运行程序
13 |
14 | ```shell
15 | python main.py
16 | ```
17 |
18 | ## 程序使用说明
19 |
20 | 串口的打开有顺序要求:先开启myArmM的串口连接,再开启myArmC的串口连接。
21 |
22 | 
23 | 
24 |
25 | 两个串口都开启以后就可以通过移动myArmC来控制myArmM运动。
26 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/get_date.py:
--------------------------------------------------------------------------------
1 |
2 | from pymycobot import MyArmC, MyArmM
3 | from pymycobot.robot_info import RobotLimit
4 |
5 | import time
6 | from PySide6.QtCore import QThread, Signal
7 |
8 | class CreateSerial(QThread):
9 | progress = Signal(dict)
10 |
11 | def __init__(self, port, index, parent_serial=None):
12 | super().__init__()
13 | if index in [1,2]:
14 | self.serial = MyArmC(port, 1000000)
15 | else:
16 | self.serial = MyArmM(port, 1000000)
17 | self.index = index
18 | self.parent_serial = parent_serial
19 | self.serial_type = self.serial.__class__.__name__
20 |
21 | def close(self):
22 | self.serial._serial_port.close()
23 |
24 |
25 | def open(self):
26 | self.serial._serial_port.open()
27 |
28 |
29 | def run(self) -> None:
30 | data = {"angle":[1,2,3,4,5,6,7,8], "speed":[1,2,3,4,5,6,7,8] , "acc": [1,2,3,4,5,6,7,8]}
31 | while True:
32 |
33 | try:
34 | if self.serial._serial_port.isOpen():
35 |
36 |
37 | if (self.index == 1 or self.index == 2) and self.parent_serial is not None and data["angle"] and data["speed"]:
38 | data["angle"] = self.serial.get_joints_angle()
39 | data["angle"][-1] = round((data["angle"][-1] - 0.08) / (-95.27 - 0.08) * (-123.13 + 1.23) - 1.23, 2)
40 | if data["angle"][-1] > 2:
41 | data["angle"][-1] = 2
42 | elif data["angle"][-1] < -118:
43 | data["angle"][-1] = -118
44 | for i in range(len(data["angle"])):
45 | if data["angle"][i] > 0 and (RobotLimit.robot_limit["MyArmM"]["angles_max"][i] - data["angle"][i]) < 5:
46 | data["angle"][i] = RobotLimit.robot_limit["MyArmM"]["angles_max"][i] - 5
47 | elif data["angle"][i] < 0 and (data["angle"][i] - RobotLimit.robot_limit["MyArmM"]["angles_min"][i]) < 5:
48 | data["angle"][i] = RobotLimit.robot_limit["MyArmM"]["angles_min"][i] + 5
49 | self.parent_serial.serial.set_joints_angle(data["angle"], 100)
50 | else:
51 | # data["angle"] = self.serial.get_servos_encoder()
52 | # data["speed"] = self.serial.get_servos_speed()
53 | time.sleep(1)
54 | self.progress.emit({str(self.index):data})
55 | # if data["angle"]:
56 | # self.progress.emit({str(self.index):data})
57 | except:
58 | pass
59 | time.sleep(0.0001)
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/myarm_c.py:
--------------------------------------------------------------------------------
1 | # 读取myarm_c的角度并发送
2 | import socket
3 | from pymycobot import MyArmC, MyArmM
4 | import serial.tools.list_ports
5 | import time
6 |
7 | def get_port(): # 获取所有串口号
8 | port_list = serial.tools.list_ports.comports()
9 | i = 1
10 | res = {}
11 | for port in port_list:
12 | print("{} - {}".format(i, port.device))
13 | res[str(i)] = port.device
14 | i += 1
15 | return res
16 |
17 | def main():
18 | port_dict = get_port()
19 | print("Note: After the program is started, the M750 will follow the C650 to do the same action. Please place the two machines in the same position to avoid sudden swinging of the machines.")
20 | port_c = input("input myArm C port: ")
21 | c_port = port_dict[port_c]
22 | c = MyArmC(c_port, debug=False)
23 | HOST = '127.0.0.1'
24 | PORT = 8001
25 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26 | # 请求连接
27 | client.connect((HOST, PORT))
28 | while True:
29 | angle = c.get_joints_angle()
30 | if angle is not None:
31 | data = '\n' + str(angle)
32 | client.send(data.encode('utf-8'))
33 |
34 | if __name__ == "__main__":
35 | main()
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/myarm_m.py:
--------------------------------------------------------------------------------
1 | # myarm_m接收角度并执行
2 | from pymycobot.error import MyArmDataException
3 | from pymycobot import MyArmC, MyArmM
4 | import serial.tools.list_ports
5 | import time
6 | import socket
7 | from pymycobot.robot_info import RobotLimit
8 |
9 | def get_port(): # 获取所有串口号
10 | port_list = serial.tools.list_ports.comports()
11 | i = 1
12 | res = {}
13 | for port in port_list:
14 | print("{} - {}".format(i, port.device))
15 | res[str(i)] = port.device
16 | i += 1
17 | return res
18 |
19 | def processing_data(data):
20 | data = data.split('\n')[-1]
21 | angle = list(data[1:-1].split(','))
22 | angle = [float(i) for i in angle]
23 | # angle[2] *= -1
24 | gripper_angle = angle.pop(-1)
25 | angle.append((gripper_angle - 0.08) / (-95.27 - 0.08) * (-123.13 + 1.23) - 1.23)
26 | return angle
27 |
28 | def main():
29 | HOST = '127.0.0.1'
30 | PORT = 8001
31 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
32 | server.bind((HOST, PORT))
33 | server.listen(5)
34 | port_dict = get_port()
35 | print("Note: After the program is started, the M750 will follow the C650 to do the same action. Please place the two machines in the same position to avoid sudden swinging of the machines.")
36 | port_m = input("input myArm M port: ")
37 | m_port = port_dict[port_m]
38 | m = MyArmM(m_port, 1000000, debug=False)
39 | speed = 100
40 |
41 | print('Server start at: %s:%s' % (HOST, PORT))
42 | print('wait for connection...')
43 | # 接收客户端请求
44 |
45 | while True:
46 | conn, addr = server.accept()
47 | # 客户端IP
48 | print('Connected by ', addr)
49 | while True:
50 | try:
51 | data = conn.recv(1024).decode('utf-8')
52 | angle = processing_data(data)
53 | for i in range(len(angle)):
54 | if angle[i] > 0 and (RobotLimit.robot_limit["MyArmM"]["angles_max"][i] - angle[i]) < 5:
55 | angle[i] = RobotLimit.robot_limit["MyArmM"]["angles_max"][i] - 5
56 | elif angle[i] < 0 and (angle[i] - RobotLimit.robot_limit["MyArmM"]["angles_min"][i]) < 5:
57 | angle[i] = RobotLimit.robot_limit["MyArmM"]["angles_min"][i] + 5
58 | m.set_joints_angle(angle, speed)
59 | except MyArmDataException:
60 | pass
61 |
62 |
63 | if __name__ == "__main__":
64 | main()
65 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/requirement.txt:
--------------------------------------------------------------------------------
1 | PySide6==6.7.0
2 | pymycobot==3.4.6b1
3 |
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/resources/app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo_v1.1/resources/app.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/resources/app_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo_v1.1/resources/app_1.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/resources/app_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo_v1.1/resources/app_2.png
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/resources/mystudio.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_M&C_demo_v1.1/resources/mystudio.ico
--------------------------------------------------------------------------------
/demo/myArm_M&C_demo_v1.1/ui/bt.py:
--------------------------------------------------------------------------------
1 | from PySide6.QtCore import *
2 | from PySide6.QtWidgets import *
3 | from PySide6.QtGui import *
4 |
5 |
6 | class SwitchButton(QCheckBox):
7 | status_button = Signal(bool)
8 |
9 | def __init__(
10 | self,
11 | width=60,
12 | bg_color="#777",
13 | circle_color="#ddd",
14 | active_color="#409eff",
15 | animation_curve=QEasingCurve.OutQuint
16 |
17 | ):
18 | QCheckBox.__init__(self)
19 |
20 | self.setFixedSize(width, 28)
21 | self.setCursor(Qt.PointingHandCursor)
22 |
23 | self._bg_corlor = bg_color
24 | self._circle_color = circle_color
25 | self._active_color = active_color
26 |
27 | self.stateChanged.connect(self.start_transition)
28 |
29 | self._circle_position = 3
30 | self.animation = QPropertyAnimation(self, b"circle_position", self)
31 | self.animation.setEasingCurve(animation_curve)
32 | self.animation.setDuration(500)
33 |
34 | @Property(float)
35 | def circle_position(self):
36 | return self._circle_position
37 |
38 | @circle_position.setter
39 | def circle_position(self, pos):
40 | self._circle_position = pos
41 | self.update()
42 |
43 | def reset_state(self):
44 | self.setChecked(False)
45 | self.animation.setEndValue(3)
46 |
47 | def start_transition(self, value):
48 | # print(f'status:{self.isChecked()}')
49 |
50 | # print(value, "value")
51 |
52 | self.animation.stop()
53 |
54 | if value:
55 | self.animation.setEndValue(self.width()-25)
56 | self.status_button.emit(True)
57 | else:
58 | self.animation.setEndValue(3)
59 | self.status_button.emit(False)
60 |
61 | self.animation.start()
62 |
63 | def hitButton(self, pos: QPoint):
64 | return self.contentsRect().contains(pos)
65 |
66 | def paintEvent(self, e):
67 | # pass
68 | p = QPainter(self)
69 | p.setRenderHint(QPainter.Antialiasing)
70 |
71 | p.setPen(Qt.NoPen)
72 |
73 | rect = QRect(0, 0, self.width(), self.height())
74 |
75 | if self.isChecked():
76 |
77 | p.setBrush(QColor(self._active_color))
78 | p.drawRoundedRect(0, 0, rect.width(), self.height(),
79 | self.height()/2, self.height()/2)
80 |
81 | p.setBrush(QColor(self._circle_color))
82 | p.drawEllipse(self._circle_position, 3, 22, 22)
83 |
84 | else:
85 |
86 | p.setBrush(QColor(self._bg_corlor))
87 | p.drawRoundedRect(0, 0, rect.width(), self.height(),
88 | self.height()/2, self.height()/2)
89 |
90 | p.setBrush(QColor(self._circle_color))
91 |
92 | p.drawEllipse(self.circle_position, 3, 22, 22)
93 |
94 | p.end()
95 |
--------------------------------------------------------------------------------
/demo/myArm_demo/.xiaqi.py.swp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/myArm_demo/.xiaqi.py.swp
--------------------------------------------------------------------------------
/demo/myArm_demo/all_run_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding:utf-8 -*-
3 | # @File : all_run_test.py
4 | # @Author : Wang Weijian
5 | # @Time : 2023/07/11 15:38:45
6 | # @function: the script is used to do something
7 | # @version : V1
8 |
9 | import time
10 | from pymycobot.myarm import MyArm
11 |
12 | mc = MyArm('/dev/ttyAMA0')
13 |
14 | init_angles = [
15 | [90, 0, 0, 0, 0, 0, 0], # zero point
16 | [-90, 0, 0, -90, 0, -90, 0], # first init point
17 | [90, 0, 0, -90, 0, -90, 0], # second init point
18 | [0, 80, 0, 0, 0, 0, 0], # four
19 | [-150, 80, 0, 0, 0, 0, 0],
20 | [150, 80, 0, 0, 0, 0, 0], # 6
21 | [155.12, -79.27, -0.26, 76.46, 5.71, 45.0, -0.08], # 7
22 | [-29.53, -48.11, 165, -89.2, 0.41, -43.56, 0.35], # 8
23 | [87.62, 80, 165, -82.96, 165, -73.38, 0.26], # 9
24 | [-114.16, 80, 165, -82.96, 165, -104.58, 0.26], # 10
25 | [17.84, -2.1, 165, -100, 165, 64.16, -6.24], # 11
26 | [-11.07, -11.68, 2.1, -93.42, 3.07, -9.14, -45.35], # 12
27 | [-19.68, -16.96, -165, -84.28, -161.19, 1.05, -43.76] , # 13
28 | [-108.89, -78.39, -165, -89.64, 165, 110, -0.7], # 14
29 | [160.57, -78.92, 165, -84.63, -163.3, 1.05, -43.76], # 15
30 | ]
31 |
32 | low_speed = 10
33 | medium_speed = 50
34 | high_speed = 100
35 | timet = int(3)
36 |
37 |
38 | def main():
39 | """
40 | 体现myarm三种不同速度的多种运动姿态
41 | :return: None
42 | """
43 | mc.send_angles(init_angles[0], medium_speed)
44 | time.sleep(3+timet)
45 |
46 | mc.send_angles(init_angles[1], low_speed)
47 | time.sleep(10+timet)
48 |
49 | mc.send_angles(init_angles[2], high_speed)
50 | time.sleep(2+timet)
51 |
52 | mc.send_angles(init_angles[3], high_speed)
53 | time.sleep(4+timet)
54 | mc.send_angles(init_angles[4], high_speed)
55 | time.sleep(4.5+timet)
56 | mc.send_angles(init_angles[5], high_speed)
57 | time.sleep(6+timet)
58 | mc.send_angles(init_angles[6], medium_speed)
59 | time.sleep(4+timet)
60 | mc.send_angles(init_angles[7], medium_speed)
61 | time.sleep(8+timet)
62 | mc.send_angles(init_angles[8], medium_speed)
63 | time.sleep(4+timet)
64 | mc.send_angles(init_angles[9], high_speed)
65 | time.sleep(4+timet)
66 | mc.send_angles(init_angles[10], high_speed)
67 | time.sleep(4+timet)
68 | mc.send_angles(init_angles[11], high_speed)
69 | time.sleep(4+timet)
70 | mc.send_angles(init_angles[12], high_speed)
71 | time.sleep(4+timet)
72 | mc.send_angles(init_angles[13], medium_speed)
73 | time.sleep(8+timet)
74 | mc.send_angles(init_angles[14], high_speed)
75 | time.sleep(5+timet)
76 | mc.send_angles(init_angles[0], medium_speed)
77 | time.sleep(7.5+timet)
78 |
79 |
80 |
81 | if __name__ == '__main__':
82 | main()
83 |
--------------------------------------------------------------------------------
/demo/myArm_demo/dexterous_hands.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | """
3 | File : dexterous_hands.py
4 | Time : 2023/11/16
5 | Function: This script is used to control the switch of the dexterous hand of the robot arm end effector.
6 | Atom Version: V1.1
7 | pymycobot Version: 3.3.0
8 | """
9 | import time
10 | from pymycobot.myarm import MyArm
11 |
12 | # Initialize the MyArm object with the appropriate port
13 | ma = MyArm('/dev/ttyAMA0')
14 |
15 | # Perform dexterity hand switch action 3 times
16 | for i in range(3):
17 | # Open the gripper (0 represents open dexterous hand gripper, 80 represents speed, and 2 represents dexterous hand type.)
18 | ma.set_gripper_state(0, 80, 2)
19 | # Wait for 2 seconds
20 | time.sleep(2)
21 |
22 | # Close the gripper (1 represents close dexterous hand gripper, 80 represents speed, and 2 represents dexterous hand type.)
23 | ma.set_gripper_state(1, 80, 2)
24 | # Wait for 2 seconds
25 | time.sleep(2)
26 |
--------------------------------------------------------------------------------
/demo/myArm_demo/four_piece_chess.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 | mc = MyArm('/dev/ttyAMA0')
5 | time.sleep(0.1)
6 |
7 |
8 | def main():
9 | """
10 | 模仿myarm与人类下棋输赢状态的动作
11 | :return: None
12 | """
13 | init_angles = [
14 | [-60, 0, 0, -90, 0, -90, -0.79], # first init point
15 | # [0, 49, 0, -104, 0, -45, -0.79], # second init point
16 | [0, -49, 0, -100, 0, -45, -0.79],
17 | # [-0.26, 2.0, 0.43, -111.0, 0.43, 20.22, -0.79], # third
18 | [-3.16, -11.77, 0.17, -100, -0.52, -3.25, 1.23], # third
19 | [3.25, -8.61, 0.17, -99.14, 1.14, -2.81, -0.79], # left
20 | [-10.01, -6.85, 0.17, -99.49, -2.63, -2.81, 3.07], # right
21 | ]
22 |
23 | # mc.send_angles(init_angles[0], 50)
24 |
25 | # time.sleep(3)
26 |
27 | # mc.send_angles(init_angles[1], 50)
28 | # time.sleep(3)
29 |
30 | # mc.send_angles(init_angles[2], 50)
31 | # time.sleep(3)
32 | # mc.set_gservo_round(12)
33 | # time.sleep(1.5)
34 |
35 | # for i in range(5):
36 |
37 | mc.send_angles(init_angles[2], 50)
38 | time.sleep(2.5)
39 | mc.set_gservo_round(12)
40 | time.sleep(1.5)
41 | mc.send_angles(init_angles[1], 50)
42 | time.sleep(3)
43 | for i in range(3):
44 | mc.send_angles([0, -49, 0, -100, 0, -65, -0.79], 90)
45 | time.sleep(1)
46 | mc.send_angles([0, -49, 0, -100, 0, -25, -0.79], 90)
47 | time.sleep(1)
48 | # mc.send_angles(init_angles[1], 50)
49 | # time.sleep(3)
50 |
51 | # mc.send_angles(init_angles[2], 50)
52 | # time.sleep(3)
53 | # mc.set_gservo_round(12)
54 | # time.sleep(1.5)
55 | # mc.send_angles(init_angles[1], 50)
56 | # time.sleep(3)
57 |
58 | # mc.send_angles(init_angles[2], 50)
59 | # time.sleep(3)
60 | # mc.set_gservo_round(12)
61 | # time.sleep(1.5)
62 | # mc.send_angles(init_angles[1], 50)
63 | # time.sleep(3)
64 |
65 |
66 | # mc.send_angles([0.26, -2.0, 0.43, -100.0, 0.43, 20.22, -0.79], 50)
67 | # time.sleep(3)
68 |
69 | # win
70 | # for i in range(5):
71 | # mc.send_angles([0.0, -0.34, 0.17, -100.62, 0.17, 20.29, 0.08], 90)
72 | # time.sleep(1)
73 | # mc.send_angles([0.0, -0.34, 0.17, -100.62, 0.17, 20.29, 0.08], 90)
74 | # time.sleep(1)
75 | # print(init_angles[2])
76 |
77 | # mc.send_angles(init_angles[2], 50)
78 | # time.sleep(3)
79 | # fail
80 | # mc.send_angles([0.0, -18.34, 0.17, -100.62, 0.17, -7.29, 0.08], 50)
81 | # time.sleep(3)
82 | # mc.send_angles([0.0, -18.34, 0.17, -100.62, 0.17, -26.29, 0.08], 5)
83 | # time.sleep(7)
84 | # mc.send_angle(4, -80, 30)
85 | # time.sleep(3)
86 |
87 |
88 | # mc.send_angles(init_angles[2], 50)
89 | # time.sleep(3)
90 |
91 | if __name__ == '__main__':
92 | main()
93 |
--------------------------------------------------------------------------------
/demo/myArm_demo/gripper_aikit_v2.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 |
5 | mc = MyArm('/dev/ttyAMA0')
6 |
7 |
8 | init_angles = [
9 | [-60, 0, 0, -90, 0, -90, 0], # first init point
10 | [0, 0, 0, -90, 0, -90, 0], # second init point
11 | ]
12 |
13 | box_angles = [
14 | [-47.9, 17.31, 0.17, -89.91, -0.17, -56.07, 0.0], # D
15 | [-27.59, 44.82, -1.75, -48.95, 0.0, -55.89, -0.0], # C
16 | [52.99, 18.36, -1.4, -86.57, -0.17, -55.89, -0.0], # A
17 | [87.97, 18.28, -1.4, -86.57, -0.35, -71.19, -0.0], # B
18 | ]
19 |
20 |
21 | # 开启
22 | def gripper_on():
23 | mc.set_gripper_state(0, 100)
24 | time.sleep(0.5)
25 |
26 |
27 | # 关闭
28 | def gripper_off():
29 | mc.set_gripper_state(1, 100)
30 | time.sleep(0.5)
31 |
32 |
33 | def move():
34 | """
35 | myarm使用夹爪模拟aikitV2套装抓取木块
36 | """
37 | mc.send_angles(init_angles[0], 50)
38 | time.sleep(3)
39 |
40 | mc.send_angles(init_angles[1], 50)
41 | time.sleep(3)
42 | gripper_on()
43 | mc.send_angles([0.0, 26.27, 0.17, -72.86, -0.17, -77.51, 0.0], 50)
44 | time.sleep(3)
45 |
46 | # mc.send_angles([0.0, -47.63, 0.17, -77.43, 0.08, -55.72, 0.0], 50)
47 | mc.send_angles([-2.02, 41.74, 0.43, -86.13, -0.17, -46.05, 0.0], 50)
48 |
49 |
50 | time.sleep(3)
51 |
52 | gripper_off()
53 | time.sleep(2)
54 | tmp = []
55 | while True:
56 | if not tmp:
57 | tmp = mc.get_angles()
58 | else:
59 | break
60 | time.sleep(0.5)
61 | tmp[6] = 0.0
62 | print(tmp)
63 | mc.send_angles([tmp[0], 0, 0, -90, -0.0, -90, tmp[6]], 50)
64 | # mc.send_angles([0, 0, 0, -90, 0, -90, 0], 50)
65 | time.sleep(3)
66 | mc.send_angles(box_angles[3], 50)
67 | time.sleep(4)
68 | gripper_on()
69 | time.sleep(2)
70 | mc.send_angles(init_angles[0], 50)
71 | time.sleep(4)
72 |
73 |
74 | if __name__ == '__main__':
75 | gripper_off()
76 | move()
77 |
--------------------------------------------------------------------------------
/demo/myArm_demo/hand_gripper.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 | mc = MyArm('/dev/ttyAMA0', debug=False)
5 | time.sleep(0.1)
6 |
7 | mc.set_fresh_mode(0)
8 | time.sleep(0.2)
9 |
10 | mc.set_servo_data(7, 5, 8)
11 | time.sleep(0.1)
12 |
13 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
14 | time.sleep(3)
15 |
16 | def main():
17 |
18 | #mc.send_angles([-57.65, 35.24, -0.17, -68.11, 0.0, 14.76, 135.0], 50)
19 | #print(mc.get_error_information())
20 | #exit()
21 | mc.send_angles([-58.88, 34.27, -0.43, -67.5, -0.35, 20.2, 0.0], 60)
22 | time.sleep(2.5)
23 |
24 | for i in range(4):
25 | mc.set_solution_angles(70, 20)
26 |
27 | time.sleep(2.5)
28 | mc.set_solution_angles(-70, 20)
29 | time.sleep(2.5)
30 |
31 |
32 | mc.send_angles([-58.88, 34.27, -0.43, -67.5, -0.35, 20.2, 0.0], 60)
33 | time.sleep(2.5)
34 |
35 | time.sleep(5)
36 |
37 | # two action
38 | mc.send_angles([-90, 0, 0.0, -90, 0, 0, -30], 60)
39 | time.sleep(2.5)
40 |
41 | for i in range(4):
42 | mc.send_angle(7, -65, 50)
43 | time.sleep(2)
44 | mc.set_encoder(8, 2450)
45 | time.sleep(2)
46 | mc.send_angle(7, 35, 50)
47 | time.sleep(2)
48 | mc.set_encoder(8, 2000)
49 | time.sleep(2)
50 |
51 | mc.send_angles([-90, 0.87, -0.08, -90.79, 0.35, 0.26, -30], 50)
52 | time.sleep(2.5)
53 |
54 | time.sleep(5)
55 | # three action
56 | mc.send_angles([-90, 0, 0, 0, 0, 0, 40], 60)
57 | time.sleep(2.5)
58 |
59 | for i in range(4):
60 | mc.send_angle(4, 45, 95)
61 | time.sleep(1.5)
62 | mc.send_angle(4, -45, 95)
63 | time.sleep(1.5)
64 |
65 | for i in range(4):
66 | mc.send_angle(4, 45, 20)
67 | time.sleep(2.5)
68 | mc.send_angle(4, -45, 20)
69 | time.sleep(2.5)
70 | mc.send_angles([-90, 0, 0, 0, 0, 0, 40], 50)
71 | time.sleep(2.5)
72 |
73 | i = 0
74 | while i <1:
75 | main()
76 | i+=1
77 |
78 |
--------------------------------------------------------------------------------
/demo/myArm_demo/myarm_agv_demo.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 |
5 | mc = MyArm('/dev/ttyAMA0')
6 |
7 | init_angles = [
8 | [-60, 0, 0, -90, 0, -90, 0], # first init point
9 | [0, 0, 0, -90, 0, -90, 0], # second init point
10 | ]
11 |
12 | box_angles = [
13 | [-47.9, -17.31, 0.17, -89.91, -0.17, -56.07, 0.0], # D
14 | [-27.59, -44.82, -1.75, -48.95, 0.0, -55.89, -0.0], # C
15 | [52.99, -18.36, -1.4, -86.57, -0.17, -55.89, -0.0], # A
16 | [87.97, -18.28, -1.4, -86.57, -0.35, -71.19, -0.0], # B
17 | ]
18 |
19 |
20 | # 开启
21 | def gripper_on():
22 | mc.set_gripper_state(0, 100)
23 | time.sleep(0.5)
24 |
25 |
26 | # 关闭
27 | def gripper_off():
28 | mc.set_gripper_state(1, 100)
29 | time.sleep(0.5)
30 |
31 |
32 | def move():
33 | """
34 | myarm使用夹爪模拟aikitV2套装抓取木块
35 | """
36 | mc.send_angles(init_angles[0], 50)
37 | time.sleep(3)
38 |
39 | mc.send_angles(init_angles[1], 50)
40 | time.sleep(3)
41 | gripper_on()
42 | mc.send_angles([0.0, -26.27, 0.17, -72.86, -0.17, -77.51, 0.0], 50)
43 | time.sleep(3)
44 |
45 | # mc.send_angles([0.0, -47.63, 0.17, -77.43, 0.08, -55.72, 0.0], 50)
46 | mc.send_angles([-2.02, -41.74, 0.43, -86.13, -0.17, -46.05, 0.0], 50)
47 |
48 |
49 | time.sleep(3)
50 |
51 | gripper_off()
52 | time.sleep(2)
53 | tmp = []
54 | while True:
55 | if not tmp:
56 | tmp = mc.get_angles()
57 | else:
58 | break
59 | time.sleep(0.5)
60 | tmp[6] = 0.0
61 | print(tmp)
62 | mc.send_angles([tmp[0], 0, 0, -90, -0.0, -90, tmp[6]], 50)
63 | # mc.send_angles([0, 0, 0, -90, 0, -90, 0], 50)
64 | time.sleep(3)
65 | mc.send_angles(box_angles[3], 50)
66 | time.sleep(4)
67 | gripper_on()
68 | time.sleep(2)
69 | mc.send_angles(init_angles[0], 50)
70 | time.sleep(4)
71 |
72 |
73 | if __name__ == '__main__':
74 | gripper_off()
75 | move()
76 |
--------------------------------------------------------------------------------
/demo/myArm_demo/pump_aikit_v2.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 | import RPi.GPIO as GPIO
4 |
5 | mc = MyArm('/dev/ttyAMA0')
6 |
7 | # 初始化
8 | GPIO.setmode(GPIO.BCM)
9 | # 引脚20/21分别控制电磁阀和泄气阀门
10 | GPIO.setup(20, GPIO.OUT)
11 | GPIO.setup(21, GPIO.OUT)
12 |
13 | init_angles = [
14 | [-60, 0, 0, -90, 0, -90, 0], # first init point
15 | [0, 0, 0, -90, 0, -90, 0], # second init point
16 | ]
17 |
18 | box_angles = [
19 | [-47.9, 17.31, 0.17, -89.91, -0.17, -56.07, 0.0], # D
20 | [-27.59, 44.82, -1.75, -48.95, 0.0, -55.89, -0.08], # C
21 | [52.99, 18.36, -1.4, -86.57, -0.17, -55.89, -0.08], # A
22 | [87.97, 18.28, -1.4, -86.57, -0.35, -71.19, -0.08], # B
23 | ]
24 |
25 |
26 | # 开启吸泵
27 | def pump_on():
28 | # 打开电磁阀
29 | GPIO.output(20, 0)
30 |
31 |
32 | # 停止吸泵
33 | def pump_off():
34 | # 关闭电磁阀
35 | GPIO.output(20, 1)
36 | time.sleep(0.05)
37 | # 打开泄气阀门
38 | GPIO.output(21, 0)
39 | time.sleep(1)
40 | GPIO.output(21, 1)
41 | time.sleep(0.05)
42 |
43 |
44 | def move():
45 | """
46 | myarm使用吸泵模拟aikitV2套装抓取木块
47 | """
48 | #mc.send_angles(init_angles[0], 50)
49 | #time.sleep(3)
50 |
51 | mc.send_angles(init_angles[1], 50)
52 | time.sleep(3)
53 |
54 | #mc.send_angles([0, 22, 0, -70, 0, -82, 0], 30)
55 | mc.send_coords([176.3, -1.5, 201.3, -179.89, 3.6, 179.49], 30)
56 | time.sleep(3)
57 |
58 | #mc.send_angles([-0.35, 37.79, -0.7, -90.43, -0.35, -45.96, -0.26], 30)
59 | mc.send_coords([177.8, -3.5, 114, -179.26, 5.79, 179.64], 30)
60 | time.sleep(2.5)
61 | pump_on()
62 | time.sleep(3)
63 | tmp = []
64 | while True:
65 | if not tmp:
66 | tmp = mc.get_angles()
67 | else:
68 | break
69 | time.sleep(0.5)
70 | mc.send_angles([tmp[0], 0, 0, -90, -0.79, -90, tmp[6]], 50)
71 | # mc.send_angles([0, 0, 0, -90, 0, -90, 0], 50)
72 | time.sleep(4)
73 | mc.send_angles(box_angles[3], 50)
74 | time.sleep(4)
75 | pump_off()
76 | time.sleep(2)
77 | mc.send_angles(init_angles[0], 50)
78 | time.sleep(4)
79 |
80 |
81 | if __name__ == '__main__':
82 | pump_off()
83 | move()
84 |
--------------------------------------------------------------------------------
/demo/myArm_demo/pump_test.py:
--------------------------------------------------------------------------------
1 | from pymycobot.myarm import MyArm
2 | import time
3 | import RPi.GPIO as GPIO
4 |
5 | # 初始化一个MyCobot对象
6 | mc = MyArm('/dev/ttyAMA0')
7 |
8 | # 初始化
9 | GPIO.setmode(GPIO.BCM)
10 | # 引脚20/21分别控制电磁阀和泄气阀门
11 | GPIO.setup(20, GPIO.OUT)
12 | GPIO.setup(21, GPIO.OUT)
13 |
14 |
15 | # 开启吸泵
16 | def pump_on():
17 | # 打开电磁阀
18 | GPIO.output(20, 0)
19 |
20 |
21 | # 停止吸泵
22 | def pump_off():
23 | # 关闭电磁阀
24 | GPIO.output(20, 1)
25 | time.sleep(0.05)
26 | # 打开泄气阀门
27 | GPIO.output(21, 0)
28 | time.sleep(1)
29 | GPIO.output(21, 1)
30 | time.sleep(0.05)
31 |
32 |
33 | pump_on()
34 | time.sleep(6)
35 | pump_off()
36 | time.sleep(3)
37 |
--------------------------------------------------------------------------------
/demo/myArm_demo/rgb_led.py:
--------------------------------------------------------------------------------
1 | import time
2 | import math
3 | from pymycobot.myarm import MyArm
4 |
5 | mc = MyArm('/dev/ttyAMA0', debug=False)
6 | time.sleep(0.1)
7 |
8 | mc.send_angles([90, 0, 0, 0, 0, 0, 0], 50)
9 | time.sleep(3)
10 |
11 |
12 | # mc.set_color(255, 0, 0)
13 | # time.sleep(1)
14 | # mc.set_color(128, 0, 0)
15 | # time.sleep(1)
16 | # mc.set_color(32, 0, 0)
17 | # time.sleep(1)
18 |
19 | def breathing_led(mc, duration):
20 | min_brightness = 0
21 | max_brightness = 255
22 | speed = 0.01
23 |
24 | period = 2 * math.pi
25 |
26 | colors = [(0, 255, 0), (255, 0, 0), (0, 0, 255)]
27 |
28 | while True:
29 | for color in colors:
30 | start_time = time.time()
31 | while time.time() - start_time < duration:
32 | elapsed_time = time.time() - start_time
33 | phase = (elapsed_time * 2 * math.pi / period) % (2 * math.pi)
34 |
35 | brightness = int(1 - (math.cos(phase)) / 2 * (max_brightness - min_brightness) + min_brightness)
36 | brightness = max(min(brightness, max_brightness), min_brightness)
37 | print('color:', brightness)
38 | # mc.set_color(brightness, 0, 0)
39 | r = color[0] * brightness // max_brightness
40 | g = color[1] * brightness // max_brightness
41 | b = color[2] * brightness // max_brightness
42 | mc.set_color(r, g, b)
43 | time.sleep(speed)
44 |
45 | # mc.set_color(0, 0, 0)
46 |
47 |
48 | duration = 6
49 |
50 | breathing_led(mc, duration)
51 |
--------------------------------------------------------------------------------
/demo/myArm_demo/rgb_test.py:
--------------------------------------------------------------------------------
1 | import time
2 | import math
3 | from pymycobot.myarm import MyArm
4 |
5 | mc = MyArm('/dev/ttyAMA0', debug=False)
6 | time.sleep(0.1)
7 |
8 | # mc.send_angle(1, 0, 80)
9 | # print(mc.get_angles(), mc.get_coords())
10 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 50)
11 | time.sleep(2.5)
12 |
13 |
14 | # mc.set_color(255, 0, 0)
15 | # time.sleep(1)
16 | # mc.set_color(128, 0, 0)
17 | # time.sleep(1)
18 | # mc.set_color(32, 0, 0)
19 | # time.sleep(1)
20 |
21 | def breathing_led(mc, duration):
22 | min_brightness = 0
23 | max_brightness = 255
24 | speed = 0.02
25 |
26 | period = 2 * math.pi
27 |
28 | while True:
29 | start_time = time.time()
30 | while time.time() - start_time < duration:
31 | elapsed_time = time.time() - start_time
32 | phase = (elapsed_time * 2 * math.pi / period) % (2 * math.pi)
33 |
34 | brightness = int(1 - (math.cos(phase)) / 2 * (max_brightness - min_brightness) + min_brightness)
35 | brightness = max(min(brightness, max_brightness), min_brightness)
36 | print('color:', brightness)
37 | mc.set_color(brightness, 0, 0)
38 | time.sleep(speed)
39 |
40 | mc.set_color(0, 0, 0)
41 |
42 |
43 | duration = 10
44 |
45 | breathing_led(mc, duration)
46 |
--------------------------------------------------------------------------------
/demo/myArm_demo/space_arm_angle.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | """
3 | File : space_arm_angle.py
4 | Time : 2023/11/16
5 | Function: The function of this script is to make the robot arm move with zero space deflection angle.
6 | Atom Version: V1.1
7 | pymycobot Version: 3.3.0
8 | """
9 |
10 | import time
11 | from pymycobot.myarm import MyArm
12 |
13 | # Create a MyArm object and specify the serial port '/dev/ttyAMA0'
14 | mc = MyArm('/dev/ttyAMA0')
15 |
16 | # Set interpolation mode
17 | mc.set_fresh_mode(0)
18 | # Wait for 0.5 seconds
19 | time.sleep(0.5)
20 |
21 | # Send the joint angle command to move the robotic arm to the initial position with a speed of 60
22 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
23 | # Wait for 2.5 seconds
24 | time.sleep(2.5)
25 |
26 | # Send the joint angle command to move the robotic arm to the specified position with a speed of 60
27 | mc.send_angles([-58.88, 34.27, -0.43, -67.5, -0.35, -76.2, 0.0], 60)
28 | # Wait for 2.5 seconds
29 | time.sleep(2.5)
30 |
31 | # Execute a series of actions in a loop, 3 times in total
32 | for i in range(3):
33 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
34 | mc.set_solution_angles(70, 20)
35 | time.sleep(2.5)
36 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
37 | mc.set_solution_angles(-70, 20)
38 | time.sleep(2.5)
39 |
40 | # Send the joint angle command to move the robotic arm to the specified position with a speed of 60
41 | mc.send_angles([-58.88, 34.27, -0.43, -67.5, -0.35, 20.2, 0.0], 60)
42 | time.sleep(2.5)
43 |
44 | # Execute a series of actions in a loop, 3 times in total
45 | for i in range(3):
46 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
47 | mc.set_solution_angles(70, 20)
48 | time.sleep(2.5)
49 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
50 | mc.set_solution_angles(-70, 20)
51 | time.sleep(2.5)
52 |
53 | # Send the joint angle command to move the robotic arm to the specified position with a speed of 60
54 | mc.send_angles([-58.88, 34.27, -0.43, -67.5, -0.35, 20.2, 0.0], 60)
55 |
56 | # Send the joint angle command to move the robotic arm to the specified position with a speed of 60
57 | mc.send_angles([40.25, 36.38, -0.52, -67.23, 0.26, -76.37, -0.35], 60)
58 | time.sleep(2.5)
59 |
60 | # Execute a series of actions in a loop, 3 times in total
61 | for i in range(3):
62 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
63 | mc.set_solution_angles(70, 20)
64 | time.sleep(2.5)
65 | # Set the zero space deflection angle value to move to the target position with a speed of 20, 70 is the angle of joint 1
66 | mc.set_solution_angles(-70, 20)
67 | time.sleep(2.5)
68 |
69 | # Send the joint angle command to move the robotic arm to the specified position with a speed of 60
70 | mc.send_angles([40.25, 36.38, -0.52, -67.23, 0.26, -76.37, -0.35], 60)
71 | time.sleep(2.5)
72 |
73 | # # Send the joint angle command to move the robotic arm to the initial position with a speed of 60
74 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
75 | time.sleep(2.5)
76 |
--------------------------------------------------------------------------------
/demo/myArm_demo/start_run_demo.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 | mc = MyArm('/dev/ttyAMA0')
5 |
6 | time.sleep(0.1)
7 |
8 |
9 | def main():
10 | """
11 | 展示MyArm各个关节的运动状态
12 | :return: None
13 | """
14 | angles_list = [
15 | [98, 7, 68, -92, 164, 5, -2],
16 | [0, 35, 0, -75, 164, 5, -2],
17 | [0, 0, 0, -90, 165, -90, 2],
18 | [0, 0, 0, 0, 0, 0, 0],
19 | ]
20 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
21 | time.sleep(3)
22 | mc.send_angles([0, 0, 0, -100, 0, -78, 0], 60)
23 | time.sleep(3)
24 |
25 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
26 | time.sleep(3)
27 | mc.send_angle(1, 90, 60)
28 | time.sleep(3)
29 |
30 | for i in range(1, 8):
31 | if i == 1:
32 | mc.send_angle(i,140 , 60)
33 | time.sleep(3)
34 | mc.send_angle(i,40 , 60)
35 | time.sleep(3)
36 | mc.send_angle(i, 90, 60)
37 | time.sleep(2)
38 | elif i == 6:
39 | mc.send_angle(i,50 , 60)
40 | time.sleep(2)
41 | mc.send_angle(i, -50, 60)
42 | time.sleep(2)
43 | mc.send_angle(i, 0, 60)
44 | time.sleep(2)
45 | else:
46 | mc.send_angle(i, 50, 60)
47 | time.sleep(2)
48 | mc.send_angle(i, -50, 60)
49 | time.sleep(2)
50 | mc.send_angle(i, 0, 60)
51 | time.sleep(2)
52 |
53 | mc.send_angles(angles_list[0], 60)
54 | time.sleep(3)
55 | mc.send_angles(angles_list[1], 60)
56 | time.sleep(3)
57 | mc.send_angles(angles_list[2], 60)
58 | time.sleep(3)
59 | mc.send_angles(angles_list[3], 60)
60 | time.sleep(3)
61 |
62 |
63 | if __name__ == '__main__':
64 | main()
65 |
--------------------------------------------------------------------------------
/demo/myArm_demo/wave_hand.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 | mc = MyArm('/dev/ttyAMA0', debug=False)
5 | time.sleep(0.1)
6 |
7 | mc.set_fresh_mode(0)
8 | time.sleep(0.2)
9 |
10 | mc.set_servo_data(7, 5, 8)
11 | time.sleep(0.1)
12 |
13 | mc.send_angles([0, 0, 0, 0, 0, 0, 0], 60)
14 | time.sleep(3)
15 |
16 | def main():
17 | # three action
18 | mc.send_angles([-90, 0, 0, 0, 0, 0, 40], 60)
19 | time.sleep(2.5)
20 |
21 | for i in range(4):
22 | mc.send_angle(4, 45, 95)
23 | time.sleep(1.5)
24 | mc.send_angle(4, -45, 95)
25 | time.sleep(1.5)
26 |
27 | for i in range(4):
28 | mc.send_angle(4, 45, 20)
29 | time.sleep(2.5)
30 | mc.send_angle(4, -45, 20)
31 | time.sleep(2.5)
32 | mc.send_angles([-90, 0, 0, 0, 0, 0, 40], 50)
33 | time.sleep(2.5)
34 |
35 | i = 0
36 | while i <1:
37 | main()
38 | i+=1
39 |
40 |
--------------------------------------------------------------------------------
/demo/myArm_demo/xiaqi.py:
--------------------------------------------------------------------------------
1 | import time
2 | from pymycobot.myarm import MyArm
3 |
4 | mc = MyArm('/dev/ttyAMA0')
5 | time.sleep(0.1)
6 |
7 |
8 | def main():
9 | """
10 | 模仿myarm与人类下棋输赢状态的动作
11 | :return: None
12 | """
13 | init_angles = [
14 | [-60, 0, 0, -90, 0, -90, -0.79], # first init point
15 | #[0, 49, 0, -104, 0, -45, -0.79], # second init point
16 | [0, -49, 0, -100, 0, -45, -0.79],
17 | #[-0.26, 2.0, 0.43, -111.0, 0.43, 20.22, -0.79], # third
18 | [-3.16, -11.77, 0.17, -100, -0.52, -3.25, 1.23], # third
19 | [3.25, -8.61, 0.17, -99.14, 1.14, -2.81, -0.79], # left
20 | [-10.01, -6.85, 0.17, -99.49, -2.63, -2.81, 3.07], # right
21 | ]
22 |
23 | #mc.send_angles(init_angles[0], 50)
24 |
25 | #time.sleep(3)
26 |
27 | #mc.send_angles(init_angles[1], 50)
28 | #time.sleep(3)
29 |
30 | #mc.send_angles(init_angles[2], 50)
31 | #time.sleep(3)
32 | #mc.set_gservo_round(12)
33 | #time.sleep(1.5)
34 |
35 | #for i in range(5):
36 |
37 | mc.send_angles(init_angles[2], 50)
38 | time.sleep(2.5)
39 | mc.set_gservo_round(12)
40 | time.sleep(1.5)
41 | mc.send_angles(init_angles[1], 50)
42 | time.sleep(3)
43 | for i in range(3):
44 | mc.send_angles([0, -49, 0, -100, 0, -65, -0.79], 90)
45 | time.sleep(1)
46 | mc.send_angles([0, -49, 0, -100, 0, -25, -0.79], 90)
47 | time.sleep(1)
48 | #mc.send_angles(init_angles[1], 50)
49 | # time.sleep(3)
50 |
51 |
52 | #mc.send_angles(init_angles[2], 50)
53 | #time.sleep(3)
54 | # mc.set_gservo_round(12)
55 | # time.sleep(1.5)
56 | # mc.send_angles(init_angles[1], 50)
57 | # time.sleep(3)
58 |
59 | #mc.send_angles(init_angles[2], 50)
60 | # time.sleep(3)
61 | #mc.set_gservo_round(12)
62 | #time.sleep(1.5)
63 | #mc.send_angles(init_angles[1], 50)
64 | # time.sleep(3)
65 |
66 | # mc.send_angles([0.26, -2.0, 0.43, -100.0, 0.43, 20.22, -0.79], 50)
67 | #time.sleep(3)
68 |
69 | # win
70 | # for i in range(5):
71 | # mc.send_angles([0.0, -0.34, 0.17, -100.62, 0.17, 20.29, 0.08], 90)
72 | # time.sleep(1)
73 | # mc.send_angles([0.0, -0.34, 0.17, -100.62, 0.17, 20.29, 0.08], 90)
74 | # time.sleep(1)
75 | #print(init_angles[2])
76 |
77 | # mc.send_angles(init_angles[2], 50)
78 | # time.sleep(3)
79 | # fail
80 | # mc.send_angles([0.0, -18.34, 0.17, -100.62, 0.17, -7.29, 0.08], 50)
81 | # time.sleep(3)
82 | # mc.send_angles([0.0, -18.34, 0.17, -100.62, 0.17, -26.29, 0.08], 5)
83 | # time.sleep(7)
84 | # mc.send_angle(4, -80, 30)
85 | # time.sleep(3)
86 |
87 |
88 | # mc.send_angles(init_angles[2], 50)
89 | # time.sleep(3)
90 |
91 | if __name__ == '__main__':
92 | main()
93 |
--------------------------------------------------------------------------------
/demo/myCobot_280_demo/280_draw_gcode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding:utf-8 -*-
3 | # This code is suitable for using the mycobot 280 M5 device to draw simple patterns
4 | # such as triangles, squares, and five-pointed stars.
5 | # It controls the movement of the robotic arm by parsing instructions in a gcode file to implement drawing operations.
6 |
7 | # Running this code requires installing the 'pymycobot'
8 | # driver library and python driver environment.
9 | # If you don't installed, please refer to here :
10 | # https://docs.elephantrobotics.com/docs/gitbook-en/7-ApplicationBasePython/
11 |
12 | # The gcode trajectory file used in this code is generated by Elephant luban, please check for details:
13 | # https://docs.elephantrobotics.com/docs/ultraArm-en/3-HowToUseultraArm/2-SoftwareControl/2-Luban/2-Luban.html
14 |
15 | # import library
16 | import time
17 | from pymycobot.mycobot280 import MyCobot280 # import mycobot library,if don't have, first 'pip install pymycobot'
18 |
19 | # use PC and M5 control
20 | mc = MyCobot280('COM14', 115200) # WINDOWS use ,need check port number when you PC
21 | # mc = MyCobot('/dev/ttyUSB0',115200) # VM linux use
22 | time.sleep(0.5)
23 |
24 | # Set interpolation mode
25 | mc.set_fresh_mode(0)
26 | time.sleep(0.5)
27 | # Send the initial point angle of the robot arm, the speed is 50,
28 | # it can be customized and modified, as long as the end is facing down
29 | mc.send_angles([0, -40, -130, 80, 0, 50], 50)
30 | # Wait 3 seconds for the robot arm to move to the specified angle
31 | time.sleep(3)
32 | # Get the current coordinates of the robot arm
33 | get_coords = mc.get_coords()
34 | time.sleep(1.5)
35 | # Save the parsed coordinates
36 | data_coords = []
37 | # Set the drawing speed to 100, and the speed range is 0~100
38 | draw_speed = 100
39 |
40 |
41 | def process_gcode(file_path):
42 | """
43 | Parse the contents of the gcode file, extract the XYZ coordinate values, and save the coordinate data into a list
44 | :param file_path: Gcode file path
45 | :return: A coordinate list
46 | """
47 | # The last valid coordinate, using the rx, ry, rz values
48 | # in the current coordinates of the robot arm as the starting attitude
49 | last_coords = [0.0, 0.0, 0.0, get_coords[3], get_coords[4], get_coords[5]]
50 | with open(file_path, 'r') as file:
51 | # Line-by-line processing instructions
52 | for line in file:
53 | command = line.strip() # Remove newline characters and other whitespace characters at the end of the line
54 | if command.startswith("G0") or command.startswith("G1"): # Move command
55 | coords = last_coords[:] # Copy the previous valid coordinates
56 | command_parts = command.split()
57 | for part in command_parts[1:]:
58 | if part.startswith("X") or part.startswith("x"):
59 | coords[0] = float(part[1:]) # Extract and transform X coordinate data
60 | elif part.startswith("Y") or part.startswith("y"):
61 | coords[1] = float(part[1:]) # Extract and transform Y coordinate data
62 | elif part.startswith("Z") or part.startswith("z"):
63 | coords[2] = float(part[1:]) # Extract and transform Z coordinate data
64 | if coords[0] == 0.0 and coords[1] == 0.0: # If XY data is missing, use the last valid XY coordinates
65 | coords[0] = last_coords[0]
66 | coords[1] = last_coords[1]
67 | if coords[2] == 0.0: # If Z data is missing, use the last valid Z coordinate
68 | coords[2] = last_coords[2]
69 | last_coords = coords
70 | data_coords.append(coords) # Add coordinates to list and save
71 | return data_coords
72 |
73 |
74 | type = int(input('Please input 1-4(1-square 2-triangle 3-five point star 4-quit):'))
75 | if type == 1:
76 | # Pass in the gcode file path and obtain the coordinate data
77 | # File path can be customized
78 | coords_data = process_gcode('square.nc')
79 | # Send coordinates to the robot arm one by one
80 | for i in coords_data:
81 | mc.send_coords(i, draw_speed, 1) # Send coordinates to the robot arm
82 | time.sleep(3.5) # Wait 3.5 seconds for the robot arm movement to complete
83 | elif type == 2:
84 | coords_data = process_gcode('triangle.nc')
85 | for i in coords_data:
86 | mc.send_coords(i, draw_speed, 1)
87 | time.sleep(3.5)
88 | elif type == 3:
89 | coords_data = process_gcode('five_point_star.nc')
90 | for i in coords_data:
91 | mc.send_coords(i, draw_speed, 1)
92 | time.sleep(3.5)
93 | elif type == 4:
94 | exit(0)
95 |
--------------------------------------------------------------------------------
/demo/myCobot_280_demo/five_point_star.nc:
--------------------------------------------------------------------------------
1 | G90
2 | G4 S1
3 | G01 x170 y0 z60 F15
4 | G4 S1
5 | G0 Y-32.03 X195.54
6 | G0 Z49.00
7 | G1 Y-9.66 X195.54
8 | G1 Y-2.75 X215.61
9 | G1 Y4.16 X195.54
10 | G1 Y26.52 X195.54
11 | G1 Y8.43 X183.14
12 | G1 Y15.34 X163.08
13 | G1 Y-2.75 X175.48
14 | G1 Y-20.84 X163.08
15 | G1 Y-13.93 X183.14
16 | G1 Y-32.03 X195.54
17 | G0 Z70.00
18 | G0 Y-2.75 X189.34
19 | M21 P0
--------------------------------------------------------------------------------
/demo/myCobot_280_demo/square.nc:
--------------------------------------------------------------------------------
1 | G90
2 | G4 S1
3 | G01 X170 Y0 Z60 F15
4 | G4 S1
5 | G0 Y-18.33 X204.06
6 | G0 Z50.00
7 | G1 Y16.67 X204.06
8 | G1 Y16.67 X169.06
9 | G1 Y-18.33 X169.06
10 | G1 Y-18.33 X204.06
11 | G0 Z75.00
12 | G0 Y-0.83 X186.56
13 | M21 P0
--------------------------------------------------------------------------------
/demo/myCobot_280_demo/triangle.nc:
--------------------------------------------------------------------------------
1 | G90
2 | G4 S1
3 | G01 X170 Y0 Z60 F15
4 | G4 S1
5 | G0 Y18.54 X168.58
6 | G0 Z49.00
7 | G1 Y-18.07 X168.58
8 | G1 Y18.54 X204.81
9 | G1 Y18.54 X168.58
10 | G0 Z70.00
11 | G0 Y0.24 X186.69
12 | M21 P0
--------------------------------------------------------------------------------
/demo/myCobot_320_demo/myCobot_320_servo_info.py:
--------------------------------------------------------------------------------
1 | # encoding=utf-8
2 | import os
3 | import sys
4 | sys.path.append(os.getcwd())
5 |
6 | import matplotlib.pyplot as plt
7 | import matplotlib.font_manager as font_manager
8 |
9 | from pymycobot import MyCobot320
10 |
11 | mc = MyCobot320("COM12", 115200)
12 |
13 | POINTS = 7
14 | sin_list = [0] * (POINTS -1)
15 | indx = 0
16 |
17 | fig, ax = plt.subplots()
18 | ax.set_ylim([0, 3250])
19 | ax.set_xlim([1, 6])
20 | ax.set_autoscale_on(False)
21 | ax.set_xticks(range(0, 3250, 500))
22 | ax.set_yticks(range(0, 11, 1))
23 | ax.grid(True)
24 |
25 | line_sin, = ax.plot([i for i in range(1,POINTS)], sin_list, label='Current', color='cornflowerblue')
26 | ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))
27 |
28 | def sin_output(ax):
29 | global sin_list, line_sin
30 | sin_list = sin_list[1:] + mc.get_servo_currents() # get current
31 | # print(sin_list)
32 | line_sin.set_ydata(sin_list)
33 | ax.draw_artist(line_sin)
34 | ax.figure.canvas.draw()
35 |
36 | timer = fig.canvas.new_timer(interval=100)
37 | timer.add_callback(sin_output, ax)
38 | timer.start()
39 | plt.show()
--------------------------------------------------------------------------------
/demo/mybuddy_demo/emoticon.md:
--------------------------------------------------------------------------------
1 | # Instructions for playing animations on MyBuddy screen.
2 | [中文]
3 | 1. 将[视频文件](emoticon.zip)和[案例代码](./mybuddy_emoticon_demo.py)下载并且解压到mybuddy系统内
4 |
5 | 2. 更改案例`pymycobot/demo/mybuddy_demo/mybuddy_emoticon_demo.py`文件,
6 |
7 | 将`/home/er/pymycobot/emo/face_video_3_2.mp4`替换成解压出来的视频文件路径
8 | ```python
9 | from pymycobot import MyBuddyEmoticon
10 | import time
11 |
12 | # [video_path, Playback_duration(s)]
13 | video1 = ["/home/er/pymycobot/emo/face_video_3_2.mp4", 10]
14 |
15 | datas = [video1]
16 |
17 | me = MyBuddyEmoticon(datas)
18 | ...
19 | ```
20 | 3. 执行mybuddy_emoticon_demo.py即可
21 | [API说明文档](../../docs/mybuddy_emoticon.md)
22 | ---
23 | [English]
24 | 1. Download and unzip [video file](emoticon.zip) and [case code](./mybuddy_emoticon_demo.py) into the mybuddy system
25 |
26 | 2. Change the case `pymycobot/demo/mybuddy_demo/mybuddy_emoticon_demo.py` file,
27 |
28 | Replace `/home/er/pymycobot/emo/face_video_3_2.mp4` with the decompressed video file path
29 | ```python
30 | from pymycobot import MyBuddyEmoticon
31 | import time
32 |
33 | # [video_path, Playback_duration(s)]
34 | video1 = ["/home/er/pymycobot/emo/face_video_3_2.mp4", 10]
35 |
36 | datas = [video1]
37 |
38 | me = MyBuddyEmoticon(datas)
39 | ...
40 | ```
41 | 3. Execute mybuddy_emoticon_demo.py
42 |
43 | [API document](../../docs/mybuddy_emoticon.md)
44 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/emoticon.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/mybuddy_demo/emoticon.zip
--------------------------------------------------------------------------------
/demo/mybuddy_demo/gpio_test.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | from pymycobot import MyBuddy
3 | import time
4 |
5 |
6 |
7 | mc = MyBuddy('/dev/ttyACM0',115200,debug=False)
8 | mc.set_gpio_init_mode(0)
9 |
10 | def pump_init_1(i,j):
11 | mc.set_gpio_setup(i,0)
12 | mc.set_gpio_setup(j,0)
13 |
14 | def pump_init_1(i,j):
15 | mc.set_gpio_setup(i,1)
16 | mc.set_gpio_setup(j,1)
17 | def pump_on(i,j):
18 | mc.set_gpio_output(i,0)
19 | mc.set_gpio_output(j,0)
20 |
21 | def pump_off(i,j):
22 | mc.set_gpio_output(i,1)
23 | mc.set_gpio_output(j,1)
24 |
25 |
26 |
27 | #It is used to check the input/output status of each I/O interface
28 | for k in range(1,17):
29 | mc.set_gpio_setup(k,0)
30 |
31 |
32 | while 1:
33 | _a = ''
34 | for k in range(1,17):
35 | _a += str(mc.get_gpio_input(k))
36 | time.sleep(1)
37 | print(_a)
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/ChewingGum.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 | # Establish serial connection
9 | mc = MyBuddy('/dev/ttyACM0', 115200)
10 |
11 |
12 |
13 | # Release the arms and record the points passed
14 | def read():
15 | time.sleep(10)
16 | t = time.time()
17 | record_list = []
18 | print(1)
19 | while time.time() - t < 5:
20 | angles_1 = mc.get_encoders(1)
21 | angles_2 = mc.get_encoders(2)
22 | if angles_1 and angles_2:
23 | record_list.append([angles_1, angles_2])
24 | time.sleep(0.1)
25 | # Print the read location information, copy and save it as a txt file
26 | for i in record_list:
27 | print(i)
28 |
29 |
30 | # Take out and use the saved location
31 | def write():
32 | time.sleep(1.5)
33 | # The file here uses the saved txt file
34 | data = list(filter(None, open(os.path.join(os.getcwd(), 'ChewingGum.txt')).read().splitlines()))
35 | for angles in data:
36 | data = eval(angles)[0]
37 | data[4] -= 280
38 | mc.set_encoders(1, data, 100)
39 | time.sleep(0.03)
40 | mc.set_encoders(2, eval(angles)[1], 100)
41 | time.sleep(0.2)
42 | time.sleep(1.5)
43 | mc.set_gripper_state(2, 1)
44 | time.sleep(1.5)
45 | # The file here uses the saved txt file
46 | data = list(filter(None, open(os.path.join(os.getcwd(), 'ChewingGum_2.txt')).read().splitlines()))
47 | for angles in data:
48 | data = eval(angles)[0]
49 | data[4] -= 280
50 | mc.set_encoders(1, data, 100)
51 | time.sleep(0.03)
52 | mc.set_encoders(2, eval(angles)[1], 100)
53 | time.sleep(0.2)
54 | time.sleep(1.5)
55 | mc.set_gripper_state(2, 0)
56 | time.sleep(1.5)
57 | # The file here uses the saved txt file
58 | data = list(filter(None, open(os.path.join(os.getcwd(), 'ChewingGum_3.txt')).read().splitlines()))
59 | for angles in data:
60 | data = eval(angles)[0]
61 | data[4] -= 280
62 | mc.set_encoders(1, data, 100)
63 | time.sleep(0.03)
64 | mc.set_encoders(2, eval(angles)[1], 100)
65 | time.sleep(0.2)
66 |
67 |
68 | # show emoji
69 | def smile():
70 | # The location where the emoji file is stored
71 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
72 | out_win = "l"
73 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
74 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
75 | # infinite loop
76 | while True:
77 | ret, frame = cap.read()
78 | if frame is not None:
79 | print(1)
80 | cv.imshow(out_win, frame)
81 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
82 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
83 |
84 |
85 | if __name__ == '__main__':
86 | # run with multithreading
87 | t1 = threading.Thread(target=write)
88 | t2 = threading.Thread(target=smile)
89 | t1.start()
90 | t2.start()
91 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/ChewingGum.txt:
--------------------------------------------------------------------------------
1 | [[2221, 1326, 2898, 3454, 3191, 1891], [1910, 2804, 1191, 605, 1108, 2685]]
2 | [[2221, 1326, 2898, 3454, 3191, 1891], [1910, 2804, 1191, 605, 1108, 2685]]
3 | [[2221, 1326, 2898, 3452, 3191, 1891], [1910, 2804, 1191, 605, 1108, 2685]]
4 | [[2221, 1326, 2898, 3451, 3191, 1891], [1910, 2803, 1191, 613, 1110, 2685]]
5 | [[2226, 1326, 2898, 3441, 3179, 1891], [1901, 2775, 1191, 647, 1127, 2685]]
6 | [[2232, 1326, 2896, 3433, 3169, 1890], [1885, 2665, 1191, 773, 1158, 2685]]
7 | [[2248, 1326, 2896, 3424, 3152, 1888], [1833, 2544, 1190, 928, 1219, 2685]]
8 | [[2266, 1326, 2895, 3423, 3128, 1888], [1755, 2431, 1190, 1091, 1309, 2685]]
9 | [[2288, 1326, 2895, 3415, 3101, 1888], [1635, 2318, 1190, 1284, 1465, 2685]]
10 | [[2291, 1326, 2895, 3406, 3093, 1886], [1449, 2238, 1190, 1459, 1687, 2685]]
11 | [[2291, 1326, 2895, 3400, 3090, 1885], [1319, 2227, 1190, 1598, 1901, 2685]]
12 | [[2291, 1326, 2895, 3400, 3090, 1885], [1249, 2230, 1190, 1714, 2072, 2685]]
13 | [[2291, 1326, 2895, 3396, 3089, 1885], [1242, 2241, 1190, 1787, 2171, 2685]]
14 | [[2291, 1326, 2895, 3393, 3091, 1885], [1259, 2334, 1190, 1730, 2199, 2685]]
15 | [[2297, 1328, 2895, 3393, 3093, 1885], [1273, 2388, 1190, 1740, 2231, 2684]]
16 | [[2301, 1327, 2895, 3389, 3092, 1885], [1274, 2435, 1190, 1719, 2228, 2678]]
17 | [[2301, 1327, 2895, 3384, 3091, 1885], [1283, 2474, 1190, 1688, 2204, 2670]]
18 | [[2301, 1327, 2895, 3378, 3091, 1885], [1288, 2487, 1190, 1680, 2202, 2666]]
19 | [[2301, 1327, 2895, 3377, 3092, 1885], [1293, 2487, 1190, 1680, 2200, 2666]]
20 | [[2301, 1327, 2895, 3375, 3091, 1885], [1293, 2487, 1190, 1679, 2194, 2666]]
21 | [[2301, 1327, 2895, 3376, 3091, 1885], [1293, 2487, 1190, 1681, 2194, 2666]]
22 | [[2301, 1327, 2895, 3377, 3093, 1885], [1293, 2487, 1190, 1681, 2193, 2666]]
23 | [[2301, 1327, 2895, 3378, 3093, 1885], [1293, 2487, 1190, 1685, 2195, 2666]]
24 | [[2301, 1327, 2895, 3378, 3094, 1885], [1293, 2487, 1190, 1687, 2195, 2666]]
25 | [[2301, 1327, 2894, 3378, 3094, 1885], [1293, 2487, 1190, 1689, 2196, 2666]]
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/ChewingGum_3.txt:
--------------------------------------------------------------------------------
1 | [[2309, 1238, 2856, 3496, 3076, 1839], [1443, 2384, 1010, 1531, 2064, 2762]]
2 | [[2309, 1238, 2856, 3494, 3076, 1839], [1446, 2384, 1010, 1535, 2067, 2760]]
3 | [[2309, 1238, 2856, 3493, 3076, 1839], [1446, 2384, 1010, 1532, 2073, 2759]]
4 | [[2309, 1238, 2856, 3492, 3076, 1839], [1443, 2384, 1010, 1533, 2077, 2758]]
5 | [[2309, 1238, 2856, 3492, 3077, 1839], [1441, 2384, 1010, 1521, 2074, 2756]]
6 | [[2309, 1238, 2856, 3492, 3077, 1839], [1441, 2384, 1010, 1519, 2066, 2756]]
7 | [[2309, 1238, 2856, 3492, 3077, 1839], [1442, 2382, 1010, 1517, 2065, 2756]]
8 | [[2309, 1238, 2856, 3492, 3077, 1839], [1444, 2382, 1010, 1513, 2064, 2756]]
9 | [[2309, 1238, 2856, 3492, 3077, 1839], [1447, 2381, 1010, 1479, 2046, 2756]]
10 | [[2309, 1238, 2856, 3492, 3080, 1839], [1448, 2371, 1010, 1466, 2027, 2755]]
11 | [[2309, 1238, 2856, 3489, 3076, 1839], [1448, 2317, 1010, 1500, 2012, 2754]]
12 | [[2309, 1238, 2856, 3489, 3074, 1839], [1449, 2243, 1010, 1522, 1970, 2752]]
13 | [[2309, 1238, 2856, 3489, 3073, 1839], [1458, 2173, 1010, 1524, 1893, 2752]]
14 | [[2309, 1238, 2856, 3489, 3072, 1839], [1501, 2161, 1010, 1379, 1749, 2754]]
15 | [[2309, 1238, 2856, 3488, 3071, 1839], [1591, 2161, 1010, 1266, 1601, 2753]]
16 | [[2309, 1238, 2856, 3487, 3071, 1839], [1708, 2164, 1008, 1155, 1430, 2753]]
17 | [[2309, 1238, 2856, 3487, 3073, 1839], [1826, 2219, 1008, 1057, 1283, 2756]]
18 | [[2309, 1238, 2856, 3488, 3075, 1839], [1885, 2328, 1008, 920, 1205, 2753]]
19 | [[2305, 1238, 2856, 3488, 3081, 1840], [1914, 2453, 1008, 816, 1170, 2756]]
20 | [[2303, 1238, 2856, 3489, 3086, 1840], [1909, 2571, 1009, 708, 1166, 2756]]
21 | [[2291, 1238, 2856, 3489, 3098, 1840], [1907, 2644, 1010, 645, 1163, 2763]]
22 | [[2282, 1238, 2856, 3491, 3108, 1840], [1907, 2675, 1010, 603, 1150, 2772]]
23 | [[2282, 1238, 2856, 3496, 3110, 1841], [1907, 2703, 1010, 605, 1161, 2772]]
24 | [[2278, 1240, 2856, 3498, 3113, 1844], [1907, 2704, 1010, 609, 1164, 2771]]
25 | [[2271, 1241, 2856, 3493, 3123, 1845], [1907, 2704, 1010, 609, 1168, 2771]]
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/README.md:
--------------------------------------------------------------------------------
1 | # This is Python Demo for myBuddy
2 |
3 | ## Firmware Requirements: The latest firmware will do
4 |
5 | ## catch_the_ball
6 |
7 | Use myBuddy's hands to grab the ball on the table, move back and forth.
8 |
9 | ## ChewingGum
10 |
11 | Use the gripper to pour the chewing gum out of the table.
12 |
13 | ## comeOn
14 |
15 | Cheer up with red flag in both hands.
16 |
17 | ## psydack
18 |
19 | psyduck dance.
20 |
21 | ## pass_the_ball
22 |
23 | Pass the ball with both hands.
24 |
25 | ## petCat
26 |
27 | pet the cat
28 |
29 | ## piano
30 |
31 | myBuddy plays the song.
32 |
33 | ## play_ball_cooperatively
34 |
35 | myBuddy spins a ball with both hands.
36 |
37 | ## praise
38 |
39 | myBuddy making a thumbs up gesture.
40 |
41 | ## reject
42 |
43 | myBuddy gesture of rejection with both hands.
44 |
45 | ## symphony
46 |
47 | myBuddy conducts like a musician.
48 |
49 | ## thanHeart
50 |
51 | myBuddy making a heart gesture with both hands.
52 |
53 | ## dence
54 |
55 | myBuddy's dance.
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/catch_the_ball.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 | # Establish serial connection
10 | mc = MyBuddy('/dev/ttyACM0', 115200)
11 |
12 |
13 | # Release the arms and record the points passed
14 | def read():
15 | time.sleep(10)
16 | t = time.time()
17 | record_list = []
18 | print(1)
19 | while time.time() - t < 40:
20 | angles_1 = mc.get_encoders(1)
21 | angles_2 = mc.get_encoders(2)
22 | if angles_1 and angles_2:
23 | record_list.append([angles_1, angles_2])
24 | time.sleep(0.1)
25 | # Print the read location information, copy and save it as a txt file
26 | for i in record_list:
27 | print(i)
28 |
29 |
30 | # Take out and use the saved location
31 | def write():
32 | time.sleep(1.5)
33 | mc.power_on()
34 | # The file here uses the saved txt file
35 | data = list(filter(None, open(os.path.join(os.getcwd(), 'catch_the_ball.txt')).read().splitlines()))
36 | # infinite loop
37 | while True:
38 | for angles in data:
39 | print(angles)
40 | mc.set_encoders(1, eval(angles)[0], 80)
41 | time.sleep(0.05)
42 | mc.set_encoders(2, eval(angles)[1], 80)
43 | time.sleep(0.1)
44 |
45 |
46 | # show emoji
47 | def smile():
48 | # The location where the emoji file is stored
49 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
50 | out_win = "l"
51 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
52 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
53 | # infinite loop
54 | while True:
55 | ret, frame = cap.read()
56 | if frame is not None:
57 | cv.imshow(out_win, frame)
58 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
59 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
60 |
61 |
62 | if __name__ == '__main__':
63 | # run with multithreading
64 | t1 = threading.Thread(target=write)
65 | t2 = threading.Thread(target=smile)
66 | t1.start()
67 | t2.start()
68 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/comeOn.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 |
15 | # Release the arms and record the points passed
16 | def read():
17 | time.sleep(10)
18 | t = time.time()
19 | record_list = []
20 | print(1)
21 | while time.time() - t < 20:
22 | angles_1 = mc.get_encoders(1)
23 | angles_2 = mc.get_encoders(2)
24 | if angles_1 and angles_2:
25 | record_list.append([angles_1, angles_2])
26 | time.sleep(0.1)
27 |
28 | # Print the read location information, copy and save it as a txt file
29 | for i in record_list:
30 | print(i)
31 |
32 |
33 | # Take out and use the saved location
34 | def write():
35 | time.sleep(1.5)
36 | # The file here uses the saved txt file
37 | data = list(filter(None, open(os.path.join(os.getcwd(), 'data_comeOn2.txt')).read().splitlines()))
38 | # infinite loop
39 | while True:
40 | for angles in data:
41 | print(angles)
42 | mc.set_encoders(1, eval(angles)[0], 80)
43 | time.sleep(0.05)
44 | mc.set_encoders(2, eval(angles)[1], 80)
45 | time.sleep(0.1)
46 |
47 |
48 | # show emoji
49 | def smile():
50 | # The location where the emoji file is stored
51 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
52 | out_win = "l"
53 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
54 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
55 | # infinite loop
56 | while True:
57 | ret, frame = cap.read()
58 | if frame is not None:
59 | print(1)
60 | cv.imshow(out_win, frame)
61 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
62 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
63 |
64 |
65 | if __name__ == '__main__':
66 | # run with multithreading
67 | t1 = threading.Thread(target=write)
68 | t2 = threading.Thread(target=smile)
69 | t1.start()
70 | t2.start()
71 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/dack.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import time
3 | from pymycobot.mybuddy import MyBuddy
4 | import threading
5 | from threading import Lock, Thread
6 | import cv2 as cv
7 |
8 |
9 | # Establish serial connection
10 | mc = MyBuddy('/dev/ttyACM0', 115200)
11 | time.sleep(1.5)
12 |
13 |
14 | def run():
15 | while True:
16 | mc.set_encoders(1, [18, 2028, 1024, 2087, 3088, 1024], 100)
17 | time.sleep(0.05)
18 | mc.set_encoders(2, [1994, 2098, 3072, 2027, 1088, 3072], 100)
19 | time.sleep(0.01)
20 | mc.set_encoder(3, 1, 1548, 100)
21 | time.sleep(3)
22 | mc.set_encoders(1, [2026, 2028, 1024, 2112, 3088, 1024], 100)
23 | time.sleep(0.05)
24 | mc.set_encoders(2, [3980, 2098, 3076, 2022, 1088, 3072], 100)
25 | time.sleep(0.01)
26 | mc.set_encoder(3, 1, 2548, 100)
27 | time.sleep(3)
28 |
29 |
30 | # show emoji
31 | def smile():
32 | # The location where the emoji file is stored
33 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
34 | out_win = "l"
35 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
36 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
37 | while True:
38 | ret, frame = cap.read()
39 | if frame is not None:
40 | print(1)
41 | cv.imshow(out_win, frame)
42 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
43 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
44 |
45 |
46 | if __name__ == '__main__':
47 | # run with multithreading
48 | t1 = threading.Thread(target=run)
49 | t2 = threading.Thread(target=smile)
50 | t1.start()
51 | t2.start()
52 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/dance.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 | # Establish serial connection
10 | mc = MyBuddy('/dev/ttyACM0', 115200)
11 |
12 | t = 1
13 |
14 |
15 | def run():
16 | while True:
17 | mc.send_angles(1, [0, 0, 0, 0, 0, 0], 50)
18 | time.sleep(0.05)
19 | mc.send_angles(2, [0, 0, 0, 0, 0, 0], 50)
20 | time.sleep(2 * t)
21 | mc.send_angles(1, [0, 0, 90, 0, 0, 0], 50)
22 | time.sleep(0.05)
23 | mc.send_angles(2, [0, 0, -90, 0, 0, 0], 50)
24 | time.sleep(2 * t)
25 | for i in range(3):
26 | mc.send_angles(1, [0, 0, 115, 0, 0, 0], 50)
27 | time.sleep(0.05)
28 | mc.send_angles(2, [0, 0, -65, 0, 0, 0], 50)
29 | time.sleep(2 * t)
30 | mc.send_angles(1, [0, 0, -115, 0, 0, 0], 50)
31 | time.sleep(0.05)
32 | mc.send_angles(2, [0, 0, 65, 0, 0, 0], 50)
33 | time.sleep(2 * t)
34 |
35 | for i in range(3):
36 | mc.send_angles(1, [45, 0, 90, 0, 0, 0], 50)
37 | time.sleep(0.05)
38 | mc.send_angles(2, [-45, 0, -90, 0, 0, 0], 50)
39 | time.sleep(2 * t)
40 | mc.send_angles(1, [-45, 0, 90, 0, 0, 0], 50)
41 | time.sleep(0.05)
42 | mc.send_angles(2, [45, 0, -90, 0, 0, 0], 50)
43 | time.sleep(2 * t)
44 | mc.send_angles(1, [180, 0, 90, 0, 0, 0], 50)
45 | time.sleep(0.05)
46 | mc.send_angles(2, [-180, 0, -90, 0, 0, 0], 50)
47 | time.sleep(2 * t)
48 | for i in range(3):
49 | mc.send_angles(1, [180, 0, 135, 0, 0, 0], 50)
50 | time.sleep(0.05)
51 | mc.send_angles(2, [-180, 0, -45, 0, 0, 0], 50)
52 | time.sleep(2 * t)
53 | mc.send_angles(1, [180, 0, 45, 0, 0, 0], 50)
54 | time.sleep(0.05)
55 | mc.send_angles(2, [-180, 0, -135, 0, 0, 0], 50)
56 | time.sleep(2 * t)
57 |
58 |
59 | # show emoji
60 | def smile():
61 | # The location where the emoji file is stored
62 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
63 | out_win = "l"
64 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
65 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
66 | # infinite loop
67 | while True:
68 | ret, frame = cap.read()
69 | if frame is not None:
70 | cv.imshow(out_win, frame)
71 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
72 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
73 |
74 |
75 | if __name__ == '__main__':
76 | # run with multithreading
77 | t1 = threading.Thread(target=run())
78 | t2 = threading.Thread(target=smile)
79 | t1.start()
80 | t2.start()
81 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/pass_the_ball.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 | # Establish serial connection
10 | mc = MyBuddy('/dev/ttyACM0', 115200)
11 |
12 |
13 | def run():
14 | # infinite loop
15 | while True:
16 | en1 = [3033, 1558, 2854, 1233, 193, 1024]
17 | en2 = [1064, 2324, 1061, 2737, 3882, 67]
18 | mc.set_encoders(1, en1, 10)
19 | time.sleep(0.05)
20 | mc.set_encoders(2, en2, 10)
21 | time.sleep(5)
22 |
23 | _en2 = [962, 3061, 1182, 2172, 3877, 115]
24 | _en1 = [3203, 908, 2679, 1690, 368, 969]
25 | mc.set_encoders(2, _en2, 10)
26 | time.sleep(5)
27 | _en2[5] += 500
28 | mc.set_encoders(2, _en2, 4)
29 | time.sleep(7)
30 | _en2[5] -= 500
31 | mc.set_encoders(2, _en2, 10)
32 | time.sleep(3)
33 | mc.set_encoders(2, en2, 10)
34 | time.sleep(5)
35 | mc.set_encoders(1, _en1, 10)
36 | time.sleep(5)
37 | _en1[5] -= 350
38 | mc.set_encoders(1, _en1, 4)
39 | time.sleep(5)
40 | _en1[5] += 350
41 | mc.set_encoders(1, _en1, 10)
42 | time.sleep(4)
43 | mc.set_encoders(1, en1, 10)
44 | time.sleep(5)
45 |
46 |
47 | # show emoji
48 | def smile():
49 | # The location where the emoji file is stored
50 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
51 | out_win = "l"
52 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
53 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
54 | # infinite loop
55 | while True:
56 | ret, frame = cap.read()
57 | # print(frame)
58 | if frame is not None:
59 | print(1)
60 | cv.imshow(out_win, frame)
61 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
62 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
63 |
64 |
65 | if __name__ == '__main__':
66 | # run with multithreading
67 | t1 = threading.Thread(target=run)
68 | t2 = threading.Thread(target=smile)
69 | t1.start()
70 | t2.start()
71 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/petCat.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock,Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 | # Release the arms and record the points passed
15 | def read():
16 | time.sleep(10)
17 | t = time.time()
18 | record_list = []
19 | print(1)
20 | while time.time() - t <20:
21 | angles_1 = mc.get_encoders(1)
22 | angles_2 = mc.get_encoders(2)
23 | if angles_1 and angles_2:
24 | record_list.append([angles_1, angles_2])
25 | time.sleep(0.1)
26 |
27 | # Print the read location information, copy and save it as a txt file
28 | for i in record_list:
29 | print(i)
30 |
31 |
32 | # Take out and use the saved location
33 | def write():
34 | time.sleep(1.5)
35 | # The file here uses the saved txt file
36 | data = list(filter(None,open(os.path.join(os.getcwd(),'petCat.txt')).read().splitlines()))
37 | # infinite loop
38 | while True:
39 | for angles in data:
40 | print(angles)
41 | mc.set_encoders(1, eval(angles)[0], 100)
42 | time.sleep(0.03)
43 | mc.set_encoders(2, eval(angles)[1], 100)
44 | time.sleep(0.2)
45 |
46 | # show emoji
47 | def smile():
48 | # The location where the emoji file is stored
49 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
50 | out_win = "l"
51 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
52 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
53 | # infinite loop
54 | while True:
55 | ret, frame = cap.read()
56 | if frame is not None:
57 | print(1)
58 | cv.imshow(out_win, frame)
59 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
60 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
61 |
62 |
63 | if __name__ == '__main__':
64 | # run with multithreading
65 | t1 = threading.Thread(target=write)
66 | t2 = threading.Thread(target=smile)
67 | t1.start()
68 | t2.start()
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/piano.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 | def one():
15 | mc.set_encoders(1, [3169, 1439, 3383, 3033, 1045, 2042], 5)
16 | time.sleep(0.3)
17 | mc.set_encoders(1, [3029, 1439, 3383, 3033, 1045, 2042], 5)
18 | time.sleep(0.3)
19 | mc.set_encoders(1, [3169, 1439, 3383, 3033, 1045, 2042], 5)
20 | time.sleep(0.3)
21 |
22 |
23 | def tow():
24 | mc.set_encoders(1, [3169, 1281, 3299, 3102, 1047, 2021], 5)
25 | time.sleep(0.3)
26 | mc.set_encoders(1, [3029, 1281, 3299, 3102, 1047, 2021], 5)
27 | time.sleep(0.3)
28 | mc.set_encoders(1, [3169, 1281, 3299, 3102, 1047, 2021], 5)
29 | time.sleep(0.3)
30 |
31 |
32 | def three():
33 | mc.set_encoders(1, [3169, 1115, 3193, 3123, 1047, 2036], 5)
34 | time.sleep(0.3)
35 | mc.set_encoders(1, [3029, 1115, 3193, 3123, 1047, 2036], 5)
36 | time.sleep(0.3)
37 | mc.set_encoders(1, [3169, 1115, 3193, 3123, 1047, 2036], 5)
38 | time.sleep(0.3)
39 |
40 |
41 | def four():
42 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
43 | time.sleep(0.3)
44 | mc.set_encoders(1, [3029, 969, 2984, 3027, 1040, 2091], 5)
45 | time.sleep(0.3)
46 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
47 | time.sleep(0.3)
48 |
49 |
50 | def five():
51 | mc.set_encoders(2, [949, 3068, 974, 1032, 3001, 2076], 5)
52 | time.sleep(0.3)
53 | mc.set_encoders(2, [1049, 3068, 974, 1032, 3001, 2076], 5)
54 | time.sleep(0.3)
55 | mc.set_encoders(2, [949, 3068, 974, 1032, 3001, 2076], 5)
56 | time.sleep(0.3)
57 |
58 |
59 | def six():
60 | mc.set_encoders(2, [944, 3068, 974, 959, 3001, 2000], 5)
61 | time.sleep(0.3)
62 | mc.set_encoders(2, [1044, 3068, 974, 959, 3001, 2000], 5)
63 | time.sleep(0.3)
64 | mc.set_encoders(2, [944, 3068, 974, 959, 3001, 2000], 5)
65 | time.sleep(0.3)
66 |
67 |
68 | def seven():
69 | mc.set_encoders(2, [3328, 1609, 3064, 1426, 1383, 1301], 5)
70 | time.sleep(0.3)
71 | mc.set_encoders(2, [3628, 1609, 3064, 1426, 1383, 1301], 5)
72 | time.sleep(0.3)
73 |
74 |
75 | def eight():
76 | mc.set_encoders(2, [3259, 1613, 2839, 1187, 1337, 1300], 5)
77 | time.sleep(0.3)
78 | mc.set_encoders(2, [3659, 1613, 2839, 1187, 1337, 1300], 5)
79 | time.sleep(0.3)
80 |
81 |
82 | def run():
83 | one()
84 | one()
85 | five()
86 | five()
87 | six()
88 | six()
89 | five()
90 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
91 | time.sleep(1)
92 | four()
93 | four()
94 | three()
95 | three()
96 | tow()
97 | tow()
98 | one()
99 | time.sleep(1)
100 | five()
101 | five()
102 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
103 | time.sleep(0.7)
104 | four()
105 | four()
106 | three()
107 | three()
108 | tow()
109 | time.sleep(1)
110 | five()
111 | five()
112 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
113 | time.sleep(1)
114 | four()
115 | four()
116 | three()
117 | three()
118 | tow()
119 | time.sleep(1)
120 | one()
121 | one()
122 | five()
123 | five()
124 | six()
125 | six()
126 | five()
127 | mc.set_encoders(1, [3169, 969, 2984, 3027, 1040, 2091], 5)
128 | time.sleep(1)
129 | four()
130 | four()
131 | three()
132 | three()
133 | tow()
134 | tow()
135 | one()
136 |
137 |
138 | # show emoji
139 | def smile():
140 | # The location where the emoji file is stored
141 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
142 | out_win = "l"
143 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
144 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
145 | # infinite loop
146 | while True:
147 | ret, frame = cap.read()
148 | if frame is not None:
149 | print(1)
150 | cv.imshow(out_win, frame)
151 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
152 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
153 |
154 |
155 | if __name__ == '__main__':
156 | # run with multithreading
157 | t1 = threading.Thread(target=run)
158 | t2 = threading.Thread(target=smile)
159 | t1.start()
160 | t2.start()
161 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/play_ball_cooperatively.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | import cv2 as cv
7 |
8 |
9 | # Establish serial connection
10 | mc = MyBuddy('/dev/ttyACM0', 115200)
11 |
12 |
13 |
14 | # Release the arms and record the points passed
15 | def read():
16 | time.sleep(10)
17 | t = time.time()
18 | record_list = []
19 | print(1)
20 | while time.time() - t < 15:
21 | angles_1 = mc.get_encoders(1)
22 | angles_2 = mc.get_encoders(2)
23 | if angles_1 and angles_2:
24 | record_list.append([angles_1, angles_2])
25 | time.sleep(0.1)
26 |
27 | # Print the read location information, copy and save it as a txt file
28 | for i in record_list:
29 | print(i)
30 |
31 |
32 | # Take out and use the saved location
33 | def write():
34 | time.sleep(1.5)
35 | # The file here uses the saved txt file
36 | data = list(filter(None, open(os.path.join(os.getcwd(), 'play_ball_cooperatively.txt')).read().splitlines()))
37 | # infinite loop
38 | while True:
39 | for angles in data:
40 | print(angles)
41 | mc.set_encoders(1, eval(angles)[0], 100)
42 | time.sleep(0.03)
43 | mc.set_encoders(2, eval(angles)[1], 100)
44 | time.sleep(0.2)
45 |
46 |
47 | # show emoji
48 | def smile():
49 | # The location where the emoji file is stored
50 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
51 | out_win = "l"
52 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
53 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
54 | # infinite loop
55 | while True:
56 | ret, frame = cap.read()
57 | if frame is not None:
58 | print(1)
59 | cv.imshow(out_win, frame)
60 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
61 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
62 |
63 |
64 | if __name__ == '__main__':
65 | # run with multithreading
66 | t1 = threading.Thread(target=write)
67 | t2 = threading.Thread(target=smile)
68 | t1.start()
69 | t2.start()
70 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/praise.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 |
15 | # Release the arms and record the points passed
16 | def read():
17 | time.sleep(3)
18 | mc.release_all_servos()
19 | time.sleep(10)
20 | t = time.time()
21 | record_list = []
22 | print(1)
23 | while time.time() - t < 15:
24 | angles_1 = mc.get_encoders(1)
25 | angles_2 = mc.get_encoders(2)
26 | if angles_1 and angles_2:
27 | record_list.append([angles_1, angles_2])
28 | time.sleep(0.1)
29 |
30 | # Print the read location information, copy and save it as a txt file
31 | for i in record_list:
32 | print(i)
33 |
34 |
35 | # Take out and use the saved location
36 | def write():
37 | time.sleep(1.5)
38 | # The file here uses the saved txt file
39 | data = list(filter(None, open(os.path.join(os.getcwd(), 'praise.txt')).read().splitlines()))
40 |
41 | for angles in data:
42 | print(angles)
43 | mc.set_encoders(1, eval(angles)[0], 100)
44 | time.sleep(0.05)
45 | mc.set_encoders(2, eval(angles)[1], 100)
46 | time.sleep(0.1)
47 |
48 |
49 | def smile():
50 | # The location where the emoji file is stored
51 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
52 | out_win = "l"
53 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
54 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
55 | # infinite loop
56 | while True:
57 | ret, frame = cap.read()
58 | if frame is not None:
59 | print(1)
60 | cv.imshow(out_win, frame)
61 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
62 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
63 |
64 |
65 | if __name__ == '__main__':
66 | # run with multithreading
67 | t1 = threading.Thread(target=write)
68 | t2 = threading.Thread(target=smile)
69 | t1.start()
70 | t2.start()
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/reject.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 |
15 | # Release the arms and record the points passed
16 | def read():
17 | time.sleep(10)
18 | t = time.time()
19 | record_list = []
20 | print(1)
21 | while time.time() - t < 10:
22 | angles_1 = mc.get_encoders(1)
23 | angles_2 = mc.get_encoders(2)
24 | if angles_1 and angles_2:
25 | record_list.append([angles_1, angles_2])
26 | time.sleep(0.1)
27 |
28 | # Print the read location information, copy and save it as a txt file
29 | for i in record_list:
30 | print(i)
31 |
32 |
33 | # Take out and use the saved location
34 | def write():
35 | time.sleep(1.5)
36 | # The file here uses the saved txt file
37 | data = list(filter(None, open(os.path.join(os.getcwd(), 'data_no_cant.txt')).read().splitlines()))
38 | # infinite loop
39 | while True:
40 | for angles in data:
41 | print(angles)
42 | mc.set_encoders(1, eval(angles)[0], 100)
43 | time.sleep(0.05)
44 | mc.set_encoders(2, eval(angles)[1], 100)
45 | time.sleep(0.1)
46 |
47 |
48 | # show emoji
49 | def smile():
50 | # The location where the emoji file is stored
51 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
52 | out_win = "l"
53 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
54 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
55 | # infinite loop
56 | while True:
57 | ret, frame = cap.read()
58 | if frame is not None:
59 | print(1)
60 | cv.imshow(out_win, frame)
61 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
62 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
63 |
64 |
65 | if __name__ == '__main__':
66 | # run with multithreading
67 | t1 = threading.Thread(target=write)
68 | t2 = threading.Thread(target=smile)
69 | t1.start()
70 | t2.start()
71 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/reject.txt:
--------------------------------------------------------------------------------
1 | [[2641, 1451, 3297, 3407, 2420, 539], [1420, 2692, 852, 642, 1772, 3326]]
2 | [[2641, 1451, 3297, 3407, 2419, 539], [1420, 2692, 852, 642, 1773, 3326]]
3 | [[2640, 1451, 3297, 3408, 2418, 539], [1421, 2692, 852, 639, 1776, 3326]]
4 | [[2639, 1451, 3297, 3409, 2417, 539], [1423, 2692, 852, 629, 1777, 3325]]
5 | [[2625, 1451, 3297, 3410, 2419, 539], [1423, 2692, 852, 628, 1777, 3325]]
6 | [[2624, 1451, 3297, 3409, 2419, 539], [1432, 2692, 852, 632, 1778, 3325]]
7 | [[2629, 1451, 3297, 3395, 2412, 536], [1439, 2692, 852, 666, 1790, 3330]]
8 | [[2673, 1451, 3297, 3356, 2396, 533], [1409, 2692, 852, 702, 1813, 3334]]
9 | [[2737, 1451, 3297, 3267, 2372, 526], [1359, 2694, 916, 781, 1852, 3334]]
10 | [[2806, 1451, 3297, 3208, 2367, 523], [1312, 2702, 1006, 900, 1878, 3341]]
11 | [[2869, 1451, 3297, 3149, 2357, 519], [1261, 2751, 1042, 922, 1899, 3341]]
12 | [[2933, 1451, 3297, 3121, 2353, 514], [1206, 2802, 1084, 939, 1914, 3340]]
13 | [[3008, 1451, 3297, 3089, 2346, 513], [1142, 2837, 1117, 961, 1919, 3340]]
14 | [[3067, 1451, 3297, 3041, 2343, 513], [1072, 2863, 1122, 962, 1909, 3341]]
15 | [[3110, 1424, 3297, 3028, 2365, 511], [1028, 2900, 1122, 935, 1876, 3345]]
16 | [[3130, 1366, 3297, 3082, 2393, 511], [1015, 2931, 1122, 921, 1844, 3351]]
17 | [[3124, 1360, 3296, 3096, 2417, 512], [1028, 2931, 1122, 949, 1812, 3360]]
18 | [[3093, 1361, 3290, 3102, 2426, 513], [1031, 2931, 1122, 958, 1793, 3363]]
19 | [[3079, 1358, 3259, 3097, 2438, 513], [1041, 2931, 1122, 961, 1791, 3367]]
20 | [[3071, 1358, 3259, 3090, 2440, 511], [1042, 2931, 1122, 974, 1793, 3371]]
21 | [[3057, 1358, 3259, 3088, 2445, 510], [1051, 2931, 1122, 973, 1797, 3372]]
22 | [[3050, 1358, 3259, 3088, 2455, 508], [1067, 2931, 1119, 971, 1794, 3375]]
23 | [[3047, 1358, 3259, 3081, 2464, 500], [1062, 2931, 1119, 977, 1792, 3375]]
24 | [[3047, 1358, 3259, 3080, 2470, 499], [1060, 2931, 1119, 981, 1793, 3375]]
25 | [[3047, 1358, 3259, 3079, 2475, 499], [1053, 2931, 1119, 976, 1791, 3375]]
26 | [[3047, 1358, 3259, 3079, 2476, 499], [1038, 2931, 1119, 979, 1793, 3375]]
27 | [[3051, 1358, 3259, 3079, 2478, 499], [1038, 2931, 1119, 979, 1792, 3375]]
28 | [[3053, 1358, 3259, 3076, 2479, 499], [1038, 2931, 1119, 979, 1792, 3375]]
29 | [[3054, 1358, 3259, 3074, 2479, 498], [1038, 2931, 1119, 980, 1790, 3375]]
30 | [[3054, 1358, 3259, 3074, 2477, 498], [1038, 2931, 1119, 981, 1790, 3375]]
31 | [[3054, 1358, 3259, 3074, 2476, 498], [1038, 2931, 1119, 981, 1790, 3375]]
32 | [[3054, 1358, 3259, 3074, 2475, 498], [1038, 2931, 1119, 980, 1788, 3375]]
33 | [[3054, 1358, 3259, 3074, 2473, 498], [1033, 2931, 1119, 976, 1788, 3375]]
34 | [[3054, 1358, 3259, 3074, 2473, 498], [1033, 2931, 1119, 976, 1788, 3375]]
35 | [[3054, 1358, 3259, 3074, 2472, 498], [1032, 2931, 1119, 976, 1788, 3375]]
36 | [[3049, 1358, 3259, 3074, 2471, 498], [1041, 2931, 1119, 971, 1786, 3375]]
37 | [[3051, 1358, 3259, 3074, 2471, 498], [1038, 2931, 1119, 974, 1786, 3375]]
38 | [[3053, 1358, 3259, 3074, 2469, 498], [1037, 2931, 1119, 975, 1786, 3375]]
39 | [[3053, 1358, 3259, 3074, 2469, 498], [1036, 2931, 1119, 977, 1787, 3375]]
40 | [[3054, 1358, 3259, 3074, 2467, 498], [1035, 2931, 1119, 976, 1787, 3375]]
41 | [[3054, 1358, 3259, 3074, 2466, 498], [1035, 2931, 1118, 975, 1787, 3375]]
42 | [[3054, 1358, 3259, 3074, 2462, 497], [1036, 2931, 1118, 974, 1787, 3375]]
43 | [[3051, 1358, 3259, 3074, 2460, 496], [1046, 2931, 1118, 972, 1788, 3375]]
44 | [[2991, 1361, 3259, 3077, 2459, 496], [1115, 2931, 1118, 947, 1782, 3375]]
45 | [[2890, 1361, 3259, 3088, 2463, 496], [1202, 2929, 1118, 907, 1769, 3374]]
46 | [[2827, 1362, 3259, 3125, 2475, 506], [1298, 2916, 1118, 828, 1723, 3364]]
47 | [[2740, 1391, 3259, 3142, 2483, 511], [1374, 2864, 1118, 802, 1693, 3360]]
48 | [[2683, 1488, 3259, 3141, 2523, 514], [1425, 2813, 1118, 794, 1668, 3360]]
49 | [[2638, 1539, 3259, 3145, 2549, 515], [1428, 2752, 1118, 802, 1666, 3357]]
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/symphony.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock,Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 | # Release the arms and record the points passed
15 | def read():
16 | time.sleep(10)
17 | t = time.time()
18 | record_list = []
19 | print(1)
20 | while time.time() - t <20:
21 | angles_1 = mc.get_encoders(1)
22 | angles_2 = mc.get_encoders(2)
23 | if angles_1 and angles_2:
24 | record_list.append([angles_1, angles_2])
25 | time.sleep(0.1)
26 |
27 | # Print the read location information, copy and save it as a txt file
28 | for i in record_list:
29 | print(i)
30 |
31 |
32 | # Take out and use the saved location
33 | def write():
34 | time.sleep(1.5)
35 | # The file here uses the saved txt file
36 | data = list(filter(None,open(os.path.join(os.getcwd(),'data_musician.txt')).read().splitlines()))
37 | # infinite loop
38 | while True:
39 | for angles in data:
40 | print(angles)
41 | mc.set_encoders(1, eval(angles)[0], 100)
42 | time.sleep(0.03)
43 | mc.set_encoders(2, eval(angles)[1], 100)
44 | time.sleep(0.2)
45 |
46 | # show emoji
47 | def smile():
48 | # The location where the emoji file is stored
49 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
50 | out_win = "l"
51 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
52 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
53 | # infinite loop
54 | while True:
55 | ret, frame = cap.read()
56 | if frame is not None:
57 | print(1)
58 | cv.imshow(out_win, frame)
59 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
60 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
61 |
62 |
63 | if __name__ == '__main__':
64 | # run with multithreading
65 | t1 = threading.Thread(target=write)
66 | t2 = threading.Thread(target=smile)
67 | t1.start()
68 | t2.start()
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/thanHeart.py:
--------------------------------------------------------------------------------
1 | # coding=utf8
2 | import os
3 | import time
4 | from pymycobot.mybuddy import MyBuddy
5 | import threading
6 | from threading import Lock, Thread
7 | import cv2 as cv
8 |
9 |
10 | # Establish serial connection
11 | mc = MyBuddy('/dev/ttyACM0', 115200)
12 |
13 |
14 |
15 | # Release the arms and record the points passed
16 | def read():
17 | time.sleep(3)
18 | mc.release_all_servos()
19 | time.sleep(10)
20 | t = time.time()
21 | record_list = []
22 | print(1)
23 | while time.time() - t < 15:
24 | angles_1 = mc.get_encoders(1)
25 | angles_2 = mc.get_encoders(2)
26 | if angles_1 and angles_2:
27 | record_list.append([angles_1, angles_2])
28 | time.sleep(0.1)
29 |
30 | # Print the read location information, copy and save it as a txt file
31 | for i in record_list:
32 | print(i)
33 |
34 |
35 | # Take out and use the saved location
36 | def write():
37 | time.sleep(1.5)
38 | # The file here uses the saved txt file
39 | data = list(filter(None, open(os.path.join(os.getcwd(), 'thanHeart.txt')).read().splitlines()))
40 | # infinite loop
41 | while True:
42 | for angles in data:
43 | print(angles)
44 | mc.set_encoders(1, eval(angles)[0], 100)
45 | time.sleep(0.05)
46 | mc.set_encoders(2, eval(angles)[1], 100)
47 | time.sleep(0.1)
48 |
49 |
50 | # show emoji
51 | def smile():
52 | # The location where the emoji file is stored
53 | cap = cv.VideoCapture("/home/ubuntu/emo/face_video_3_2.mp4")
54 | out_win = "l"
55 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
56 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
57 | # infinite loop
58 | while True:
59 | ret, frame = cap.read()
60 | if frame is not None:
61 | print(1)
62 | cv.imshow(out_win, frame)
63 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
64 | cap = cv.VideoCapture("/home/ubuntu/emo/look_happy.mp4")
65 |
66 |
67 | if __name__ == '__main__':
68 | # run with multithreading
69 | t1 = threading.Thread(target=write)
70 | t2 = threading.Thread(target=smile)
71 | t1.start()
72 | t2.start()
73 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_Action/thanHeart.txt:
--------------------------------------------------------------------------------
1 | [[2018, 2029, 1567, 2079, 4091, 872], [1995, 2003, 2384, 2074, 177, 3202]]
2 | [[2018, 2029, 1567, 2079, 4090, 872], [1995, 2010, 2377, 2086, 187, 3203]]
3 | [[2018, 2030, 1567, 2083, 4088, 871], [1995, 2010, 2379, 2089, 187, 3204]]
4 | [[2017, 2030, 1567, 2086, 4081, 872], [2023, 1998, 2385, 2050, 187, 3201]]
5 | [[2012, 2150, 1567, 2034, 4066, 871], [2085, 1885, 2382, 2028, 158, 3199]]
6 | [[2012, 2174, 1567, 2034, 4050, 871], [2101, 1838, 2384, 2007, 158, 3200]]
7 | [[1993, 2218, 1566, 2081, 4029, 873], [2115, 1794, 2385, 1959, 148, 3200]]
8 | [[1994, 2283, 1487, 2125, 4059, 873], [2139, 1627, 2450, 1895, 132, 3209]]
9 | [[1938, 2281, 1192, 1827, 4094, 874], [2164, 1638, 2680, 2105, 131, 3209]]
10 | [[1910, 2397, 1282, 1850, 4094, 870], [2185, 1627, 2804, 2200, 131, 3212]]
11 | [[1908, 2434, 1284, 1881, 4094, 868], [2205, 1625, 2898, 2181, 131, 3212]]
12 | [[1877, 2475, 1277, 1955, 4094, 862], [2218, 1624, 2922, 2183, 131, 3212]]
13 | [[1869, 2467, 1206, 1926, 4094, 861], [2222, 1537, 2921, 2261, 131, 3211]]
14 | [[1859, 2478, 1080, 1751, 4094, 860], [2219, 1512, 2930, 2246, 131, 3211]]
15 | [[1846, 2479, 1081, 1807, 4094, 860], [2218, 1508, 2932, 2217, 131, 3222]]
16 | [[1852, 2474, 1080, 1778, 4094, 805], [2200, 1509, 2999, 2324, 131, 3274]]
17 | [[1855, 2470, 1071, 1787, 4094, 757], [2196, 1518, 3044, 2395, 132, 3303]]
18 | [[1863, 2473, 1071, 1787, 4094, 729], [2209, 1521, 3044, 2365, 132, 3309]]
19 | [[1863, 2475, 1071, 1783, 4094, 733], [2216, 1521, 3044, 2352, 132, 3306]]
20 | [[1863, 2470, 1070, 1800, 4094, 735], [2216, 1521, 3044, 2362, 132, 3306]]
21 | [[1864, 2475, 1070, 1789, 4094, 728], [2215, 1521, 3044, 2372, 132, 3307]]
22 | [[1864, 2473, 1070, 1792, 4094, 726], [2216, 1521, 3044, 2349, 132, 3304]]
23 | [[1864, 2475, 1069, 1804, 4094, 726], [2217, 1521, 3044, 2339, 132, 3297]]
24 | [[1864, 2477, 1069, 1804, 4094, 726], [2215, 1521, 3044, 2343, 132, 3295]]
25 | [[1864, 2475, 1069, 1805, 4093, 727], [2214, 1521, 3044, 2344, 132, 3294]]
26 | [[1864, 2477, 1069, 1805, 4084, 728], [2210, 1507, 2902, 2178, 132, 3290]]
27 | [[1864, 2478, 1069, 1784, 4088, 728], [2210, 1507, 2900, 2177, 132, 3290]]
28 | [[1864, 2479, 1069, 1773, 4088, 728], [2210, 1504, 2902, 2173, 132, 3291]]
29 | [[1864, 2479, 1069, 1763, 4090, 729], [2202, 1443, 2889, 2236, 132, 3290]]
30 | [[1864, 2478, 1069, 1758, 4091, 731], [2195, 1465, 2899, 2224, 132, 3285]]
31 | [[1864, 2478, 1069, 1756, 4091, 731], [2194, 1459, 2899, 2225, 132, 3283]]
32 | [[1864, 2478, 1069, 1755, 4091, 731], [2194, 1459, 2899, 2226, 132, 3283]]
33 | [[1864, 2478, 1069, 1774, 4091, 731], [2194, 1455, 2900, 2225, 132, 3283]]
34 | [[1864, 2473, 1069, 1828, 4087, 731], [2194, 1454, 2900, 2181, 132, 3282]]
35 | [[1864, 2478, 1069, 1831, 4088, 731], [2194, 1454, 2900, 2167, 132, 3279]]
36 | [[1864, 2478, 1069, 1844, 4091, 732], [2192, 1454, 2900, 2150, 132, 3277]]
37 | [[1864, 2478, 1069, 1870, 4091, 733], [2191, 1454, 2900, 2139, 132, 3274]]
38 | [[1864, 2478, 1069, 1873, 4093, 733], [2190, 1454, 2900, 2135, 132, 3272]]
39 | [[1864, 2478, 1069, 1874, 4093, 733], [2190, 1454, 2900, 2134, 132, 3272]]
40 | [[1864, 2479, 1069, 1870, 4094, 733], [2190, 1454, 2900, 2133, 132, 3270]]
41 | [[1864, 2479, 1069, 1859, 4094, 734], [2191, 1454, 2900, 2136, 132, 3265]]
--------------------------------------------------------------------------------
/demo/mybuddy_demo/myBuddy_gpio_test.py:
--------------------------------------------------------------------------------
1 | #import library
2 | import time
3 | import os
4 | import sys
5 | import serial
6 | import serial.tools.list_ports
7 | import platform
8 | sys.path.append(os.getcwd())
9 | from pymycobot.mybuddy import MyBuddy
10 |
11 | #define type
12 | port: str
13 | mc: MyBuddy
14 | DEBUG = False
15 |
16 | # auto select system port
17 | if platform.system() == 'Windows':
18 | port = 'COM21'
19 | baud = 115200
20 | elif platform.system() == 'Linux':
21 | port = '/dev/ttyACM0'
22 | baud = 115200
23 |
24 |
25 | # Connect Robot
26 | mc = MyBuddy(port, baud, debug=DEBUG)
27 | time.sleep(1)
28 |
29 | # Test IO output
30 | pin_no = 15
31 | mc.set_gpio_init_mode(0)
32 | mc.set_gpio_setup(pin_no,1)
33 |
34 | mc.set_gpio_output(pin_no,1)
35 | time.sleep(2)
36 | mc.set_gpio_output(pin_no,0)
37 | time.sleep(2)
38 | mc.set_gpio_clearup(pin_no)
39 |
40 | # #Test io_pwm output
41 | # mc.set_gpio_pwm_start(3,0.5,50)
42 | # time.sleep(2)
43 | # mc.set_gpio_pwm_change_dc(100)
44 | # time.sleep(2)
45 | # mc.set_gpio_pwm_change_freq(100)
46 | # time,time.sleep(2)
47 | # mc.set_gpio_pwm_stop()
48 | # time.sleep(1)
49 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/mybuddy_change_pid.py:
--------------------------------------------------------------------------------
1 | #import library
2 | import time
3 | import os
4 | import sys
5 | import serial
6 | import serial.tools.list_ports
7 | import platform
8 |
9 | sys.path.append(os.getcwd())
10 | from pymycobot.mybuddy import MyBuddy
11 |
12 | #define type
13 | port: str
14 | mc: MyBuddy
15 | DEBUG = False
16 |
17 | # Connect Robot
18 |
19 | data_id = [21, 22, 23, 24, 26, 27]
20 | data = [25, 25, 1, 0, 3, 3]
21 | mb : MyBuddy
22 | ports = []
23 |
24 | def setup(): #机械臂检测函数,选择正确的串口
25 | global mb
26 | # auto select system port
27 | if platform.system() == 'Windows':
28 | port = 'COM21'
29 | baud = 115200
30 | elif platform.system() == 'Linux':
31 | port = '/dev/ttyACM0'
32 | baud = 115200
33 | mb = MyBuddy(port, baud, debug=DEBUG)
34 | time.sleep(1)
35 |
36 | def change():
37 | global mb, data, data_id
38 | _mybuddy = mb
39 | print(_mybuddy)
40 | for m in range(1,3):
41 | for i in range(1,7):
42 | for j in range(len(data_id)):
43 | _mybuddy.set_servo_data(m, i, data_id[j], data[j])
44 | time.sleep(0.1)
45 | _data = _mybuddy.get_servo_data(m, i, data_id[j])
46 | time.sleep(0.1)
47 | if _data == data[j]:
48 | print("Servo motor :" + str(i) + " data_id : " + str(data_id[j]) + " data: " + str(_data) + " modify successfully ")
49 | else:
50 | print("Servo motor :" + str(i) + " data_id : " + str(data_id[j]) + " data: " + str(_data) + " modify error ")
51 |
52 | if __name__ == "__main__": #主函数
53 | setup()
54 | try:
55 | change()
56 | except Exception as e:
57 | print(e)
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/mybuddy_emoticon_demo.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyBuddyEmoticon
2 | import time
3 |
4 | # [video_path, Playback_duration(s)]
5 | video1 = ["/home/er/pymycobot/emo/face_video_3_2.mp4", 10]
6 |
7 | datas = [video1]
8 |
9 | me = MyBuddyEmoticon(datas)
10 | me.start()
11 |
12 | time.sleep(3)
13 | # Pause playback
14 | me.pause()
15 |
16 | time.sleep(3)
17 | # Continue playing
18 | me.run()
19 |
20 | # Waiting for playback to complete
21 | me.join()
--------------------------------------------------------------------------------
/demo/mybuddy_demo/mybuddy_encoders_test.py:
--------------------------------------------------------------------------------
1 | #import library
2 | import time
3 | import os
4 | import sys
5 | import serial
6 | import serial.tools.list_ports
7 | import platform
8 | sys.path.append(os.getcwd())
9 | from pymycobot.mybuddy import MyBuddy
10 |
11 | #define type
12 | port: str
13 | mc: MyBuddy
14 | DEBUG = False
15 |
16 | # auto select system port
17 | if platform.system() == 'Windows':
18 | port = 'COM21'
19 | baud = 115200
20 | elif platform.system() == 'Linux':
21 | port = '/dev/ttyACM0'
22 | baud = 115200
23 |
24 | # demo encoders and speeds
25 | encoders = [2047,2047,2047,2047,2047,2047,2047, 2047,2047,2047,2047,2047,2047,2047, 2047] # Lram + gipper & Rram + gipper & Wram encoders
26 | speeds = [500,500,500,500,500,500,500, 500,500,500,500,500,500,500, 500] # Lram + gipper & Rram + gipper & Wram speeds
27 |
28 | # Connect Robot
29 | mc = MyBuddy(port, baud, debug=DEBUG)
30 | time.sleep(1)
31 |
32 | # Test IO output
33 | mc.set_gpio_mode(1,1)
34 | mc.set_gpio_output(1,1)
35 | time.sleep(2)
36 | mc.set_gpio_output(1,0)
37 | time.sleep(2)
38 | mc.set_gpio_clearup(1)
39 |
40 | #Test io_pwm output
41 | mc.set_gpio_pwm_start(3,0.5,50)
42 | time.sleep(2)
43 | mc.set_gpio_pwm_change_dc(100)
44 | time.sleep(2)
45 | mc.set_gpio_pwm_change_freq(100)
46 | time,time.sleep(2)
47 | mc.set_gpio_pwm_stop()
48 | time.sleep(1)
49 |
50 | #
51 | iic = mc.set_iic_init(1)
52 |
53 |
54 |
55 | # print all encoders and speeds
56 | print(mc.get_encoders(0))
57 |
58 | # set run demo encoders,init robot
59 | mc.set_encoders(0,encoders,speeds)
60 |
--------------------------------------------------------------------------------
/demo/mybuddy_demo/mybuddy_send_angles_auto.py:
--------------------------------------------------------------------------------
1 | import imp
2 |
3 |
4 | import os
5 | import sys
6 | sys.path.append(os.getcwd())
7 | from pymycobot.mybuddy import MyBuddy
8 |
9 | mb = MyBuddy('COM4',115200)
10 |
11 | mb.send_angles_auto(1,[0,0,0,0,0,0],1)
12 |
13 |
--------------------------------------------------------------------------------
/demo/mybuddy_emo.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyBuddyEmoticon
2 | import time
3 |
4 | file_path = [
5 | ['/home/er/emo/look_happy.mp4', 10]
6 | ]
7 |
8 | em = MyBuddyEmoticon(file_path, loop=True)
9 |
10 | em.start()
11 | time.sleep(5)
12 |
13 | # 暂停
14 | em.pause()
15 |
16 | time.sleep(2)
17 |
18 | # 继续播放
19 | em.run()
20 |
21 | # 等待播放结束
22 | em.join()
--------------------------------------------------------------------------------
/demo/mycobot_pi_bluetooth/README.md:
--------------------------------------------------------------------------------
1 | # Used for mycobot pi and mycobot_app
2 |
3 | ## Usage method
4 |
5 | ### 1.Make sure raspberry pi Bluetooth is available
6 |
7 | The Ubuntu 20.04 system needs to restart the Bluetooth service first.
8 |
9 | ```shell
10 | sudo systemctl restart bluetooth
11 | ```
12 |
13 | ### 2.Run Bluetooth server
14 |
15 | ```shell
16 | python uart_peripheral_serial.py
17 | ```
--------------------------------------------------------------------------------
/demo/mycobot_pi_bluetooth/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/demo/mycobot_pi_bluetooth/__init__.py
--------------------------------------------------------------------------------
/demo/mycobot_pi_bluetooth/app.py:
--------------------------------------------------------------------------------
1 | import sys, time, threading, logging
2 | sys.path.append('.')
3 |
4 | from ai import singleton, parameters, functools, coloredlogging
5 |
6 | logger = coloredlogging.get_logger("AS", coloredlogging.BLUE)
7 | logger.addHandler(logging.NullHandler())
8 |
9 | class AppStates(metaclass=singleton.Singleton):
10 | happiness = 4
11 | hungry = 4
12 | energy = 4
13 | comfort = 4
14 | counter = 0
15 |
16 | def __init__(self) -> None:
17 | ...
18 |
19 | @classmethod
20 | def recover(cls, genre):
21 | if genre == 'energy':
22 | cls.energy += 1
23 | cls.energy = min(4, cls.energy)
24 | elif genre == 'happiness':
25 | cls.happiness += 1
26 | cls.happiness = min(4, cls.happiness)
27 | elif genre == 'hungry':
28 | cls.happiness += 1
29 | cls.happiness = min(4, cls.happiness)
30 | elif genre == 'comfort':
31 | cls.comfort += 1
32 | cls.comfort = min(4, cls.comfort)
33 |
34 | @classmethod
35 | def drop(cls, genre: str):
36 | if genre == 'energy':
37 | cls.energy -= 1
38 | cls.energy = max(0, cls.energy)
39 | elif genre == 'happiness':
40 | cls.happiness -= 1
41 | cls.happiness = max(0, cls.happiness)
42 | elif genre == 'hungry':
43 | cls.happiness -= 1
44 | cls.happiness = max(0, cls.happiness)
45 | elif genre == 'comfort':
46 | cls.comfort -= 1
47 | cls.comfort = max(0, cls.comfort)
48 |
49 | @classmethod
50 | def recover_by_action(cls, action: str):
51 | if action == 'eat':
52 | cls.recover('hungry')
53 | elif action.startswith('touch'):
54 | cls.recover('comfort')
55 | elif action in parameters.BEHAVIOURS['relax']:
56 | cls.recover('energy')
57 | elif action.startswith('voice') or action.startswith(
58 | 'stare') or action in ['ball', 'attack', 'flap']:
59 | cls.recover('happiness')
60 |
61 | @classmethod
62 | @functools.thread_run
63 | def async_run(cls):
64 | logger.debug(f'Starting Stats recorder')
65 | while ...:
66 | time.sleep(60 * 10)
67 | AppStates.counter += 1
68 | cls.drop('energy')
69 | if AppStates.counter % 2 == 0:
70 | cls.drop('happiness')
71 | cls.drop('comfort')
72 | elif AppStates.counter % 12 == 0:
73 | cls.drop('hungry')
74 |
75 |
--------------------------------------------------------------------------------
/demo/mycobot_pi_bluetooth/bt_client.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import bluetooth
3 |
4 |
5 | if __name__ == "__main__":
6 | addr = None
7 |
8 | if len(sys.argv) < 2:
9 | print("No device specified. Searching all nearby bluetooth devices for the marscat_bt service...")
10 | else:
11 | addr = sys.argv[1]
12 | print("Searching for marscat_bt on {}...".format(addr))
13 |
14 | uuid = '26754beb-1bd0-4017-b341-154bed30b71a'
15 | service_matches = bluetooth.find_service(uuid=uuid, address=addr)
16 |
17 | if len(service_matches) == 0:
18 | print("Couldn't find the marscat_bt service.")
19 | sys.exit(0)
20 |
21 | first_match = service_matches[0]
22 | port = first_match["port"]
23 | name = first_match["name"]
24 | host = first_match["host"]
25 |
26 | print("Connecting to \"{}\" on {}".format(name, host))
27 |
28 | # Create the client socket
29 | sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
30 | sock.connect((host, port))
31 |
32 | print("Connected. Type something...")
33 | while True:
34 | data = input()
35 | if not data:
36 | break
37 | sock.send(data)
38 |
39 | sock.close()
40 |
--------------------------------------------------------------------------------
/demo/mycobot_pi_bluetooth/timezone.py:
--------------------------------------------------------------------------------
1 | import sys, subprocess
2 | sys.path.append('.')
3 |
4 |
5 | def getLocaleTimeZone() -> str:
6 | resp: str = subprocess.run(['ls -l /etc/localtime'],
7 | stdout=subprocess.PIPE,
8 | shell=True).stdout.decode('utf-8')
9 | t = resp.split('->')[1]
10 | l = t.split('/')
11 | timezone = f'{l[-2]}/{l[-1]}'.replace('\n','').replace('\r','')
12 | return timezone
13 |
14 | def setTimeZone(timezone:str):
15 | subprocess.run([f'sudo timedatectl set-timezone {timezone}'],
16 | stdout=subprocess.PIPE,
17 | shell=True)
18 |
19 | if __name__ == "__main__":
20 | getLocaleTimeZone()
21 |
--------------------------------------------------------------------------------
/demo/pid_read_write.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyCobot280, MyCobot320
2 | # from pymycobot import PI_PORT
3 | import time
4 | import serial
5 |
6 | # pi
7 | # 280
8 | # mc = MyCobot280(PI_PORT, 1000000)
9 | # mc = MyCobot280('/dev/ttyAMA0', 1000000)
10 | # 320
11 | # mc = MyCobot320(PI_PORT, 115200)
12 | # mc = MyCobot320('/dev/ttyAMA0', 115200)
13 |
14 | # M5
15 | # 280
16 | mc = MyCobot280('COM66', 115200)
17 | # mc = MyCobot280('/dev/ttyUSB0',115200)
18 |
19 | # 320
20 | # mc = MyCobot320('COM66', 115200)
21 | # mc = MyCobot320('/dev/ttyUSB0',115200)
22 |
23 | # 参数对应地址
24 | data_id = [7, 21, 22, 23, 24, 26, 27]
25 | # 修改后的参数
26 | data = [0, 32, 8, 0, 0, 3, 3]
27 |
28 | def read():
29 | for i in range(1, 7):
30 | for j in range(7):
31 | print("Servo motor " + str(i) + " data_id " +str(data_id[j]) + " : " + str(mc.get_servo_data(i, data_id[j])) )
32 | time.sleep(0.2)
33 |
34 | def write():
35 | for i in range(1,7):
36 | for j in range(7):
37 | mc.set_servo_data(i, data_id[j], data[j])
38 | time.sleep(0.5)
39 |
40 | if __name__ == "__main__":
41 | mc.power_on()
42 | time.sleep(2)
43 | # 写入参数(第一次使用先读取再进行修改)
44 | write()
45 | # 读取参数
46 | read()
47 |
--------------------------------------------------------------------------------
/demo/port_setup.py:
--------------------------------------------------------------------------------
1 | import serial
2 | import serial.tools.list_ports
3 |
4 | from pymycobot.mycobot280 import MyCobot280
5 |
6 |
7 |
8 | def setup():
9 | print("")
10 |
11 | plist = list(serial.tools.list_ports.comports())
12 | idx = 1
13 | for port in plist:
14 | print("{} : {}".format(idx, port))
15 | idx += 1
16 |
17 | _in = input("\nPlease input 1 - {} to choice:".format(idx - 1))
18 | port = str(plist[int(_in) - 1]).split(" - ")[0].strip()
19 | print(port)
20 | print("")
21 |
22 | baud = 115200
23 | _baud = input("Please input baud(default:115200):")
24 | try:
25 | baud = int(_baud)
26 | except Exception:
27 | pass
28 | print(baud)
29 | print("")
30 |
31 | DEBUG = False
32 | f = input("Wether DEBUG mode[Y/n]:")
33 | if f in ["y", "Y", "yes", "Yes"]:
34 | DEBUG = True
35 | # mc = MyCobot(port, debug=True)
36 | mc = MyCobot280(port, baud, debug=DEBUG)
37 | return mc
38 |
39 |
--------------------------------------------------------------------------------
/demo/reader.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyCobot280, MyCobot320
2 | from port_setup import setup
3 |
4 | # 280
5 | mc: MyCobot280
6 | sp: int = 80
7 |
8 | # 320
9 | # mc: MyCobot320
10 | # sp: int = 80
11 |
12 |
13 | def setup():
14 | print("")
15 | global mc
16 | mc = setup()
17 |
18 |
19 | def focus():
20 | for i in range(6):
21 | mc.focus_servo(i + 1)
22 |
23 |
24 | def release():
25 | for i in range(6):
26 | mc.release_servo(i + 1)
27 |
28 |
29 | def angles():
30 | print(mc.get_angles())
31 |
32 |
33 | def coords():
34 | print(mc.get_coords())
35 |
36 |
37 | if __name__ == "__main__":
38 | setup()
39 | while not False:
40 | in_ = int(input("number"))
41 | if in_ == 1:
42 | focus()
43 | elif in_ == 2:
44 | release()
45 | elif in_ == 3:
46 | angles()
47 | elif in_ == 4:
48 | coords()
49 |
--------------------------------------------------------------------------------
/demo/send_angle.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | sys.path.append(os.path.dirname(__file__))
4 | from port_setup import setup
5 |
6 | if __name__ == "__main__":
7 | mc = setup()
8 | _sp = input('Please input speed(0-100):')
9 | try:
10 | sp = int(_sp)
11 | except Exception:
12 | print('Error: invalid speed, speed is default: 80')
13 | sp = 80
14 |
15 | while not False:
16 | angles_str = input('Please input angles, like ("0,0,0,0,0,0"):')
17 | try:
18 | angles_str_l = angles_str.split(',')
19 | if len(angles_str_l) != 6:
20 | raise Exception('')
21 | angles = [float(i) for i in angles_str_l]
22 | except Exception:
23 | print('Error: invalid angles string.')
24 | continue
25 |
26 | mc.send_angles(angles, sp)
27 |
28 |
--------------------------------------------------------------------------------
/demo/sync.py:
--------------------------------------------------------------------------------
1 | import time
2 | import os
3 | import sys
4 | from pymycobot.mycobot import MyCobot
5 |
6 | sys.path.append(os.path.dirname(__file__))
7 | from port_setup import setup
8 |
9 | reset = [153.19, 137.81, -153.54, 156.79, 87.27, 13.62]
10 |
11 |
12 | def test(mycobot):
13 | print("\nStart check basic options\n")
14 |
15 | """
16 | mycobot.sync_send_angles([0,0,0,0,0,0], 100)
17 | mycobot.sync_send_angles([100,50,0,0,70,160], 100)
18 | mycobot.sync_send_angles([-100,-50,0,0,-70,-160], 100)
19 | """
20 | # mycobot.sync_send_angles([0, 0, 0, 0, 0, 0], 100).sync_send_angles(
21 | # [100, 50, 0, 0, 70, 160], 100
22 | # ).sync_send_angles([-100, -50, 0, 0, -70, -160], 100).sync_send_angles(
23 | # reset, 100
24 | # ).set_free_mode()
25 | # See: https://github.com/elephantrobotics/pymycobot/issues/144
26 | mycobot.sync_send_angles([0, 0, 0, 0, 0, 0], 100)
27 | mycobot.sync_send_angles([100, 50, 0, 0, 70, 160], 100)
28 | mycobot.sync_send_angles([-100,-50, 0, 0, -70,-160], 100)
29 | mycobot.set_free_mode(1)
30 |
31 | print("=== check end ===\n")
32 |
33 |
34 | if __name__ == "__main__":
35 | print(
36 | """
37 | --------------------------------------------
38 | | This file will test basic option method: |
39 | | sync_send_angles() |
40 | --------------------------------------------
41 | """
42 | )
43 | time.sleep(3)
44 | mycobot = setup()
45 | test(mycobot)
46 | # print(mycobot.get_angles())
47 |
--------------------------------------------------------------------------------
/demo/tools/pump_demo_M5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # This code is suitable for the use of the myCobot
4 | # series product pump provided by Elephant Robotics;
5 | # Please check the instructions for use of the
6 | # suction pump before use, please refer to here:
7 | # https://docs.elephantrobotics.com/docs/gitbook-en/2-serialproduct/2.7-accessories/2.7.4-pump.html
8 | # Running this code requires installing the 'pymycobot'
9 | # driver library and python driver environment.
10 | # If you don't installed, please refer to here :
11 | # https://docs.elephantrobotics.com/docs/gitbook-en/7-ApplicationBasePython/
12 |
13 | # import library
14 | from pymycobot import MyCobot280 #import mycobot library,if don't have, first 'pip install pymycobot'
15 | import time
16 |
17 | # if use PC and M5 control
18 | mc = MyCobot280('COM3', 115200) # WINDOWS use ,need check port number when you PC
19 | # mc = MyCobot('/dev/ttyUSB0',115200) #VM linux use
20 |
21 | #init robot
22 | mc.power_on()
23 | time.sleep(1)
24 |
25 | #define pump pin and work state
26 | pump_motor_pin = 5 # control vacuum pump motor work pin, can be modified
27 | pump_relay_pin = 2 # control vacuum pump relay work pin, can be modified
28 | pump_open = 0 # control vacuum pump motor work turn on
29 | pump_close = 1 # control vacuum pump motor work turn off
30 |
31 | #define api, If you are using the first generation or
32 | #earlier suction pump, then define his interface as follows:
33 | def pump_V1_on():
34 | mc.set_basic_output(pump_motor_pin, pump_open)
35 | time.sleep(0.05)
36 | mc.set_basic_output(pump_relay_pin, pump_open)
37 | time.sleep(0.05)
38 |
39 | def pump_V1_off():
40 | mc.set_basic_output(pump_motor_pin, pump_close)
41 | time.sleep(0.05)
42 | mc.set_basic_output(pump_relay_pin, pump_close)
43 | time.sleep(0.05)
44 |
45 | #If you are using the suction pump V2.0 version of
46 | # the device, then define his interface as follows:
47 | def pump_V2_on():
48 | mc.set_basic_output(pump_relay_pin, pump_close)
49 | time.sleep(0.05)
50 | mc.set_basic_output(pump_motor_pin, pump_open)
51 | time.sleep(0.05)
52 |
53 | def pump_V2_off():
54 | mc.set_basic_output(pump_relay_pin, pump_open)
55 | mc.set_basic_output(pump_motor_pin, pump_close)
56 | time.sleep(1.5)
57 | mc.set_basic_output(pump_relay_pin, pump_close)
58 | time.sleep(0.05)
59 |
60 |
61 | # demo control, First turn on the vacuum pump motor,
62 | # Then turn off the motor and turn on the relay to
63 | # introduce air.If you do not know the version of
64 | # your suction pump, please use it after checking
65 | # the instructions of the suction pump;
66 |
67 | # define pump V1.0 work demo
68 | # for i in range (5):
69 | # pump_V1_on()
70 | # time.sleep(5)
71 | # pump_V1_off()
72 |
73 | # define pump V2.0 work demo
74 | for i in range (5):
75 | pump_V2_on()
76 | time.sleep(5)
77 | pump_V2_off()
--------------------------------------------------------------------------------
/demo/tools/pump_demo_PI.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # This code is suitable for the use of the myCobot
4 | # series product pump provided by Elephant Robotics;
5 | # Please check the instructions for use of the
6 | # suction pump before use, please refer to here:
7 | # https://docs.elephantrobotics.com/docs/gitbook-en/2-serialproduct/2.7-accessories/2.7.4-pump.html
8 | # Running this code requires installing the 'pymycobot'
9 | # driver library and python driver environment.
10 | # If you don't installed, please refer to here :
11 | # https://docs.elephantrobotics.com/docs/gitbook-en/7-ApplicationBasePython/
12 |
13 | # import library
14 | from pymycobot import MyCobot280 #import mycobot library,if don't have, first 'pip install pymycobot'
15 | import time
16 | import RPi.GPIO as GPIO
17 | GPIO.setmode(GPIO.BCM)
18 | # if use Pi control
19 | mc = MyCobot280('/dev/ttyAMA0',1000000) #linux use
20 |
21 | #init robot
22 | mc.power_on()
23 | time.sleep(1)
24 |
25 | #define pump pin and work state
26 | pump_motor_pin = 20 # control vacuum pump motor work pin, can be modified
27 | pump_relay_pin = 21 # control vacuum pump relay work pin, can be modified
28 | pump_open = 0 # control vacuum pump motor work turn on
29 | pump_close = 1 # control vacuum pump motor work turn off
30 |
31 | def init_gpio(io_number, state):
32 | if state == 0:
33 | st = GPIO.OUT
34 | elif state == 1:
35 | st = GPIO.IN
36 | GPIO.setup(io_number, st)
37 |
38 | def init_pump_pin():
39 | init_gpio(pump_motor_pin,0)
40 | init_gpio(pump_relay_pin,0)
41 | #define api, If you are using the first generation or
42 | #earlier suction pump, then define his interface as follows:
43 | def pump_V1_on():
44 | GPIO.output(pump_motor_pin, pump_open)
45 | time.sleep(0.05)
46 | GPIO.output(pump_relay_pin, pump_open)
47 | time.sleep(0.05)
48 |
49 | def pump_V1_off():
50 | GPIO.output(pump_motor_pin, pump_close)
51 | time.sleep(0.05)
52 | GPIO.output(pump_relay_pin, pump_close)
53 | time.sleep(0.05)
54 |
55 | #If you are using the suction pump V2.0 version of
56 | # the device, then define his interface as follows:
57 | def pump_V2_on():
58 | GPIO.output(pump_motor_pin, pump_open)
59 | time.sleep(0.05)
60 |
61 | def pump_V2_off():
62 | GPIO.output(pump_motor_pin, pump_close)
63 | time.sleep(0.05)
64 | GPIO.output(pump_relay_pin, pump_open)
65 | time.sleep(1)
66 | GPIO.output(pump_relay_pin, pump_close)
67 | time.sleep(0.05)
68 |
69 | # demo control, First turn on the vacuum pump motor,
70 | # Then turn off the motor and turn on the relay to
71 | # introduce air.If you do not know the version of
72 | # your suction pump, please use it after checking
73 | # the instructions of the suction pump;
74 |
75 | # define pump V1.0 work demo
76 | # for i in range (5):
77 | # pump_V1_on()
78 | # time.sleep(5)
79 | # pump_V1_off()
80 |
81 | # define pump V2.0 work demo
82 | init_pump_pin()
83 | for i in range (5):
84 | pump_V2_on()
85 | time.sleep(5)
86 | pump_V2_off()
87 |
88 |
89 |
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/3-angles_control.py:
--------------------------------------------------------------------------------
1 | from pymycobot.ultraArmP340 import ultraArmP340
2 | import time
3 | import serial
4 | import serial.tools.list_ports
5 |
6 | #以上需写在代码开头,意为导入项目包
7 |
8 | # ultraArmP340 类初始化需要两个参数:串口和波特率
9 | # 第一个是串口字符串, 如:
10 | # linux: "/dev/ttyUSB0"
11 | # windows: "COM3"
12 | # 第二个是波特率:115200
13 | # 以下为如:
14 | # linux:
15 | # ua = ultraArmP340("/dev/USB0", 115200)
16 | # windows:
17 | # ua = ultraArmP340("COM3", 115200)
18 |
19 | # 获取串口列表
20 | plist = [
21 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
22 | ]
23 |
24 | # 初始化一个ultraArmP340对象
25 | # 下面为 windows版本创建对象代码
26 |
27 | ua = ultraArmP340(plist[0], 115200)
28 | # ultraArmP340进行坐标运动/角度运动之前必须进行回零,否则无法获取到正确的角度/坐标
29 | ua.go_zero()
30 | time.sleep(0.5)
31 |
32 | # 通过传递角度参数,让机械臂每个关节移动到对应[0, 0, 0]的位置
33 | ua.set_angles([0, 0, 0], 50)
34 |
35 | # 设置等待时间,确保机械臂已经到达指定位置
36 | time.sleep(2.5)
37 |
38 | # 让关节1移动到90这个位置
39 | ua.set_angle(1, 90, 50)
40 | # 设置等待时间,确保机械臂已经到达指定位置
41 | time.sleep(2)
42 |
43 | # 以下代码可以让机械臂左右摇摆
44 | # 设置循环次数
45 | num = 7
46 |
47 | while num > 0:
48 | # 让关节2移动到45这个位置
49 | ua.send_angle(2, 45, 50)
50 |
51 | # 设置等待时间,确保机械臂已经到达指定位置
52 | time.sleep(3)
53 |
54 | # 让关节2移动到-15这个位置
55 | ua.set_angle(2, -15, 50)
56 |
57 | # 设置等待时间,确保机械臂已经到达指定位置
58 | time.sleep(3)
59 |
60 | num -= 1
61 |
62 | # 让机械臂缩起来。你可以手动摆动机械臂,然后使用get_angles()函数获得坐标数列,
63 | # 通过该函数让机械臂到达你所想的位置。
64 | ua.set_angles([88.68, 60, 30], 50)
65 |
66 | # 设置等待时间,确保机械臂已经到达指定位置
67 | time.sleep(2.5)
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/4-coords_control.py:
--------------------------------------------------------------------------------
1 | from pymycobot.ultraArmP340 import ultraArmP340
2 | import time
3 | import serial
4 | import serial.tools.list_ports
5 |
6 | #以上需写在代码开头,意为导入项目包
7 |
8 | # ultraArmP340 类初始化需要两个参数:串口和波特率
9 | # 第一个是串口字符串, 如:
10 | # linux: "/dev/ttyUSB0"
11 | # windows: "COM3"
12 | # 第二个是波特率:115200
13 | # 以下为如:
14 | # linux:
15 | # ua = ultraArmP340("/dev/USB0", 115200)
16 | # windows:
17 | # ua = ultraArmP340("COM3", 115200)
18 | #
19 | # 获取串口列表
20 | plist = [
21 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
22 | ]
23 |
24 | # 初始化一个ultraArmP340对象
25 | # 下面为 windows版本创建对象代码
26 | ua = ultraArmP340(plist[0], 115200)
27 |
28 | # ultraArmP340进行坐标运动/角度运动之前必须进行回零,否则无法获取到正确的角度/坐标
29 | ua.go_zero()
30 | time.sleep(0.5)
31 |
32 | # 获取当前头部的坐标以及姿态
33 | coords = ua.get_coords_info()
34 | time.sleep(2)
35 | print(coords)
36 |
37 | # # 让机械臂到达[57.0,-10,30]这个坐标,速度为80mm/s
38 | ua.set_coords([57.0,-10,30], 80)
39 |
40 | # 设置等待时间2秒
41 | time.sleep(2)
42 |
43 | # 让机械臂到达[-13.7, 40, 20]这个坐标,速度为80mm/s
44 | ua.set_coords([-13.7, 40, 20], 80)
45 |
46 | # 设置等待时间2秒
47 | time.sleep(2)
48 |
49 | # 仅改变头部的x坐标,设置头部的x坐标为-40,速度为70mm/s
50 | ua.set_coord(1, -40, 70)
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/5-Palletizing_handling.py:
--------------------------------------------------------------------------------
1 | from pymycobot.ultraArmP340 import ultraArmP340
2 | import serial
3 | import serial.tools.list_ports
4 |
5 | # 被搬运的木块的坐标位置
6 | green_pos = [[74.6, 167.55, 120], [74.6, 167.55, 92.45], [74.6, 167.55, 52.45], [74.6, 167.55, 12.45]]
7 | red_pos = [[112.67, 173.5, 120], [112.67, 173.5, 92.45], [112.67, 173.5, 52.45], [112.67, 173.5, 12.45]]
8 | yellow_pos = [[150.92, 167.61, 120], [150.92, 167.61, 92.45], [150.92, 167.61, 52.45], [150.92, 167.61, 12.45]]
9 |
10 | # 木块到达的坐标位置
11 | cube_pos_g = [[200, -75, 120], [200, -75, 15], [200, -75, 55], [200, -75, 95]]
12 | cube_pos_r = [[150.63, -75, 15], [150.63, -75, 55], [150.63, -75, 95]]
13 | cube_pos_y = [[109.63, -75, 15], [109.63, -75, 55], [109.63, -75, 95]]
14 |
15 | # 被搬运的木块所在的方向
16 | block_high = [60, 5, 0]
17 |
18 | # 木块到达的位置所在方向
19 | cube_high = [-30, 10, 10]
20 |
21 | # 获取串口列表
22 | plist = [
23 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
24 | ]
25 |
26 | # 连接串口
27 | ua = ultraArmP340(plist[0],115200)
28 |
29 | # ultraArmP340进行坐标运动/角度运动之前必须进行回零,否则无法获取到正确的角度/坐标
30 | ua.go_zero()
31 | ua.sleep(0.5)
32 |
33 |
34 | # Yellow
35 | # 搬运第一个木块
36 | # 移动到木块所在方向
37 | ua.set_angles(block_high, 50)
38 | ua.sleep(0.5)
39 |
40 | ua.set_coords(yellow_pos[0], 50)
41 | ua.sleep(1)
42 |
43 | # 到达木块所在位置
44 | ua.set_coords(yellow_pos[1], 50)
45 | ua.sleep(1)
46 | # 打开吸泵
47 | ua.set_gpio_state(0)
48 | ua.sleep(0.5)
49 |
50 | # 移动到需要到达的位置上方
51 | ua.set_angles(cube_high, 50)
52 | ua.sleep(0.5)
53 |
54 | # 下降到需要到达的位置
55 | ua.set_coords(cube_pos_y[0], 50)
56 | ua.sleep(0.5)
57 | # 关闭吸泵
58 | ua.set_gpio_state(1)
59 | ua.sleep(0.5)
60 |
61 | # 移动到木块所在位置上方,一次搬运动作完成,后续搬运动作跟此次搬运动作一致
62 | ua.set_angles(cube_high, 50)
63 | ua.sleep(0.5)
64 |
65 | #2
66 | ua.set_angles(block_high, 50)
67 | ua.sleep(0.5)
68 |
69 | ua.set_coords(yellow_pos[0], 50)
70 | ua.sleep(1)
71 |
72 | ua.set_coords(yellow_pos[2], 50)
73 | ua.sleep(1)
74 | ua.set_gpio_state(0)
75 | ua.sleep(0.5)
76 |
77 | ua.set_angles(cube_high, 50)
78 | ua.sleep(0.5)
79 |
80 | ua.set_coords(cube_pos_y[1], 50)
81 | ua.sleep(0.5)
82 | ua.set_gpio_state(1)
83 | ua.sleep(0.5)
84 |
85 | ua.set_angles(cube_high, 50)
86 | ua.sleep(0.5)
87 |
88 | # Red
89 | # 1
90 | ua.set_angles(block_high, 50)
91 | ua.sleep(0.5)
92 |
93 | ua.set_coords(red_pos[0], 50)
94 | ua.sleep(1)
95 |
96 | ua.set_coords(red_pos[1], 50)
97 | ua.sleep(1)
98 | ua.set_gpio_state(0)
99 | ua.sleep(0.5)
100 |
101 | ua.set_angles(cube_high, 50)
102 | ua.sleep(0.5)
103 |
104 | ua.set_coords(cube_pos_r[0], 50)
105 | ua.sleep(0.5)
106 | ua.set_gpio_state(1)
107 | ua.sleep(0.5)
108 |
109 | ua.set_angles(cube_high, 50)
110 | ua.sleep(0.5)
111 |
112 | #2
113 | ua.set_angles(block_high, 50)
114 | ua.sleep(0.5)
115 |
116 | ua.set_coords(red_pos[0], 50)
117 | ua.sleep(1)
118 |
119 | ua.set_coords(red_pos[2], 50)
120 | ua.sleep(1)
121 | ua.set_gpio_state(0)
122 | ua.sleep(0.5)
123 |
124 | ua.set_angles(cube_high, 50)
125 | ua.sleep(0.5)
126 |
127 | ua.set_coords(cube_pos_r[1], 50)
128 | ua.sleep(0.5)
129 | ua.set_gpio_state(1)
130 | ua.sleep(0.5)
131 |
132 | ua.set_angles(cube_high, 50)
133 | ua.sleep(0.5)
134 |
135 |
136 | # Green
137 | # 1
138 | ua.set_angles(block_high, 50)
139 | ua.sleep(0.5)
140 |
141 | ua.set_coords(green_pos[0], 50)
142 | ua.sleep(1)
143 |
144 | ua.set_coords(green_pos[1], 50)
145 | ua.sleep(1)
146 | ua.set_gpio_state(0)
147 | ua.sleep(0.5)
148 |
149 | ua.set_angles(cube_high, 50)
150 | ua.sleep(0.5)
151 |
152 | ua.set_coords(cube_pos_g[0], 50)
153 | ua.sleep(0.5)
154 |
155 | ua.set_coords(cube_pos_g[1], 50)
156 | ua.sleep(0.5)
157 | ua.set_gpio_state(1)
158 | ua.sleep(0.5)
159 |
160 | ua.set_angles(cube_high, 50)
161 | ua.sleep(0.5)
162 |
163 | #2
164 | ua.set_angles(block_high, 50)
165 | ua.sleep(0.5)
166 |
167 | ua.set_coords(green_pos[0], 50)
168 | ua.sleep(1)
169 |
170 | ua.set_coords(green_pos[2], 50)
171 | ua.sleep(1)
172 | ua.set_gpio_state(0)
173 | ua.sleep(0.5)
174 |
175 | ua.set_angles(cube_high, 50)
176 | ua.sleep(0.5)
177 |
178 | ua.set_coords(cube_pos_g[0], 50)
179 | ua.sleep(0.5)
180 |
181 | ua.set_coords(cube_pos_g[2], 50)
182 | ua.sleep(0.5)
183 | ua.set_gpio_state(1)
184 | ua.sleep(0.5)
185 |
186 | ua.set_angles(cube_high, 50)
187 | ua.sleep(0.5)
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/6-laser_use.py:
--------------------------------------------------------------------------------
1 | from pymycobot.ultraArmP340 import ultraArmP340
2 | import time
3 | import serial
4 | import serial.tools.list_ports
5 |
6 | #以上需写在代码开头,意为导入项目包
7 |
8 | # ultraArmP340 类初始化需要两个参数:串口和波特率
9 | # 第一个是串口字符串, 如:
10 | # linux: "/dev/ttyUSB0"
11 | # windows: "COM3"
12 | # 第二个是波特率:115200
13 | # 以下为如:
14 | # linux:
15 | # ua = ultraArmP340("/dev/USB0", 115200)
16 | # windows:
17 | # ua = ultraArmP340("COM3", 115200)
18 | #
19 |
20 | plist = [
21 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
22 | ]
23 |
24 | # 初始化一个ultraArmP340对象
25 | # 下面为 windows版本创建对象代码
26 | ua = ultraArmP340(plist[0], 115200)
27 | ua.go_zero()
28 |
29 | time.sleep(2)
30 |
31 | ua.set_pwm(128)
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/8-gripper_use.py:
--------------------------------------------------------------------------------
1 | import time
2 | import platform
3 | import serial
4 | import serial.tools.list_ports
5 | from pymycobot.ultraArmP340 import ultraArmP340
6 |
7 | plist = [
8 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
9 | ]
10 |
11 | # 自动选择系统并连接机械臂
12 | if platform.system() == "Windows":
13 | ua = ultraArmP340(plist[0], 115200)
14 | ua.go_zero()
15 | elif platform.system() == "Linux":
16 | ua = ultraArmP340('/dev/ttyUSB0', 115200)
17 | ua.go_zero()
18 |
19 | # 机械臂运动的位置
20 | angles = [
21 | [-81.71, 0.0, 0.0],
22 | [-90.53, 21.77, 47.56],
23 | [-90.53, 0.0, 0.0],
24 | [-59.01, 21.77, 45.84],
25 | [-59.01, 0.0, 0.0]
26 | ]
27 |
28 | ua.set_angles(angles[0], 50)
29 | time.sleep(3)
30 |
31 | i = 5
32 | # 循环5次
33 | while i > 0:
34 | # 张开夹爪
35 | ua.set_gripper_state(0)
36 | time.sleep(2)
37 | # 闭合夹爪
38 | ua.set_gripper_state(1)
39 | time.sleep(2)
40 | i -= 1
--------------------------------------------------------------------------------
/demo/ultraArm_P340_demo/9-pump_use.py:
--------------------------------------------------------------------------------
1 | from pymycobot.ultraArmP340 import ultraArmP340
2 | import time
3 | import serial
4 | import serial.tools.list_ports
5 | #输入以上代码导入工程所需要的包
6 |
7 | # ultraArmP340 类初始化需要两个参数:
8 | # 第一个是串口字符串, 如:
9 | # linux: "/dev/ttyUSB0"
10 | # windows: "COM3"
11 | # 第二个是波特率: 115200
12 | #
13 | # 如:
14 | # linux:
15 | # ua = ultraArmP340("/dev/USB0", 115200)
16 | # windows:
17 | # ua = ultraArmP340("COM3", 115200)
18 | #
19 |
20 | plist = [
21 | str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
22 | ]
23 |
24 | # 初始化一个ultraArmP340对象
25 | # 下面为 windows版本创建对象代码
26 | ua = ultraArmP340(plist[0], 115200)
27 |
28 | # ultraArmP340进行坐标运动/角度运动之前必须进行回零,否则无法获取到正确的角度/坐标
29 | ua.go_zero()
30 | time.sleep(0.5)
31 |
32 | # 开启吸泵
33 | ua.set_gpio_state(0)
34 |
35 | #等待2 秒
36 | time.sleep(3)
37 |
38 |
39 | # 关闭吸泵
40 | ua.set_gpio_state(1)
41 |
42 | time.sleep(2)
--------------------------------------------------------------------------------
/docs/Mercury_X1_Chassis_en.md:
--------------------------------------------------------------------------------
1 | # Mercury X1 Chassis
2 |
3 | ---
4 |
5 | - **Prerequisites**
6 | - First, open a console terminal and run the following command to start chassis communication.
7 |
8 | ```bash
9 | roslaunch turn_on_mercury_robot mapping.launch
10 | ```
11 |
12 | - **API Usage Instructions**
13 | >> API (Application Programming Interface), also known as application programming interface function, is a predefined function. When using the following function interface, please enter the following code at the beginning to import our API library, otherwise it will not run successfully.
14 |
15 | ```python
16 | # demo
17 | from pymycobot import mercurychassis_api
18 |
19 | mc = ChassisControl('/dev/wheeltec_controller')
20 |
21 | # Get battery voltage
22 | voltage = mc.get_power_voltage()
23 | print(voltage)
24 |
25 | # Set the chassis RGB light strip to green
26 | mc.set_color(255, 0, 0)
27 | ```
28 |
29 | ## get_power_voltage()
30 |
31 | - Function: Get the battery voltage.
32 | - Return value: Battery voltage (floating point type), unit: Volt
33 |
34 | ## get_ultrasonic_value()
35 |
36 | - Function: Get all ultrasonic data.
37 | - Return value: List of all ultrasonic data, unit: millimeter.
38 |
39 | ## go_straight(speed)
40 |
41 | - Function: Control the chassis to move forward.
42 | - Parameters:
43 | - speed: (floating point type) the speed of chassis movement, the range is `0 ~ 1`, unit: meters per second.
44 |
45 | ## go_back(speed)
46 |
47 | - Function: Control chassis to move backward.
48 | - Parameters:
49 | - speed: (floating point type) chassis movement speed, range is `-1 ~ 0`, unit: meter per second.
50 |
51 | ## turn_left(speed)
52 |
53 | - Function: Control the chassis to rotate to the left.
54 | - Parameters:
55 | - speed: (floating point type) the speed of chassis movement, ranging from `0 ~ 1`, unit: meters per second.
56 |
57 | ## turn_right(speed)
58 |
59 | - Function: Control chassis to rotate right.
60 | - Parameters:
61 | - speed: (floating point type) chassis movement speed, range is `-1 ~ 0`, unit: meters per second.
62 |
63 | ## stop()
64 |
65 | - Function: Stop motion.
66 |
67 | ## set_color(r, g, b)
68 |
69 | - Function: Set the color of the chassis RGB light strip.
70 | - Parameters:
71 | - r (int): 0 ~ 255
72 | - g (int): 0 ~ 255
73 | - b (int): 0 ~ 255
74 |
75 |
--------------------------------------------------------------------------------
/docs/Mercury_X1_Chassis_zh.md:
--------------------------------------------------------------------------------
1 | # Mercury X1 Chassis
2 |
3 | ---
4 |
5 | - 使用前提
6 | - 先在打开一个控制台终端运行下面指令,启动底盘通信。
7 |
8 | ```bash
9 | roslaunch turn_on_mercury_robot mapping.launch
10 | ```
11 |
12 | - API使用说明
13 | >> API (Application Programming Interface), 也称为应用程序编程接口函数,是预定义的函数。使用以下函数接口时,请在开始时输入以下代码导入我们的 API 库,否则将无法成功运行.
14 |
15 | ```python
16 | # 示例
17 | from pymycobot import mercurychassis_api
18 |
19 | mc = ChassisControl('/dev/wheeltec_controller')
20 |
21 | # 获取电池电压
22 | voltage = mc.get_power_voltage()
23 | print(voltage)
24 |
25 | # 设置底盘RGB灯带为绿色
26 | mc.set_color(255, 0, 0)
27 | ```
28 |
29 | ## get_power_voltage()
30 |
31 | - 功能:获取电池电压。
32 | - 返回值:电池电压(浮点型),单位:伏特
33 |
34 | ## get_ultrasonic_value()
35 |
36 | - 功能:获取所有超声波数据
37 | - 返回值:所有超声波数据列表,单位:毫米。
38 |
39 | ## go_straight(speed)
40 |
41 | - 功能:控制底盘前进
42 | - 参数:
43 | - speed:(浮点型)底盘运动的速度,范围是`0 ~ 1`,单位:米每秒。
44 |
45 | ## go_back(speed)
46 |
47 | - 功能:控制底盘后退
48 | - 参数:
49 | - speed:(浮点型)底盘运动的速度,范围是`-1 ~ 0`,单位:米每秒。
50 |
51 | ## turn_left(speed)
52 |
53 | - 功能:控制底盘向左旋转
54 | - 参数:
55 | - speed:(浮点型)底盘运动的速度,范围是`0 ~ 1`,单位:米每秒。
56 |
57 | ## turn_right(speed)
58 |
59 | - 功能:控制底盘右旋转
60 | - 参数:
61 | - speed:(浮点型)底盘运动的速度,范围是`-1 ~ 0`,单位:米每秒。
62 |
63 | ## stop()
64 |
65 | - 功能:停止运动
66 |
67 | ## set_color(r, g, b)
68 |
69 | - 功能:设置底盘RGB灯带颜色
70 | - 参数:
71 | - r (int):0 ~ 255
72 | - g (int):0 ~ 255
73 | - b (int):0 ~ 255
74 |
75 |
--------------------------------------------------------------------------------
/docs/MyAGVPro_zh.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/docs/MyAGVPro_zh.md
--------------------------------------------------------------------------------
/docs/MyCobot_280_RDKX5_zh.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/docs/MyCobot_280_RDKX5_zh.md
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # pymycobot
2 |
3 | **This is python API for ElephantRobotics product**
4 |
5 | We support Python2, Python3.5 or later.
6 |
7 |  
8 |
9 | [MyCobot 280 API说明](./MyCobot_280_zh.md) | [MyCobot 280 API Description](./MyCobot_280_en.md)
10 |
11 | [MyCobot 320 API说明](./MyCobot_320_zh.md) | [MyCobot 320 API Description](./MyCobot_320_en.md)
12 |
13 | [MechArm 270 API说明](./MechArm_270_zh.md) | [MechArm 270 API Description](./MechArm_270_en.md)
14 |
15 | [MyPalletizer 260 API说明](./MyPalletizer_260_zh.md) | [MyPalletizer 260 API Description](./MyPalletizer_260_en.md)
16 |
17 | [myAGV API说明](./myAGV_zh.md) | [myAGV API Description](./myAGV_en.md)
18 |
19 | [myArm_M&C API说明](./myArm_M&C_zh.md) | [myArm_M&C API Description](./myArm_M&C_en.md)
20 |
21 | [ultraArm P340 API说明](./ultraArm_P340_zh.md) | [ultraArm P340 API Description](./ultraArm_P340_en.md)
22 |
23 | [MyBuddy API说明](./MyBuddy_zh.md) | [MyBuddy API Description](./MyBuddy_en.md)
24 |
25 | [MyBuddyEmoticon API说明](./mybuddy_emoticon_zh.md) | [MyBuddyEmoticon API Description](./mybuddy_emoticon_en.md)
26 |
27 |
28 | Catalogue:
29 |
30 |
31 |
32 | - [pymycobot](#pymycobot)
33 |
34 |
35 |
36 |
37 | ---
38 | More demo can go to [here](../demo).
39 |
--------------------------------------------------------------------------------
/docs/myAGV_en.md:
--------------------------------------------------------------------------------
1 | # myAgv
2 |
3 |
4 | Catalogue:
5 |
6 | - [myAgv](#myagv)
7 | - [set\_led(mode, R, G, B)](#set_ledmode-r-g-b)
8 | - [get\_firmware\_version](#get_firmware_version)
9 | - [get\_motors\_current](#get_motors_current)
10 | - [get\_battery\_info](#get_battery_info)
11 | - [go\_ahead(go\_speed)](#go_aheadgo_speed)
12 | - [retreat(back\_speed)](#retreatback_speed)
13 | - [pan\_left(pan\_left\_speed)](#pan_leftpan_left_speed)
14 | - [pan\_right(pan\_right\_speed)](#pan_rightpan_right_speed)
15 | - [clockwise\_rotation(rotate\_right\_speed)](#clockwise_rotationrotate_right_speed)
16 | - [counterclockwise\_rotation(rotate\_left\_speed)](#counterclockwise_rotationrotate_left_speed)
17 | - [stop()](#stop)
18 | - [restore()](#restore)
19 |
20 |
21 |
22 | ## set_led(mode, R, G, B)
23 |
24 | Set up LED lights
25 |
26 | - **Parameters**
27 |
28 | - **mode** – 1 - Set LED light color. 2 - Set the LED light to blink.
29 |
30 | - **R** – (int) 0 ~ 255
31 |
32 | - **G** – (int) 0 ~ 255
33 |
34 | - **B** – (int) 0 ~ 255
35 |
36 | ## get_firmware_version
37 |
38 | Get firmware version number
39 |
40 | ## get_motors_current
41 |
42 | Get the total current of the motor
43 |
44 | ## get_battery_info
45 |
46 | Read battery information
47 |
48 | - **Return**
49 | list : [battery_data, battery_1_voltage, battery_2_voltage].
50 | `battery_data`:A string of length 6, represented from left to right: bit5, bit4, bit3, bit2, bit1, bit0.
51 | bit5 : Battery 2 is inserted into the interface 1 means inserted, 0 is not inserted.
52 | bit4 : Battery 1 is inserted into the interface, 1 means inserted, 0 is not inserted.
53 | bit3 : The adapter is plugged into the interface 1 means plugged in, 0 not plugged in.
54 | bit2 : The charging pile is inserted into the interface, 1 means plugged in, 0 is not plugged in.
55 | bit1 : Battery 2 charging light 0 means off, 1 means on.
56 | bit0 : Battery 1 charging light, 0 means off, 1 means on.
57 | `battery_1_voltage` : Battery 1 voltage in volts.
58 | `battery_2_voltage` : Battery 2 voltage in volts.
59 |
60 |
71 |
72 | ## go_ahead(go_speed)
73 |
74 | Control the car to move forward
75 |
76 | - **Parameters**
77 |
78 | - **go_speed** – (int) 1 ~ 127 is forward.The smaller the value, the smaller the speed
79 |
80 | ## retreat(back_speed)
81 |
82 | Control the car back
83 |
84 | - **Parameters**
85 |
86 | - **back_speed** – (int) 1 ~ 127 is backward.The smaller the value, the smaller the speed
87 |
88 | ## pan_left(pan_left_speed)
89 |
90 | Control the car to pan to the left
91 |
92 | - **Parameters**
93 |
94 | - **pan_left_speed** – (int) 1 ~ 127.The smaller the value, the smaller the speed
95 |
96 | ## pan_right(pan_right_speed)
97 |
98 | Control the car to pan to the right
99 |
100 | - **Parameters**
101 |
102 | - **pan_right_speed** – (int) 1 ~ 127.The smaller the value, the smaller the speed
103 |
104 | ## clockwise_rotation(rotate_right_speed)
105 |
106 | Control the car to rotate clockwise
107 |
108 | - **Parameters**
109 |
110 | - **rotate_right_speed** – (int) 1 ~ 127.The smaller the value, the smaller the speed
111 |
112 | ## counterclockwise_rotation(rotate_left_speed)
113 |
114 | Control the car to rotate counterclockwise
115 |
116 | - **Parameters**
117 |
118 | - **rotate_left_speed** – (int) 1 ~ 127.The smaller the value, the smaller the speed
119 |
120 | ## stop()
121 |
122 | stop motion.
123 |
124 | ## restore()
125 |
126 | Motor stall recovery
127 |
--------------------------------------------------------------------------------
/docs/myAGV_zh.md:
--------------------------------------------------------------------------------
1 | # myAgv
2 |
3 |
4 | API目录:
5 |
6 | - [myAgv](#myagv)
7 | - [set\_led(mode, R, G, B)](#set_ledmode-r-g-b)
8 | - [get\_firmware\_version](#get_firmware_version)
9 | - [get\_motors\_current](#get_motors_current)
10 | - [get\_battery\_info](#get_battery_info)
11 | - [go\_ahead(go\_speed)](#go_aheadgo_speed)
12 | - [retreat(back\_speed)](#retreatback_speed)
13 | - [pan\_left(pan\_left\_speed)](#pan_leftpan_left_speed)
14 | - [pan\_right(pan\_right\_speed)](#pan_rightpan_right_speed)
15 | - [clockwise\_rotation(rotate\_right\_speed)](#clockwise_rotationrotate_right_speed)
16 | - [counterclockwise\_rotation(rotate\_left\_speed)](#counterclockwise_rotationrotate_left_speed)
17 | - [stop()](#stop)
18 | - [restore()](#restore)
19 |
20 |
21 |
22 | ## set_led(mode, R, G, B)
23 |
24 | 设置led灯颜色
25 |
26 | - **参数**
27 |
28 | - **mode** – 1 - 常亮. 2 - 闪烁.
29 |
30 | - **R** – (int) 0 ~ 255
31 |
32 | - **G** – (int) 0 ~ 255
33 |
34 | - **B** – (int) 0 ~ 255
35 |
36 | ## get_firmware_version
37 |
38 | 获取固件版本号
39 |
40 | ## get_motors_current
41 |
42 | 获取电机电流信息
43 |
44 | ## get_battery_info
45 |
46 | 获取电池信息
47 |
48 | - **Return**
49 | list : [battery_data, battery_1_voltage, battery_2_voltage].
50 | `battery_data`: 长度为6的字符串, 从左到右依次对应: bit5, bit4, bit3, bit2, bit1, bit0.
51 | bit5 : 电池2插入接口,1表示插入,0未插入.
52 | bit4 : 电池1插入接口,1表示插入,0未插入.
53 | bit3 : 适配器插入接口,1表示插入,0未插入.
54 | bit2 : 充电桩插入接口,1表示插入,0未插入.
55 | bit1 : 电池2充电灯,0表示没亮,1表示亮.
56 | bit0 : 电池1充电灯,0表示没亮,1表示亮.
57 | `battery_1_voltage` : 电池1电压.
58 | `battery_2_voltage` : 电池2电压.
59 |
60 |
71 |
72 | ## go_ahead(go_speed)
73 |
74 | 控制前进
75 |
76 | - **参数**
77 |
78 | - **go_speed** – (int) 1 ~ 127 数值越小,速度越慢
79 |
80 | ## retreat(back_speed)
81 |
82 | 控制后退
83 |
84 | - **参数**
85 |
86 | - **back_speed** – (int) 1 ~ 127 数值越小,速度越慢
87 |
88 | ## pan_left(pan_left_speed)
89 |
90 | 控制左平移
91 |
92 | - **参数**
93 |
94 | - **pan_left_speed** – (int) 1 ~ 127 数值越小,速度越慢
95 |
96 | ## pan_right(pan_right_speed)
97 |
98 | 控制右平移
99 |
100 | - **参数**
101 |
102 | - **pan_right_speed** – (int) 1 ~ 127 数值越小,速度越慢
103 |
104 | ## clockwise_rotation(rotate_right_speed)
105 |
106 | 控制顺时针旋转
107 |
108 | - **参数**
109 |
110 | - **rotate_right_speed** – (int) 1 ~ 127 数值越小,速度越慢
111 |
112 | ## counterclockwise_rotation(rotate_left_speed)
113 |
114 | 控制逆时针旋转
115 |
116 | - **参数**
117 |
118 | - **rotate_left_speed** – (int) 1 ~ 127 数值越小,速度越慢
119 |
120 | ## stop()
121 |
122 | 停止运动
123 |
124 | ## restore()
125 |
126 | 堵转恢复
127 |
--------------------------------------------------------------------------------
/docs/mybuddy_emoticon_en.md:
--------------------------------------------------------------------------------
1 | # MyBuddyEmoticon
2 |
3 | ```python
4 | from pymycobot import MyBuddyEmoticon
5 | import time
6 |
7 | # [video_path, Playback_duration(s)]
8 | video1 = ["/home/er/pymycobot/emo/face_video_3_2.mp4", 10]
9 |
10 | datas = [video1]
11 |
12 | me = MyBuddyEmoticon(datas)
13 | me.start()
14 | ```
15 |
16 | ## MyBuddyEmoticon(file_path: list = [], window_size: tuple = (), loop=False)
17 |
18 | * **Function:** API for playing emoticons
19 |
20 | * **Parameters:**
21 |
22 | - **file_path (list)**: `[[path, time]]`The absolute path of facial expression video and the length of time to play.Time in seconds.
23 | - **window_size (tuple)**: `(Length, width) `Size of the playback window (default is full screen).
24 | - **loop (bool)**: Loop playback or not (default False. only once by default).
25 |
26 | ### file_path()
27 |
28 | * **Function:** Get Playfile List
29 | * **Return**
30 | * video path list
31 |
32 | ### add_file_path(path_time)
33 |
34 | * **Function:** Add Playback File
35 | * **Parameters**
36 | **path_time(list)**: `[path, time]` The video address to be added and the running time
37 |
38 | ### del_file_path(index)
39 |
40 | * **Function:** Delete the element with the specified subscript in the playlist list
41 | * **Parameters**
42 |
43 | **index(int)**:: The subscript of the element in the playlist to be deleted
44 |
45 | ### pause()
46 |
47 | * **Function:** Pause playback
48 |
49 | ### run()
50 |
51 | * **Function:** Continue playing
52 |
53 | ### start()
54 |
55 | * **Function:** start playing video
56 |
57 | ### join()
58 |
59 | * **Function:** Wait for the thread playing the video to finish.
60 |
61 | [--->>> play_demo](../demo/mybuddy_demo/mybuddy_emoticon_demo.py)
--------------------------------------------------------------------------------
/docs/mybuddy_emoticon_zh.md:
--------------------------------------------------------------------------------
1 | # MyBuddyEmoticon
2 |
3 | ```python
4 | from pymycobot import MyBuddyEmoticon
5 | import time
6 |
7 | # [video_path, Playback_duration(s)]
8 | video1 = ["/home/er/pymycobot/emo/face_video_3_2.mp4", 10]
9 |
10 | datas = [video1]
11 |
12 | me = MyBuddyEmoticon(datas)
13 | me.start()
14 | ```
15 |
16 | ## MyBuddyEmoticon(file_path: list = [], window_size: tuple = (), loop=False)
17 |
18 | * **功能**:播放表情的 API
19 |
20 | * **参数**:
21 |
22 | - **file_path (list)**:`[[path, time]]` 表情视频的绝对路径及播放时长,单位为秒。
23 | - **window_size (tuple)**:`(长, 宽)` 播放窗口大小(默认全屏)。
24 | - **loop (bool)**:是否循环播放(默认 False,仅循环播放一次)。
25 |
26 | ### file_path()
27 |
28 | * **功能:** 获取播放文件列表
29 | * **返回**
30 | * 视频路径列表
31 |
32 | ### add_file_path(path_time)
33 |
34 | * **功能:** 添加播放文件
35 | * **参数**
36 | **path_time(list)**: `[path, time]` 待添加的视频地址及播放时长
37 |
38 | ### del_file_path(index)
39 |
40 | * **函数:** 删除播放列表中指定下标的元素
41 | * **参数:**
42 |
43 | **index(int)**:: 待删除元素在播放列表中的下标
44 |
45 | ### pause()
46 |
47 | **功能:** 暂停播放
48 |
49 | ### run()
50 |
51 | **功能:** 继续播放
52 |
53 | ### start()
54 |
55 | * **功能:** 开始播放视频
56 |
57 | ### join()
58 |
59 | * **功能**:等待播放视频的线程完成。
60 |
61 | [--->>> 播放演示](../demo/mybuddy_demo/mybuddy_emoticon_demo.py)
--------------------------------------------------------------------------------
/f3-min2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/f3-min2.jpg
--------------------------------------------------------------------------------
/pymycobot/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from __future__ import absolute_import
4 | import datetime
5 | import sys
6 | from pymycobot.mycobot280 import MyCobot280
7 | from pymycobot.mycobot280rdkx5 import MyCobot280RDKX5, MyCobot280RDKX5Socket
8 | from pymycobot.mypalletizer260 import MyPalletizer260
9 | from pymycobot.mecharm270 import MechArm270
10 | from pymycobot.mycobot280socket import MyCobot280Socket
11 | from pymycobot.mycobot320socket import MyCobot320Socket
12 | from pymycobot.mycobot320 import MyCobot320
13 | from pymycobot.generate import CommandGenerator
14 | from pymycobot.Interface import MyBuddyCommandGenerator
15 | from pymycobot.mycobot import MyCobot
16 | from pymycobot.mybuddy import MyBuddy
17 | from pymycobot.mecharm import MechArm
18 | from pymycobot.mypalletizer import MyPalletizer
19 | from pymycobot.mycobotsocket import MyCobotSocket
20 | from pymycobot.genre import Angle, Coord
21 | from pymycobot import utils
22 | from pymycobot.mybuddysocket import MyBuddySocket
23 | from pymycobot.ultraArm import ultraArm
24 | from pymycobot.mybuddybluetooth import MyBuddyBlueTooth
25 | from pymycobot.mypalletizersocket import MyPalletizerSocket
26 | from pymycobot.myarm import MyArm
27 | from pymycobot.myarmsocket import MyArmSocket
28 | from pymycobot.elephantrobot import ElephantRobot
29 | from pymycobot.mercury import Mercury
30 | from pymycobot.myagv import MyAgv
31 | from pymycobot.myagvpro import MyAGVPro
32 | from pymycobot.myagvpro_socket import MyAGVProSocket
33 | from pymycobot.myagvpro_bluetooth import MyAGVProBluetooth
34 | from pymycobot.myarmsocket import MyArmSocket
35 | from pymycobot.mecharmsocket import MechArmSocket
36 | # from pymycobot.mycobotpro630 import Phoenix
37 | from pymycobot.mercurysocket import MercurySocket
38 | from pymycobot.myarmm import MyArmM
39 | from pymycobot.myarmc import MyArmC
40 | from pymycobot.pro630 import Pro630
41 | from pymycobot.pro630client import Pro630Client
42 | from pymycobot.pro400 import Pro400
43 | from pymycobot.pro400client import Pro400Client
44 | from pymycobot.myarmm_control import MyArmMControl
45 | from pymycobot.mercurychassis_api import ChassisControl
46 | from pymycobot.conveyor_api import ConveyorAPI
47 | from pymycobot.ultraArmP340 import ultraArmP340
48 | from pymycobot.exoskeleton import Exoskeleton
49 | from pymycobot.exoskeletonsocket import ExoskeletonSocket
50 | from pymycobot.mybuddyemoticon import MyBuddyEmoticon
51 |
52 |
53 | __all__ = [
54 | "MyPalletizer260",
55 | "MechArm270",
56 | "MyCobot280",
57 | "MyCobot320",
58 | "MyCobot",
59 | "CommandGenerator",
60 | "Angle",
61 | "Coord",
62 | "utils",
63 | "MyPalletizer",
64 | "MyCobotSocket",
65 | "MyBuddyCommandGenerator",
66 | "MyBuddy",
67 | "MyBuddySocket",
68 | "MyBuddyBlueTooth",
69 | "ultraArm",
70 | "MyPalletizerSocket",
71 | "MechArm",
72 | "MyArm",
73 | "ElephantRobot",
74 | "Mercury",
75 | "MyAgv",
76 | "MyAGVPro",
77 | "MyAGVProSocket",
78 | "MyAGVProBluetooth",
79 | "MechArmSocket",
80 | "MyArmSocket",
81 | "MercurySocket",
82 | "MyArmM",
83 | "MyArmC",
84 | # "Phoenix",
85 | "Pro630",
86 | "Pro630Client",
87 | "Pro400",
88 | "Pro400Client",
89 | "MyCobot280Socket",
90 | "MyCobot320Socket",
91 | "MyArmMControl",
92 | "ChassisControl",
93 | "ConveyorAPI",
94 | "MyCobot280RDKX5",
95 | "MyCobot280RDKX5Socket",
96 | "ultraArmP340",
97 | "Exoskeleton",
98 | "ExoskeletonSocket",
99 | "MyBuddyEmoticon"
100 | ]
101 |
102 | __version__ = "3.9.8"
103 | __author__ = "Elephantrobotics"
104 | __email__ = "weiquan.xu@elephantrobotics.com"
105 | __git_url__ = "https://github.com/elephantrobotics/pymycobot"
106 | __copyright__ = "CopyRight (c) 2020-{0} Shenzhen Elephantrobotics technology".format(
107 | datetime.datetime.now().year
108 | )
109 |
110 | # For raspberry mycobot 280.
111 | PI_PORT = "/dev/ttyAMA0"
112 | PI_BAUD = 1000000
113 |
--------------------------------------------------------------------------------
/pymycobot/bluet.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | import sys
3 |
4 | class BluetoothConnection:
5 | def __init__(self, bd_address=None, port=None):
6 | self.device = []
7 | import bluetooth
8 | self.bluetooth = bluetooth
9 | self.target_name = "mybuddy"
10 | self.nearby_devices = None
11 | self.bd_address = bd_address
12 | self.port = port
13 |
14 | def find_target_device(self):
15 | available_addr = []
16 | self.nearby_devices = self.bluetooth.discover_devices(lookup_names=True, duration=5)
17 | if self.nearby_devices:
18 | for addr, name in self.nearby_devices:
19 | if self.target_name == name:
20 | available_addr.append(addr)
21 | return available_addr
22 | return None
23 |
24 | def connect_target_device(self):
25 | if self.bd_address:
26 | sock = self.bluetooth.BluetoothSocket(self.bluetooth.RFCOMM)
27 | sock.connect((self.bd_address, self.port))
28 | return sock
29 | target_address = self.find_target_device()
30 | if target_address:
31 | if len(target_address) > 1:
32 | device_info = ""
33 | i = 1
34 | sys.stdout.write("please select the device you want to connect:\n".format(4))
35 | for addr, name in target_address:
36 | device_info += "{} >>> {} - {} \n".format(i,addr, name)
37 | sys.stdout.write(device_info)
38 | choose_device = input("please enter 1-{}:".format(len(target_address)))
39 | target_address = target_address[int(choose_device)-1][0]
40 | sock = self.bluetooth.BluetoothSocket(self.bluetooth.RFCOMM)
41 | try:
42 | sock.connect((target_address[0][0], 1))
43 | return sock
44 | except Exception as e:
45 | # print("connection fail\n", e)
46 | sock.close()
47 | return None
48 | return None
49 |
50 | if __name__ == "__main__":
51 | pass
--------------------------------------------------------------------------------
/pymycobot/genre.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import enum
4 |
5 |
6 | class Angle(enum.Enum):
7 | J1 = 1
8 | J2 = 2
9 | J3 = 3
10 | J4 = 4
11 | J5 = 5
12 | J6 = 6
13 |
14 |
15 | class Coord(enum.Enum):
16 | X = 1
17 | Y = 2
18 | Z = 3
19 | Rx = 4
20 | Ry = 5
21 | Rz = 6
22 |
23 |
--------------------------------------------------------------------------------
/pymycobot/log.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import logging
4 | import logging.handlers
5 |
6 |
7 | def setup_logging(debug=False):
8 | # logging.basicConfig()
9 | root_logger = logging.getLogger()
10 |
11 | debug_fomatter = logging.Formatter(
12 | fmt="%(asctime)s.%(msecs)03d %(levelname).4s [%(name)s] %(message)s",
13 | datefmt="%H:%M:%S",
14 | )
15 | logger_handle = logging.StreamHandler()
16 | logger_handle.setFormatter(debug_fomatter)
17 | if debug:
18 | logger_handle.setLevel(logging.DEBUG)
19 | # 100M日志
20 | save = logging.handlers.RotatingFileHandler(
21 | "python_debug.log", maxBytes=100*1024*1024, backupCount=1)
22 | save.setFormatter(debug_fomatter)
23 | root_logger.addHandler(save)
24 | root_logger.setLevel(logging.DEBUG)
25 | else:
26 | logger_handle.setLevel(logging.WARNING)
27 | root_logger.setLevel(logging.WARNING)
28 |
29 | root_logger.addHandler(logger_handle)
30 | # root_logger.setLevel(0)
31 |
--------------------------------------------------------------------------------
/pymycobot/mecharm.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | from pymycobot import MyCobot
3 |
4 | class MechArm(MyCobot):
5 | def __init__(self, port, baudrate="115200", timeout=0.1, debug=False, thread_lock=True):
6 | super(MechArm, self).__init__(port, baudrate, timeout, debug, thread_lock)
--------------------------------------------------------------------------------
/pymycobot/mercury.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import time
4 | import threading
5 | import serial
6 | import serial.serialutil
7 |
8 | from pymycobot.mercury_api import MercuryCommandGenerator
9 |
10 | class Mercury(MercuryCommandGenerator):
11 | def __init__(self, port="/dev/ttyAMA1", baudrate="115200", timeout=0.1, debug=False, save_serial_log=False):
12 | """
13 | Args:
14 | port : port string
15 | baudrate : baud rate string, default '115200'
16 | timeout : default 0.1
17 | debug : whether show debug info
18 | """
19 | super(Mercury, self).__init__(debug)
20 | self.save_serial_log = save_serial_log
21 | self._serial_port = serial.Serial()
22 | self._serial_port.port = port
23 | self._serial_port.baudrate = baudrate
24 | self._serial_port.timeout = timeout
25 | self._serial_port.rts = False
26 | self._serial_port.open()
27 | self.lock = threading.Lock()
28 | self.lock_out = threading.Lock()
29 | self.read_threading = threading.Thread(target=self.read_thread)
30 | self.read_threading.daemon = True
31 | self.read_threading.start()
32 | try:
33 | self._serial_port.write(b"\xfa")
34 | except serial.serialutil.SerialException as e:
35 | self._serial_port.close()
36 | time.sleep(0.5)
37 | self._serial_port = serial.Serial()
38 | self._serial_port.port = port
39 | self._serial_port.baudrate = baudrate
40 | self._serial_port.timeout = timeout
41 | self._serial_port.rts = False
42 | self._serial_port.open()
43 | self.get_limit_switch()
44 |
45 | def open(self):
46 | self._serial_port.open()
47 |
48 | def close(self):
49 | self._serial_port.close()
50 |
--------------------------------------------------------------------------------
/pymycobot/mercury_arms_socket.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | import json
4 | import struct
5 | import socket
6 | import threading
7 | from pymycobot.mercury_api import MercuryCommandGenerator
8 | from pymycobot.error import calibration_parameters
9 |
10 | """
11 | for mercury x1 robot arms (six-axis or seven-axis), using socket to communicate with the robot
12 | """
13 |
14 |
15 | class MercuryArmsSocket(MercuryCommandGenerator):
16 | def __init__(self, arm, ip, netport=9000, debug=False):
17 | """
18 | Arm socket connection
19 | Args:
20 | arm: 'left_arm' or 'right_arm'
21 | ip: ip address
22 | netport: port
23 | debug: debug mode
24 | """
25 | super(MercuryArmsSocket, self).__init__(debug)
26 | self.arm = arm
27 | self.calibration_parameters = calibration_parameters
28 | self.SERVER_IP = ip
29 | self.SERVER_PORT = netport
30 | self.sock = self.connect_socket()
31 | self.lock = threading.Lock()
32 | self.lock_out = threading.Lock()
33 | self.read_threading = threading.Thread(target=self.read_thread, args=("socket", ))
34 | self.read_threading.daemon = True
35 | self.read_threading.start()
36 | self.get_limit_switch()
37 |
38 | def connect_socket(self):
39 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
40 | sock.connect((self.SERVER_IP, self.SERVER_PORT))
41 | return sock
42 |
43 | def open(self):
44 | self.sock = self.connect_socket()
45 |
46 | def close(self):
47 | self.sock.close()
48 | self.sock = None
49 |
50 | def __format(self, command: str) -> bytes:
51 | send_data = {"command": command, "arm": self.arm}
52 | data_byter = json.dumps(send_data).encode('utf-8')
53 | date_length = struct.pack('!I', len(data_byter))
54 | return b''.join([date_length, data_byter])
55 |
56 | def _write(self, command, method=None):
57 | log_command = " ".join(map(lambda n: hex(n)[2:], command))
58 | self.log.debug("_write: {}".format(log_command))
59 | self.sock.sendall(self.__format(command))
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/pymycobot/mercurysocket.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import time
4 | import socket
5 | import threading
6 |
7 | from pymycobot.mercury_api import MercuryCommandGenerator
8 |
9 |
10 | class MercurySocket(MercuryCommandGenerator):
11 | def __init__(self, ip, netport=9000, debug=False):
12 | """
13 | Args:
14 | ip: Server ip
15 | netport: Server port(default 9000)
16 | """
17 | super(MercurySocket, self).__init__(debug)
18 | self.SERVER_IP = ip
19 | self.SERVER_PORT = netport
20 | self.sock = self.connect_socket()
21 | self.lock = threading.Lock()
22 | self.lock_out = threading.Lock()
23 | self.read_threading = threading.Thread(
24 | target=self.read_thread, args=("socket", ))
25 | self.read_threading.daemon = True
26 | self.read_threading.start()
27 | self.get_limit_switch()
28 |
29 | def connect_socket(self):
30 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31 | sock.connect((self.SERVER_IP, self.SERVER_PORT))
32 | return sock
33 |
34 | def open(self):
35 | self.sock = self.connect_socket()
36 |
37 | def close(self):
38 | self.sock.close()
39 |
--------------------------------------------------------------------------------
/pymycobot/myagvapi.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | import serial
4 | import struct
5 | import logging
6 | import logging.handlers
7 |
8 |
9 | def setup_logging(name: str = __name__, debug: bool = False) -> logging.Logger:
10 | debug_formatter = logging.Formatter(
11 | fmt="%(asctime)s.%(msecs)06d %(levelname).4s [%(name)s] %(message)s",
12 | datefmt="%H:%M:%S",
13 | )
14 | logger = logging.getLogger(name)
15 | stream_handler = logging.StreamHandler()
16 | stream_handler.setFormatter(debug_formatter)
17 | if debug is True:
18 | logger.addHandler(stream_handler)
19 | logger.setLevel(logging.INFO) # 100M日志
20 | file_handler = logging.handlers.RotatingFileHandler(
21 | filename="python_debug.log", maxBytes=100 * 1024 * 1024, backupCount=1
22 | )
23 | file_handler.setFormatter(debug_formatter)
24 | logger.addHandler(file_handler)
25 |
26 | else:
27 | logger.setLevel(logging.DEBUG)
28 |
29 | return logger
30 |
31 |
32 | def setup_serial_connect(port, baudrate, timeout=None):
33 | serial_api = serial.Serial()
34 | serial_api.port = port
35 | serial_api.baudrate = baudrate
36 | serial_api.timeout = timeout
37 | serial_api.rts = False
38 | serial_api.open()
39 | return serial_api
40 |
41 |
42 | class CommunicationProtocol(object):
43 | def write(self, command):
44 | raise NotImplementedError
45 |
46 | def read(self, size=1):
47 | raise NotImplementedError
48 |
49 | def close(self):
50 | raise NotImplementedError
51 |
52 | def open(self):
53 | raise NotImplementedError
54 |
55 | def is_open(self):
56 | raise NotImplementedError
57 |
58 | def clear(self):
59 | raise NotImplementedError
60 |
61 |
62 | class Utils:
63 | @classmethod
64 | def process_data_command(cls, args):
65 | if not args:
66 | return []
67 |
68 | processed_args = []
69 | for index in range(len(args)):
70 | if isinstance(args[index], list):
71 | data = cls.encode_int16(args[index])
72 | processed_args.extend(data)
73 | else:
74 | processed_args.append(args[index])
75 |
76 | return cls.flatten(processed_args)
77 |
78 | @classmethod
79 | def flatten(cls, datas):
80 | flat_list = []
81 | for item in datas:
82 | if not isinstance(item, list):
83 | flat_list.append(item)
84 | else:
85 | flat_list.extend(cls.flatten(item))
86 | return flat_list
87 |
88 | @classmethod
89 | def float(cls, number, decimal=2):
90 | return round(number / 10 ** decimal, 2)
91 |
92 | @classmethod
93 | def encode_int16(cls, data):
94 | if isinstance(data, int):
95 | return [
96 | ord(i) if isinstance(i, str) else i
97 | for i in list(struct.pack(">h", data))
98 | ]
99 | else:
100 | res = []
101 | for v in data:
102 | t = cls.encode_int16(v)
103 | res.extend(t)
104 | return res
105 |
106 | @classmethod
107 | def decode_int16(cls, data):
108 | return struct.unpack(">h", data)[0]
109 |
110 | @classmethod
111 | def crc16_check(cls, command):
112 | crc = 0xffff
113 | for index in range(len(command)):
114 | crc ^= command[index]
115 | for _ in range(8):
116 | if crc & 1 == 1:
117 | crc >>= 1
118 | crc ^= 0xA001
119 | else:
120 | crc >>= 1
121 | if crc > 0x7FFF:
122 | crc_res = list(struct.pack(">H", crc))
123 | else:
124 | crc_res = cls.encode_int16(crc)
125 |
126 | for i in range(2):
127 | if isinstance(crc_res[i], str):
128 | crc_res[i] = ord(crc_res[i])
129 | return crc_res
130 |
131 | @classmethod
132 | def crc16_check_bytes(cls, command):
133 | data = cls.crc16_check(command)
134 | return bytes(bytearray(data))
135 |
136 | @classmethod
137 | def get_bits(cls, data):
138 | reverse_bins = reversed(bin(data)[2:])
139 | rank = [i for i, e in enumerate(reverse_bins) if e != '0']
140 | return rank
141 |
--------------------------------------------------------------------------------
/pymycobot/myagvpro_socket.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | import socket
4 | from pymycobot.myagvpro import MyAGVProCommandApi
5 |
6 |
7 | def setup_socket_connect(host, port, timeout=0.1):
8 | socket_api = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9 | socket_api.settimeout(timeout)
10 | socket_api.connect((host, port))
11 | return socket_api
12 |
13 |
14 | class MyAGVProSocket(MyAGVProCommandApi):
15 | def __init__(self, host, port, debug=False, save_serial_log=False):
16 | super().__init__(debug=debug, save_serial_log=save_serial_log)
17 | self._socket = setup_socket_connect(host=host, port=port)
18 | self._serial_filename = 'agvpro_socket_serial.log'
19 | self._communication_mode = 1
20 |
21 | def __exit__(self, exc_type, exc_val, exc_tb):
22 | self.close()
23 |
24 | def __enter__(self):
25 | return self
26 |
27 | def write(self, command):
28 | return self._socket.send(command)
29 |
30 | def read(self, size=1):
31 | try:
32 | return self._socket.recv(size)
33 | except socket.timeout:
34 | return b''
35 |
36 | def close(self):
37 | self._socket.close()
38 |
39 | def clear(self):
40 | pass
41 |
--------------------------------------------------------------------------------
/pymycobot/myarmc.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from __future__ import division
4 | from pymycobot.common import ProtocolCode
5 | from pymycobot.myarm_api import MyArmAPI
6 |
7 |
8 | class MyArmC(MyArmAPI):
9 |
10 | def __init__(self, port, baudrate=1000000, timeout=0.1, debug=False):
11 | super(MyArmC, self).__init__(port, baudrate, timeout, debug)
12 |
13 | def is_tool_btn_clicked(self, mode=1):
14 | """get the end button status
15 | Args:
16 | 1: atom
17 | 2: gripper red button
18 | 3: gripper blue button
19 | 254: get all button status
20 | Returns:
21 | list[int]: 0/1, 1: press, 0: no press
22 | """
23 | if not isinstance(mode, int):
24 | raise TypeError('mode must be int')
25 |
26 | if mode not in [1, 2, 3, 254]:
27 | raise ValueError('mode must be 1, 2, 3 or 254')
28 |
29 | return self._mesg(ProtocolCode.GET_ATOM_PRESS_STATUS, mode, has_reply=True)
30 |
31 |
--------------------------------------------------------------------------------
/pymycobot/mybuddyemoticon.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from __future__ import division
4 | import time
5 | import threading
6 |
7 |
8 | class MyBuddyEmoticon:
9 | def __init__(self, file_path, window_size=None, loop=False):
10 | """API for playing emoticons
11 |
12 | Args:
13 | file_path(list): `[[path, time]]`The absolute path of facial expression video and the length of time to play.Time in seconds.
14 | window_size(tuple): `(Length, width) `Size of the playback window (default is full screen).
15 | loop: Loop playback or not (only once by default).
16 |
17 | """
18 | try:
19 | import cv2 as cv
20 | except ImportError:
21 | raise ImportError("Please install opencv-python")
22 | self.__file_path = file_path
23 | self.__window_size = window_size
24 | self.quit = False
25 | self.stop_play = False
26 | self.start_time = 0
27 | self.loop = loop
28 |
29 | @property
30 | def file_path(self):
31 | """Get Playfile List
32 |
33 | Return:
34 | list
35 | """
36 | return self.__file_path
37 |
38 | def add_file_path(self, path_time: list):
39 | """Add Playback File
40 |
41 | Args:
42 | path_time: `[path, time]` The video address to be added and the running time
43 | """
44 | self.__file_path.append(path_time)
45 |
46 | def del_file_path(self, index: int):
47 | """Delete the element with the specified subscript in the playlist list
48 |
49 | Args:
50 | index: The subscript of the element in the playlist to be deleted
51 | """
52 | if index >= len(self.__file_path):
53 | raise IndexError("list index out of range")
54 | self.__file_path.pop(index)
55 |
56 | @property
57 | def window_size(self):
58 | return self.__window_size
59 |
60 | @window_size.setter
61 | def window_size(self, data: tuple):
62 | """Set playback window size"""
63 | self.__window_size = data
64 |
65 | def mouse_callback(self, event, x, y, flags, param):
66 | """Mouse click callback function"""
67 | if event == cv.EVENT_LBUTTONDOWN:
68 | self.quit = True
69 |
70 | def pause(self):
71 | """Pause playback"""
72 | self.stop_play = True
73 |
74 | def run(self):
75 | """Continue playing"""
76 | self.stop_play = False
77 |
78 | def play(self):
79 | index = 0
80 | cap = cv.VideoCapture(self.__file_path[index][0])
81 | out_win = "frame"
82 | cv.namedWindow(out_win, cv.WINDOW_NORMAL)
83 | if not self.window_size:
84 | cv.setWindowProperty(out_win, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
85 | else:
86 | cv.resizeWindow(out_win, self.window_size[0], self.window_size[1])
87 | t = time.time()
88 | cv.setMouseCallback(out_win, self.mouse_callback)
89 | _exit = False
90 | while True:
91 | while time.time() - t < self.__file_path[index][1]:
92 | if self.quit:
93 | break
94 | while self.stop_play and self.quit == False:
95 | if self.start_time == 0:
96 | self.start_time = time.time() - t
97 | if self.start_time>0:
98 | t = time.time() - self.start_time
99 | self.start_time = 0
100 | ret, frame = cap.read()
101 | if frame is not None:
102 | cv.imshow(out_win, frame)
103 | if time.time() - t >= self.__file_path[index][1]:
104 | index += 1
105 | if index >= len(self.__file_path):
106 | if self.loop:
107 | index = 0
108 | else:
109 | _exit = True
110 | break
111 | t = time.time()
112 | if cv.waitKey(1) & 0xFF == ord('q') or ret == False:
113 | cap = cv.VideoCapture(self.__file_path[index][0])
114 | if _exit or self.quit:
115 | break
116 | if time.time() - t >= self.__file_path[index][1]:
117 | index += 1
118 | if index >= len(self.__file_path):
119 | if self.loop:
120 | index = 0
121 | else:
122 | break
123 | t = time.time()
124 | cap = cv.VideoCapture(self.__file_path[index][0])
125 | cap.release()
126 | cv.destroyAllWindows()
127 |
128 | def start(self):
129 | """Start playing"""
130 | self.t = threading.Thread(target=self.play, daemon=True)
131 | self.t.start()
132 |
133 | def join(self):
134 | """Wait for the thread playing the video to finish"""
135 | self.t.join()
136 |
--------------------------------------------------------------------------------
/pymycobot/pro630client.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import socket
3 | import sys
4 | import time
5 | import traceback
6 |
7 | from pymycobot.pro630 import Pro630Api
8 | from pymycobot.common import ProtocolCode
9 |
10 | SYS_VERSION_INFO = sys.version_info.major
11 |
12 |
13 | def format_hex_log(data):
14 | if SYS_VERSION_INFO == 2:
15 | command_log = ""
16 | for d in data:
17 | command_log += hex(ord(d))[2:] + " "
18 | else:
19 | command_log = ""
20 | for d in data:
21 | command_log += hex(d)[2:] + " "
22 |
23 | return command_log
24 |
25 |
26 | def connect_socket(addr, port):
27 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
28 | sock.connect((addr, port))
29 | return sock
30 |
31 |
32 | class Pro630Client(Pro630Api):
33 | def __init__(self, host, port=9000, timeout=0.1, debug=False):
34 | """
35 | Args:
36 | host: host address
37 | port: port number
38 | timeout: socket timeout
39 | debug: debug mode
40 | """
41 | self.sock = connect_socket(host, port)
42 | self.timeout = timeout
43 | self.host = host
44 | self.port = port
45 | super().__init__(debug=debug, method='socket')
46 |
47 | def close(self):
48 | self.sock.close()
49 |
50 | def read_thread(self, method=None):
51 | self.sock.settimeout(self.timeout)
52 | while True:
53 | try:
54 | data = self.sock.recv(1024)
55 | print(data)
56 | result = self._process_received(data)
57 | command_log = format_hex_log(result)
58 | self.log.debug(f"_read :{command_log}")
59 | if not result:
60 | continue
61 |
62 | with self.lock:
63 | self.read_command.append([result, time.time()])
64 | except socket.timeout:
65 | print("socket timeout")
66 | time.sleep(0.1)
67 | except Exception as e:
68 | print(e)
69 | traceback.print_exc()
70 |
71 | def set_basic_output(self, pin_no, pin_signal):
72 | """Set basic output.IO low-level output high-level, high-level output high resistance state
73 |
74 | Args:
75 | pin_no: pin port number. range 1 ~ 6
76 | pin_signal: 0 / 1
77 | """
78 | return self._mesg(ProtocolCode.SET_BASIC_OUTPUT, pin_no, pin_signal)
79 |
80 | def get_basic_input(self, pin_no):
81 | """Get basic input.
82 |
83 | Args:
84 | pin_no: pin port number. range 1 ~ 6
85 |
86 | Return:
87 | 1 - high
88 | 0 - low
89 | """
90 | return self._mesg(ProtocolCode.GET_BASIC_INPUT, pin_no)
91 |
92 | def send_angles_sync(self, angles, speed):
93 | self.calibration_parameters(class_name = self.__class__.__name__, angles=angles, speed=speed)
94 | angles = [self._angle2int(angle) for angle in angles]
95 | return self._mesg(ProtocolCode.SEND_ANGLES, angles, speed, no_return=True)
96 |
97 | def set_monitor_mode(self, mode):
98 | raise NotImplementedError("Pro630 does not support monitor mode")
99 |
100 | def get_monitor_mode(self):
101 | raise NotImplementedError("Pro630 does not support monitor mode")
--------------------------------------------------------------------------------
/pymycobot/progripper.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/pymycobot/progripper.py
--------------------------------------------------------------------------------
/pymycobot/public.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | import sys
4 | import logging
5 | import time
6 |
7 | from pymycobot.log import setup_logging
8 | from pymycobot.error import calibration_parameters
9 | from pymycobot.common import ProtocolCode, DataProcessor
10 |
11 |
12 | class PublicCommandGenerator(DataProcessor):
13 | # def __init__(self, debug=False):
14 | # """
15 | # Args:
16 | # debug : whether show debug info
17 | # """
18 | # self._version = sys.version_info[:2][0]
19 | # self.debug = debug
20 | # setup_logging(self.debug)
21 | # self.log = logging.getLogger(__name__)
22 | # self.calibration_parameters = calibration_parameters
23 |
24 | # def _mesg(self, genre, *args, **kwargs):
25 | # """
26 | # Args:
27 | # genre: command type (Command)
28 | # *args: other data.
29 | # It is converted to octal by default.
30 | # If the data needs to be encapsulated into hexadecimal,
31 | # the array is used to include them. (Data cannot be nested)
32 | # **kwargs: support `has_reply`
33 | # has_reply: Whether there is a return value to accept.
34 | # """
35 | # command_data = self._process_data_command(genre, args)
36 |
37 | # if genre == 178:
38 | # command_data = self._encode_int16(command_data)
39 |
40 | # elif genre in [76, 77]:
41 | # command_data = [command_data[0]] + self._encode_int16(command_data[1]*10)
42 | # elif genre == 115:
43 | # command_data = [command_data[1],command_data[3]]
44 |
45 | # LEN = len(command_data) + 2
46 | # command = [
47 | # ProtocolCode.HEADER,
48 | # ProtocolCode.HEADER,
49 | # LEN,
50 | # genre,
51 | # command_data,
52 | # ProtocolCode.FOOTER,
53 | # ]
54 |
55 | # real_command = self._flatten(command)
56 | # has_reply = kwargs.get("has_reply", False)
57 | # return real_command, has_reply
58 | pass
59 |
--------------------------------------------------------------------------------
/pymycobot/tool_coords.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 |
4 | def CvtRotationMatrixToEulerAngle(pdtRotationMatrix):
5 | pdtEulerAngle = np.zeros(3)
6 |
7 | pdtEulerAngle[2] = np.arctan2(pdtRotationMatrix[1, 0], pdtRotationMatrix[0, 0])
8 |
9 | fCosRoll = np.cos(pdtEulerAngle[2])
10 | fSinRoll = np.sin(pdtEulerAngle[2])
11 |
12 | pdtEulerAngle[1] = np.arctan2(-pdtRotationMatrix[2, 0], (fCosRoll * pdtRotationMatrix[0, 0]) + (fSinRoll * pdtRotationMatrix[1, 0]))
13 | pdtEulerAngle[0] = np.arctan2((fSinRoll * pdtRotationMatrix[0, 2]) - (fCosRoll * pdtRotationMatrix[1, 2]), (-fSinRoll * pdtRotationMatrix[0, 1]) + (fCosRoll * pdtRotationMatrix[1, 1]))
14 |
15 | return pdtEulerAngle
16 |
17 | def CvtEulerAngleToRotationMatrix(ptrEulerAngle):
18 | ptrSinAngle = np.sin(ptrEulerAngle)
19 | ptrCosAngle = np.cos(ptrEulerAngle)
20 |
21 | ptrRotationMatrix = np.zeros((3, 3))
22 | ptrRotationMatrix[0, 0] = ptrCosAngle[2] * ptrCosAngle[1]
23 | ptrRotationMatrix[0, 1] = ptrCosAngle[2] * ptrSinAngle[1] * ptrSinAngle[0] - ptrSinAngle[2] * ptrCosAngle[0]
24 | ptrRotationMatrix[0, 2] = ptrCosAngle[2] * ptrSinAngle[1] * ptrCosAngle[0] + ptrSinAngle[2] * ptrSinAngle[0]
25 | ptrRotationMatrix[1, 0] = ptrSinAngle[2] * ptrCosAngle[1]
26 | ptrRotationMatrix[1, 1] = ptrSinAngle[2] * ptrSinAngle[1] * ptrSinAngle[0] + ptrCosAngle[2] * ptrCosAngle[0]
27 | ptrRotationMatrix[1, 2] = ptrSinAngle[2] * ptrSinAngle[1] * ptrCosAngle[0] - ptrCosAngle[2] * ptrSinAngle[0]
28 | ptrRotationMatrix[2, 0] = -ptrSinAngle[1]
29 | ptrRotationMatrix[2, 1] = ptrCosAngle[1] * ptrSinAngle[0]
30 | ptrRotationMatrix[2, 2] = ptrCosAngle[1] * ptrCosAngle[0]
31 |
32 | return ptrRotationMatrix
33 |
34 | def transformation_matrix_from_parameters(rotation_matrix, translation_vector):
35 | """
36 | Create a 4x4 homogeneous transformation matrix.
37 |
38 | :param rotation_matrix: 3x3 numpy array representing rotation.
39 | :param translation_vector: 1x3 numpy array representing translation.
40 | :return: 4x4 numpy array representing the transformation matrix.
41 | """
42 | T = np.eye(4)
43 | T[:3, :3] = rotation_matrix
44 | T[:3, 3] = translation_vector
45 | return T
46 |
47 | def get_flange_pose(flange_matrix, tool_pose):
48 | """
49 | Convert the pose from flange coordinate system to tool coordinate system.
50 |
51 | :param flange_to_tool_matrix: 4x4 numpy array, transformation matrix from flange to tool.
52 | :param flange_pose: 4x4 numpy array, pose in flange coordinate system.
53 | :return: 4x4 numpy array, pose in tool coordinate system.
54 | """
55 | return np.dot(flange_matrix, np.linalg.inv(tool_pose))
56 |
57 | def get_tool_pose(flange_matrix, tool_pose):
58 | """
59 | Convert the pose from tool coordinate system to flange coordinate system.
60 |
61 | :param flange_to_tool_matrix: 4x4 numpy array, transformation matrix from flange to tool.
62 | :param tool_pose: 4x4 numpy array, pose in tool coordinate system.
63 | :return: 4x4 numpy array, pose in flange coordinate system.
64 | """
65 | return np.dot(flange_matrix, tool_pose)
66 |
67 |
68 | def flangeToTool(current_coords, tool_matrix):
69 | # Example pose in flange coordinate system
70 | flange_pose = np.eye(4)
71 | flange_pose[:3, :3] = CvtEulerAngleToRotationMatrix(current_coords[3:6] * np.pi/180.0)
72 | flange_pose[:3, 3] = current_coords[:3] # Example translation
73 |
74 | # Switch to tool coordinate system
75 | tool_pose = get_tool_pose(flange_pose, tool_matrix)
76 | tool_coords = np.concatenate((tool_pose[:3,3].T, CvtRotationMatrixToEulerAngle(tool_pose[:3,:3]) * 180/np.pi))
77 |
78 | return tool_coords
79 |
80 | def toolToflange(tool_coords, tool_matrix):
81 |
82 | # Example pose in tool coordinate system
83 | tool_pose = np.eye(4)
84 | tool_pose[:3, :3] = CvtEulerAngleToRotationMatrix(tool_coords[3:6] * np.pi/180.0)
85 | tool_pose[:3, 3] = tool_coords[:3] # Example translation
86 |
87 | # Switch to tool coordinate system
88 | flange_pose = get_flange_pose(tool_pose, tool_matrix)
89 |
90 | flange_coords = np.concatenate((flange_pose[:3,3].T, CvtRotationMatrixToEulerAngle(flange_pose[:3,:3]) * 180/np.pi ))
91 | return flange_coords
--------------------------------------------------------------------------------
/pymycobot/utils.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from __future__ import print_function
4 |
5 | try:
6 | from serial.tools.list_ports import comports
7 | except ImportError:
8 | print("Not found module `pyserial`, please install.")
9 |
10 |
11 | def get_port_list():
12 | # type:() -> list
13 | """Get all the serial port string.
14 |
15 | Return:
16 | serial port list(list)
17 | """
18 | return [p.device for p in comports()]
19 |
20 |
21 | def detect_port_of_basic():
22 | """Detect M5 Basic.
23 | Returns the serial port string of the first detected M5 Basic.
24 | If it is not found, it returns `None`.
25 | """
26 | ports = [p.device for p in comports() if p.pid == 0xEA60]
27 | return ports[0] if len(ports) > 0 else None
28 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pyserial
2 | python-can
3 | pytest
4 | flake8
5 | opencv-python
6 | numpy
7 | crc
8 | bleak~=0.22.3
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # encoding=utf-8
2 | from __future__ import print_function
3 | import sys
4 |
5 | PYTHON_VERSION = sys.version_info[:2]
6 | if (2, 7) != PYTHON_VERSION < (3, 5):
7 | print("This mycobot version requires Python2.7, 3.5 or later.")
8 | sys.exit(1)
9 |
10 | import setuptools
11 | import textwrap
12 | import pymycobot
13 |
14 | try:
15 | long_description = (
16 | open("README.md", encoding="utf-8").read()
17 | + open("docs/README.md", encoding="utf-8").read()
18 | )
19 | except:
20 | long_description = textwrap.dedent(
21 | """\
22 | # This is Python API for myCobot
23 |
24 | This is a python API for serial communication with mycobot and controlling it.
25 |
26 | [](https://www.elephantrobotics.com/en/myCobot-en/)
27 |
28 | ## Installation
29 |
30 | **Notes**:
31 |
32 | > Make sure that `Atom` is flashed into the top Atom, `Transponder` is flashed into the base Basic.
33 | > The firmware `Atom` and `Transponder` download address: [https://github.com/elephantrobotics/myCobot/tree/main/Software](https://github.com/elephantrobotics/myCobot/tree/main/Software)
34 | > You also can use myStudio to flash them, myStudio address: [https://github.com/elephantrobotics/myStudio/releases](https://github.com/elephantrobotics/myStudio/releases)
35 |
36 | ### Pip
37 |
38 | ```bash
39 | pip install pymycobot --upgrade
40 | ```
41 |
42 | ### Source code
43 |
44 | ```bash
45 | git clone https://github.com/elephantrobotics/pymycobot.git
46 | cd /pymycobot
47 | # Install
48 | [sudo] python2 setup.py install
49 | # or
50 | [sudo] python3 setup.py install
51 | ```
52 |
53 | ## Usage:
54 |
55 | ```python
56 | from pymycobot import MyCobot, Angle, Coord
57 | from pymycobot import PI_PORT, PI_BAUD # For raspberry pi version of mycobot.
58 | ```
59 |
60 | The [`demo`](./demo) directory stores some test case files.
61 |
62 | You can find out which interfaces pymycobot provides in `pymycobot/README.md`.
63 |
64 | Please go to [here](./docs/README.md).
65 | """
66 | )
67 |
68 | setuptools.setup(
69 | name="pymycobot",
70 | version=pymycobot.__version__,
71 | author=pymycobot.__author__,
72 | author_email=pymycobot.__email__,
73 | description="Python API for serial communication of MyCobot.",
74 | long_description=long_description,
75 | long_description_content_type="text/markdown",
76 | url=pymycobot.__git_url__,
77 | packages=setuptools.find_packages(),
78 | include_package_data=True, # Include non-Python files, like JSON files
79 | package_data={"pymycobot": ["*.json"]}, # Specify the JSON file(s) to include
80 | classifiers=[
81 | "Programming Language :: Python :: 2.7",
82 | "Programming Language :: Python :: 3.5",
83 | "Programming Language :: Python :: 3.6",
84 | "Programming Language :: Python :: 3.7",
85 | "Programming Language :: Python :: 3.8",
86 | "Programming Language :: Python :: 3.9",
87 | "Programming Language :: Python :: 3.10",
88 | "License :: OSI Approved :: MIT License",
89 | "Operating System :: OS Independent",
90 | ],
91 | install_requires=["pyserial"],
92 | python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, != 3.4.*",
93 | )
94 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elephantrobotics/pymycobot/40350eaf2477b4223ea8c45ddac9e705bf4d3388/tests/conftest.py
--------------------------------------------------------------------------------
/tests/special_angles.py:
--------------------------------------------------------------------------------
1 | import time
2 | import os
3 | from pymycobot.mycobot import MyCobot
4 |
5 |
6 | def test(mc):
7 | special_angles = [
8 | [0, 90, 0, 0, 90, 0],
9 | [0, 0, -90, 0, -90, 0],
10 | [0, 90, 0, -90, -90, 0],
11 | [0, -90, 90, -90, -90, 0],
12 | ]
13 |
14 | for angles in special_angles:
15 | mc.send_angles(angles, 80)
16 | time.sleep(4)
17 | coords = mc.get_coords()
18 | time.sleep(0.1)
19 | print(coords)
20 |
21 |
22 | """
23 | [-278.1, -16.8, 104.2, 79.82, -81.6, -169.53]
24 | [-279.2, -15.2, 117.5, 34.72, -85.83, -124.83]
25 | [171.6, -113.1, 229.8, 114.15, -84.21, -24.27]
26 | [-211.5, -113.8, 188.5, -89.79, 6.14, -177.87]
27 | [190.8, -113.1, 210.7, 104.26, -82.19, -14.39]
28 | """
29 |
30 | if __name__ == "__main__":
31 | time.sleep(1)
32 | with open(os.path.dirname(__file__) + "/port.txt") as f:
33 | port = f.read().strip().replace("\n", "")
34 | print(port)
35 | mc = MyCobot(port, boudrate="1000000")
36 | # test(mc)
37 | # coords = [-279.2, -15.2, 117.5, 34.72, -85.83, -124.83]
38 | # mc.send_coords(coords, 80, 1)
39 | # exit(0)
40 | while True:
41 | print(mc.get_coords())
42 | time.sleep(1)
43 |
--------------------------------------------------------------------------------
/tests/test_generator.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import pytest
4 | from pprint import pprint
5 |
6 | # Add relevant ranger module to PATH... there surely is a better way to do this...
7 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
8 |
9 | from pymycobot import MyCobotCommandGenerator
10 |
11 |
12 | @pytest.fixture(scope="module")
13 | def mcg():
14 | print("")
15 | DEBUG = False
16 | mg = MyCobotCommandGenerator(debug=DEBUG)
17 | print("")
18 | return mg
19 |
20 | def test_flatten1(mcg):
21 | assert mcg._flatten([1,2,3,4,5,6]) == [1,2,3,4,5,6]
22 |
23 | def test_flatten2(mcg):
24 | assert mcg._flatten([1,2,3,4,[],5]) == [1,2,3,4,5]
25 |
26 | def test_flatten3(mcg):
27 | assert mcg._flatten([1,2,3,4,[5,6],7]) == [1,2,3,4,5,6,7]
28 |
29 | def test_encode_int16(mcg):
30 | assert mcg._encode_int16([0, 1]) == sum([mcg._encode_int16(0), mcg._encode_int16(1)], [])
31 |
32 | def test_process_data_command1(mcg):
33 | assert mcg._process_data_command(()) == []
34 |
35 | def test_process_data_command2(mcg):
36 | assert mcg._process_data_command((1, 2, 3)) == [1, 2, 3]
37 |
38 | def test_process_data_command3(mcg):
39 | assert mcg._process_data_command((1, 2, [1, 2])) == mcg._flatten([1, 2, mcg._encode_int16([1, 2])])
40 |
41 | def test_version(mcg):
42 | assert mcg.version() == ([0xFE, 0xFE, 2, 0x00, 0xFA], True)
43 |
44 | def test_power_on(mcg):
45 | assert mcg.power_on() == ([0xFE, 0xFE, 2, 0x10, 0xFA], False)
46 |
47 | def test_power_off(mcg):
48 | assert mcg.power_off() == ([0xFE, 0xFE, 2, 0x11, 0xFA], False)
49 |
50 | def test_release_all_servos(mcg):
51 | assert mcg.release_all_servos() == ([0xFE, 0xFE, 2, 0x13, 0xFA], False)
52 |
53 | def test_is_controller_connected(mcg):
54 | assert mcg.is_controller_connected() == ([0xFE, 0xFE, 2, 0x14, 0xFA], True)
55 |
56 | def test_get_angles(mcg):
57 | assert mcg.get_angles() == ([0xFE, 0xFE, 2, 0x20, 0xFA], True)
58 |
59 | def test_get_coords(mcg):
60 | assert mcg.get_coords() == ([0xFE, 0xFE, 2, 0x23, 0xFA], True)
61 |
62 | def test_is_in_position(mcg):
63 | assert mcg.is_in_position([0, 0, 0, 0, 0, 0], 0) == (mcg._flatten([0xFE, 0xFE, 15, 0x2A, mcg._flatten([mcg._encode_int16([0, 0, 0, 0, 0, 0]), 0]), 0xFA]), True)
64 |
65 | def test_pause(mcg):
66 | assert mcg.pause() == ([0xFE, 0xFE, 2, 0x26, 0xFA], False)
67 |
68 | def test_resume(mcg):
69 | assert mcg.resume() == ([0xFE, 0xFE, 2, 0x28, 0xFA], False)
70 |
71 | def test_stop(mcg):
72 | assert mcg.stop() == ([0xFE, 0xFE, 2, 0x29, 0xFA], False)
73 |
74 | def test_set_pin_mode(mcg):
75 | assert mcg.set_pin_mode(1, 0) == ([0xFE, 0xFE, 4, 0x60, 1, 0, 0xFA], False)
76 |
77 | def test_set_digital_output(mcg):
78 | assert mcg.set_digital_output(0, 1) == ([0xFE, 0xFE, 4, 0x61, 0, 1, 0xFA], False)
79 |
--------------------------------------------------------------------------------
/tests/test_socket.py:
--------------------------------------------------------------------------------
1 | from pymycobot import MyCobotSocket
2 |
3 | mc = MyCobotSocket("192.168.10.10", "9000")
4 |
5 | print(mc.get_angles())
6 | # mc.power_on()
7 | # mc.power_off()
8 | # mc.sync_send_angles([-0.08, 71.27, -116.27, 19.77, 7.55, -1.23], 20)
9 | # mc.sync_send_angles([-1.05, -7.29, 1.4, -49.39, 7.55, -1.23], 20)
10 | # print(mc.is_controller_connected())
11 | # print(mc.release_all_servos())
12 | # print(mc.get_angles())
13 | # mc.send_angle(1, 100, 20)
14 | # print(mc.get_coords())
15 | # mc.send_coords([180.4, -55.1, 210.1, -172.81, 7.32, -86.97], 20, 1)
16 | # print(mc.jog_angle(1, 1, 20))
17 |
--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 | # Add relevant ranger module to PATH... there surely is a better way to do this...
5 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6 |
7 | from pymycobot import utils
8 |
9 | port = utils.get_port_list()
10 | print(port)
11 |
12 | detect_result = utils.detect_port_of_basic()
13 | print(detect_result)
14 |
--------------------------------------------------------------------------------