vscode配置ardino-cli
-
下载arduino-cli,github
-
选好目录后解压并修改名称
名字在批处理文件中需要用到
-
创建批处理文件,命名为arduino-cli.bat
@echo off rem 获取用户输入的所有参数 set all_args=%* rem 设置配置文件的路径 set config_file=D:\\MyProgram\\Arduino\\data\\arduino-cli.yaml rem echo %all_args% rem 调用重命名后的软件 b,并传递配置文件和用户输入的所有参数 my-arduino-cli --config-file %config_file% %all_args%
注意: my-arduino-cli为原来的arduino-cli文件重命名后的名字
-
将这两个文件所在的目录放到环境变量中,方便命令使用
其实只放批处理文件 的也行,这样的话就要指定my-arduino-cli的绝对路径
推荐直接将两个文件放一起,方便
原理及目的: arduino-cli在运行时可以指定配置文件,重命名的原因是防止终端获取到的程序是原来的,而不是我们需要的批处理文件,批处理文件命名为arduino-clli只是习惯与方便,避免以后从浏览器找到命令后还得打开路径查看程序名称
批处理文件获取用火输入的参数,并添加参数指定配置文件后,将新命令发给原来的arduino-cli程序
board_manager: additional_urls: - https://www.github.com/esp8266/Arduino/releases/download/3.1.2/package_esp8266com_index.json - https://www.github.com/espressif/arduino-esp32/releases/download/2.0.7/package_esp32_index.json directories: builtin: # 不知道干啥的,没生成这个目录 libraries: d:\\MyProgram\\Arduino\\data\\libraries # 数据目录,里面自动存放一些配置文件和下载的核心core文件, data: d:\\MyProgram\\Arduino\\data\\Arduino15 # 用户下载的第三方库路径 user: d:\\MyProgram\\Arduino\\libraries # 不知道作用 locale: zh-cn # 这个也不知道作用 library: enable_unsafe_install: false # 网络代理,懂得都懂,不懂就删除 network: proxy: http://127.0.0.1:7890/
-
-
安装vscode
-
配置vscode
-
插件安装moaayk的Arduino就行了,VScode的错误提示和代码不全差点意思,就用这一个减少一点红色报错就行,忍受得了的可以不装。c++插件不确定要不要装,我以前装了
-
创建一个目录,用于存放arduino项目
-
创建vscode配置文件
-
c_cpp_properties.json,存放一些头文件地址,减少一些红色报错
{ "configurations": [ { "name": "Arduino", "includePath": [ "${workspaceFolder}/**", "D:\\MyProgram\\Arduino\\libraries\\libraries\\**\\**", "D:\\MyProgram\\Arduino\\data\\Arduino15\\**\\**" // "D:\\MyProgram\\Arduino\\data\\Arduino15\\esp8266\\hardware\\esp8266\\**\\**", // "D:\\MyProgram\\Arduino\\data\\Arduino15\\esp32\\hardware\\esp32\\**\\**" ], "defines": [ "F_CPU=16000000L", "ARDUINO=10607", "ARDUINO_AVR_UNO", "ARDUINO_ARCH_AVR" ], "compilerPath": "D:\\MyProgram\\Arduino\\data\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7\\bin\\avr-c++.exe", "cStandard": "c11", "cppStandard": "c++11", "intelliSenseMode": "gcc-x64" } ], "version": 4 }
-
tasks.json,创建任务,用于编译和上传
{ "version": "2.0.0", "tasks": [ { // 设置端口 "label": "set Arduino", "type": "shell", "command": "python .vscode/com_get_arduino.py", "problemMatcher": [], "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "detail": "Reads the board from arduino.json" }, { // 编译 "label": "build", "type": "shell", "command": "arduino-cli", "dependsOn": ["set Arduino"], "args": [ "compile", "-v", "--fqbn", "${config:arduino.board}", "${fileDirname}", "--build-path", "${fileDirname}/.build" ], "problemMatcher": [] }, { //上传 "label": "upload", "type": "shell", "command": "arduino-cli", "args": [ "upload", "--port", "${config:arduino.port}", "--fqbn", "${config:arduino.board}", "--input-dir", "${fileDirname}/.build" ], "problemMatcher": [] }, { // 编译并上传 "label": "build and upload", "type": "shell", "dependsOn": "build", "command": "arduino-cli", "args": [ "upload", "--port", "${config:arduino.port}", "--fqbn", "${config:arduino.board}", "--input-dir", "${fileDirname}/.build" ], "problemMatcher": [] } ] }
-
com_get_arduino.py,获取端口,驱动,板子类型等,文件名在tasks.json中用到,注意修改,控制台有输出,注意查看。
代码 不一定完善。代码需要指定批处理文件的绝对路径,不知道为啥,记得修改130行
import json import subprocess from pathlib import Path from tabulate import tabulate def get_board(_core): """ Board Name FQBN 4D Systems gen4 IoD Range esp8266:esp8266:gen4iod AI Thinker ESP32-CAM esp32:esp32:esp32cam ALKS ESP32 esp32:esp32:alksesp32 ATMegaZero ESP32-S2 esp32:esp32:atmegazero_esp32s2 Adafruit Circuit Playground arduino:avr:circuitplay32u4cat Adafruit ESP32 Feather esp32:esp32:featheresp32 """ result = subprocess.run([cli_path, 'board listall'], text=True, capture_output=True) list_str = result.stdout if list_str == '': raise Exception("找不到board,请安装核心") # return [] lines = list_str.split('\n') index = lines[0].find("F") line_list = [] idx = 0 for line in lines: _board, fqbn = line[:index].strip(), line[index:].strip() if len(fqbn.split(":")) < 2: continue name = fqbn.split(":")[0] + ":" + fqbn.split(":")[1] if name != _core: continue if _board and fqbn: line_list.append(['id' if idx == 0 else idx, _board, fqbn]) idx += 1 return line_list def get_core(): """ ID Installed Latest Name arduino:avr 1.8.6 1.8.6 Arduino AVR Boards esp32:esp32 2.0.4 3.1.1 esp32 esp8266:esp8266 3.1.2 3.1.2 esp8266 """ result = subprocess.run([cli_path, 'core list'], text=True, capture_output=True) core_list_str = result.stdout if core_list_str == '': raise Exception("找不到核心,请安装核心") # return [] lines = core_list_str.split('\n') i_index = lines[0].find("I", 1) l_index = lines[0].find("L", 1) n_index = lines[0].find("N", 1) core_list = [] for index, line in enumerate(lines, 0): _id, installed, latest, name = (line[:i_index].strip(), line[i_index:l_index].strip(), line[l_index:n_index].strip(), line[n_index:].strip()) if _id and installed and latest and name: core_list.append(["index" if index == 0 else index, _id, installed, latest, name]) return core_list def get_port(): """ Port Protocol Type Board Name FQBN Core 192.168.1.44 network Network Port LOLIN(WEMOS) D1 R2 & mini esp8266:esp8266:d1_mini esp8266:esp8266 Network Port LOLIN(WEMOS) D1 R2 & mini esp8266:esp8266:d1_mini esp8266:esp8266 COM5 serial Serial Port (USB) Unknown """ result = subprocess.run([cli_path, 'board', 'list'], text=True, capture_output=True) port_str = result.stdout # 打印输出结果 if port_str.strip() == "No boards found.": raise Exception("找不到端口,请检查连接") if not port_str.startswith("Port"): return get_port() p_index = port_str.find("P", 1) f_index = port_str.find("F") c_index = port_str.find("C") results = [] index = 0 start = False for _line in port_str.split('\n'): line = _line.strip() _port = line[:p_index].strip() _fqbn = line[f_index:c_index].strip() if _port: results.append(["index" if index == 0 else index, _port, _fqbn]) index += 1 return results def set_setting(_port, _board): # 定义文件路径 (自动处理正反斜杠) vscode_dir = Path(__file__).parent settings_json = vscode_dir / "settings.json" try: # 读取或创建 settings.json try: with settings_json.open('r', encoding='utf-8') as f: settings = json.load(f) except FileNotFoundError: settings = {} # 更新配置并保留其他设置 settings.setdefault('arduino', {}).update({ 'port': _port, 'board': _board }) # 写回文件 (保留原有格式) with settings_json.open('w', encoding='utf-8') as f: json.dump(settings, f, indent=2, ensure_ascii=False) f.write('\n') # 添加结尾换行符 print(f"配置同步成功 -> {settings_json}") except json.JSONDecodeError as e: print(f"JSON 解析错误: {e.doc} (第 {e.lineno} 行)") except Exception as e: print(f"操作失败: {str(e)}") if __name__ == '__main__': cli_path = "D:\\MyProgram\\Arduino\\arduino-cli\\arduino-cli.bat" port_list = get_port() if len(port_list) < 2: print("没有找到任何端口") elif len(port_list) == 2 and port_list[1][2] is not None and port_list[1][2] != "": set_setting(port_list[1][1], port_list[1][2]) else: i = 1 if len(port_list) > 2: print(tabulate(port_list, headers="firstrow", tablefmt="grid")) i = int(input("请选择要使用的端口:")) port, board = port_list[i][1], port_list[i][2] if board == "" or board is None: core = get_core() print(tabulate(core, headers="firstrow", tablefmt="grid")) core_i = int(input(f"端口{port} 型号无法获取,请选择核心:")) board_list = get_board(core[core_i][1]) print(tabulate(board_list, headers="firstrow", tablefmt="grid")) board_i = int(input(f"端口{port} 请选择要使用型号:")) board = board_list[board_i][2] set_setting(port, board)
-
launch.json,方便点击运行时直接编译或上传,但是没有 用到参数program,但是又要配置,所以在运行结束时报错,不影响使用,直接取消即可
{ // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "编译并上传", "type": "cppdbg", "request": "launch", "program": "", "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "preLaunchTask": "build and upload" }, { "name": "编译", "type": "cppdbg", "request": "launch", "program": "", "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "preLaunchTask": "build" }, { "name": "上传", "type": "cppdbg", "request": "launch", "program": "", "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "preLaunchTask": "upload" } ] }
-
settings.json,vscode主题和插件的配置,如果没有配置项,可以等待python代码创建
{ "files.associations": { "array": "cpp", "deque": "cpp", "list": "cpp", "string": "cpp", "unordered_map": "cpp", "unordered_set": "cpp", "vector": "cpp", "string_view": "cpp", "initializer_list": "cpp", "regex": "cpp" }, "arduino": { "board": "esp8266:esp8266:d1_mini", "port": "192.168.1.44" } }
因为tasks.json无法读取到其他地方的配置,但是可以读取到settings.json,所以python将端口和板子型号存放到该文件中,方便任务读取
可以编译上传了
注意:如果时网络端口,可能需要输入密码才能上传(不确定,我需要输入),随便输入或者直接回车
运行方式,在项目文件夹中打开任意一个文件,不是主文件 也可以
-
依次点击终端—>运行任务,就可以看到tasks.json中的几个任务,这里看到的就是tasks.json中的label
-
依次点击运行—>启用调试,可以看到launch.json中的事件,这里看到的就是launch.json中的name
-
依次点击
没有配置launch.json,只能通过第一种运行任务,配置了则三种都可以
-
-
-
长处与短处
- 代码提示
- 对于JetBrains和vsstudio来说,vscode非常逊色,但是我觉得比arduino ide好很多
- 定制化
- 关于定制化,vscode非常厉害且方便,轻量级,启动迅速,风格好看(比arduino ide好看很多)
- 库安装
- 离线核心库安装会到c盘中,不会到指定的文件夹,需要复制回来,这一点比较麻烦,如果用网络下载则没事
- 工程化
- 无所谓,就算你用arduiino ide也没有工程化啊
- 代码提示
-