I2C SPI 画图 工具 程序合集

张开发
2026/4/20 7:06:22 15 分钟阅读

分享文章

I2C SPI 画图 工具 程序合集
INA219 电量监控!doctype htmlhtml langzh-CNheadmeta charsetutf-8/meta nameviewportcontentwidthdevice-width, initial-scale1/titleBattery Pie · HTML Only/titlescript srchttps://cdn.jsdelivr.net/npm/chart.js/scriptstyle:root{--bg:#0b1020;--panel:#121831;--text:#e7ecf3;--muted:#9fb0c6}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial}header{padding:14px 18px;background:#0f1631;border-bottom:1px solid #263153}h1{margin:0;font-size:18px}.wrap{padding:16px;display:grid;gap:16px;max-width:900px;margin:0auto}.card{background:var(--panel);border:1px solid#263153;border-radius:14px;padding:14px}.grid{display:grid;gap:16px;grid-template-columns:1fr}.row{display:flex;flex-wrap:wrap;gap:10px;align-items:center}label{color:var(--muted);font-size:13px}input,button{background:#0c1227;border:1px solid #2a355d;color:var(--text);border-radius:10px;padding:8px 10px;outline:none}button{cursor:pointer}.chartBox{position:relative;max-width:420px;margin:auto}#centerLabel{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:42px;font-weight:700;pointer-events:none}.muted{color:var(--muted)}/style/headbodyheaderh1Battery Pie(HTML Only)/h1/headerdivclasswrapsectionclasscard griddivclasschartBoxcanvasidchartwidth420height420/canvasdividcenterLabel--%/div/divdivclassrowlabelSoC(%)/labelinputidsocValtypenumberstep0.1min0max100value50/buttonidbtnSetUpdate/buttoninputidsocRangetyperangemin0max100step0.1value50styleflex:1 1 220px//divdivclassrowlabelAuto-poll URL/labelinputidurlstyleflex:1 1 320pxplaceholdere.g. http://pi-ip:5000/api/data or any JSON with soc/labelInterval(s)/labelinputidintervaltypenumbermin0.5step0.5value1stylewidth:90px/buttonidbtnStartStart/buttonbuttonidbtnStopStop/button/divdivclassmutedNotes:Thisisa pure HTML page.You can manuallysetthe percentage,oroptionally poll a JSON endpoint.If the endpoint returnscode{soc:number}/code,its used directly.If it returns arrays like your Flask app(code{times:[],soc:[]}/code),the last soc valueisused./div/section/divscriptconst ctxdocument.getElementById(chart).getContext(2d);const centerdocument.getElementById(centerLabel);const socInputdocument.getElementById(socVal);constrangedocument.getElementById(socRange);let chart;function socColor(p){//green-yellow-red based on percentageif(p60)return#19c37d;if(p30)return#ffb020;return#ff5c5c;}function buildChart(){chartnew Chart(ctx,{type:doughnut,data:{labels:[SoC,Empty],datasets:[{data:[50,50],borderWidth:0,backgroundColor:[socColor(50),#263153],hoverOffset:2,cutout:70%}]},options:{responsive:true,plugins:{legend:{display:false}}}});setSOC(50);}function setSOC(p){pMath.max(0,Math.min(100,Number(p)||0));if(!chart)return;chart.data.datasets[0].data[p,100-p];chart.data.datasets[0].backgroundColor[0]socColor(p);chart.update(none);center.textContentp.toFixed(1)%;socInput.valuep.toFixed(1);range.valuep.toFixed(1);}//Manual controls document.getElementById(btnSet).onclick()setSOC(socInput.value);range.oninput()setSOC(range.value);//Polling logic let timernull;asyncfunction pollOnce(url){try{const rawaitfetch(url,{cache:no-store});const jawaitr.json();let pnull;if(typeof j.socnumber)pj.soc;elseif(Array.isArray(j.soc)j.soc.length)pj.soc[j.soc.length-1];elseif(typeof j.SoCnumber)pj.SoC;if(pnull)return;setSOC(p);}catch(e){console.log(poll error,e);}}document.getElementById(btnStart).onclick(){const urldocument.getElementById(url).value.trim();const ivMath.max(0.5,Number(document.getElementById(interval).value)||1)*1000;if(!url)returnalert(Please input a JSON endpoint URL.);if(timer)clearInterval(timer);pollOnce(url);timersetInterval(()pollOnce(url),iv);};document.getElementById(btnStop).onclick(){if(timer){clearInterval(timer);timernull;}};buildChart();/script/body/html# -*- coding: utf-8 -*- 可自定义 SPI / I2C 时序图生成器 依赖: pip install Pillow 运行: python spi_i2c_custom_timing.py 特点: 1) 输出固定保存到脚本同目录 2) 支持自定义 SPI mode / bit数 / MOSI / MISO / CS有效电平 3) 支持自定义 I2C 7bit 地址 / 读写 / 数据字节 / ACK 序列 4) 自动生成 PNG 时序图 说明: - SPI: 这里画的是“逻辑示意图”不是严格 ns 级器件波形图 - I2C: 这里强调协议约束SDA 在 SCL 高电平期间保持稳定 START/STOP 是在 SCL 高时 SDA 发生跳变 from pathlib import Path from PIL import Image, ImageDraw, ImageFont import re SCRIPT_DIR Path(__file__).resolve().parent BG (255, 255, 255) FG (20, 20, 20) GRID (230, 230, 230) BLUE (52, 120, 246) RED (220, 70, 70) GREEN (34, 160, 90) ORANGE (220, 140, 40) PURPLE (128, 80, 200) GRAY (110, 110, 110) LIGHT_BLUE (215, 232, 255) LIGHT_ORANGE (255, 237, 205) STEP 86 LEFT 180 RIGHT 70 def get_font(size22): candidates [ C:/Windows/Fonts/msyh.ttc, C:/Windows/Fonts/msyhbd.ttc, C:/Windows/Fonts/simhei.ttf, C:/Windows/Fonts/arial.ttf, ] for p in candidates: try: return ImageFont.truetype(p, size) except Exception: pass return ImageFont.load_default() FONT get_font(22) FONT_SMALL get_font(18) FONT_TITLE get_font(34) def text(draw, xy, s, fillFG, fontFONT, anchorNone): draw.text(xy, s, fillfill, fontfont, anchoranchor) def y_level(base_y, highTrue, amp18): return base_y - amp if high else base_y amp def parse_int_maybe_hex(s, defaultNone): s str(s).strip() if not s: return default try: return int(s, 0) except Exception: return default def parse_bits_input(s, widthNone): 支持: - 10100101 - 0b10100101 - 0xA5 - A5 raw str(s).strip().replace(_, ).replace( , ) if not raw: return [] if re.fullmatch(r[01], raw): bits [int(c) for c in raw] if width and len(bits) width: bits [0] * (width - len(bits)) bits elif width and len(bits) width: bits bits[-width:] return bits if raw.lower().startswith(0b): bits [int(c) for c in raw[2:]] if width and len(bits) width: bits [0] * (width - len(bits)) bits elif width and len(bits) width: bits bits[-width:] return bits if raw.lower().startswith(0x): val int(raw, 16) if width is None: width (len(raw) - 2) * 4 return [(val i) 1 for i in range(width - 1, -1, -1)] if re.fullmatch(r[0-9A-Fa-f], raw): val int(raw, 16) if width is None: width len(raw) * 4 return [(val i) 1 for i in range(width - 1, -1, -1)] raise ValueError(f无法解析位串/十六进制: {s}) def parse_i2c_data_bytes(s): 支持: CA 55 0xCA,0x55 CA,55,10 raw str(s).strip() if not raw: return [] parts re.split(r[\s,;], raw) out [] for p in parts: if not p: continue out.append(int(p, 0) if p.lower().startswith(0x) else int(p, 16)) return out def parse_ack_pattern(s, n): A / N 例如: AA AAN 留空则默认全 ACK raw str(s).strip().upper().replace( , ) if not raw: return [0] * n # ACK 0 raw raw.replace(,, ) if len(raw) ! n: raise ValueError(fACK 序列长度应为 {n}你输入了 {len(raw)}) out [] for ch in raw: if ch A: out.append(0) elif ch N: out.append(1) else: raise ValueError(ACK 序列只能用 A 或 N) return out def draw_grid(draw, x0, steps, y_top, y_bottom): for i in range(steps 1): x x0 i * STEP draw.line((x, y_top, x, y_bottom), fillGRID, width1) def draw_clock(draw, x0, base_y, steps, cpol, color, name): text(draw, (50, base_y), name, anchorlm) hi y_level(base_y, True) lo y_level(base_y, False) for i in range(steps): x x0 i * STEP if cpol 0: pts [ (x, lo), (x STEP * 0.25, lo), (x STEP * 0.25, hi), (x STEP * 0.75, hi), (x STEP * 0.75, lo), (x STEP, lo), ] else: pts [ (x, hi), (x STEP * 0.25, hi), (x STEP * 0.25, lo), (x STEP * 0.75, lo), (x STEP * 0.75, hi), (x STEP, hi), ] draw.line(pts, fillcolor, width4) def draw_spi_bus(draw, x0, base_y, bits, color, name, cpha): 逻辑示意: - CPHA0: 每 bit 开始前数据已稳定采样发生在 leading edge - CPHA1: leading edge 后更新trailing edge 采样 text(draw, (50, base_y), name, anchorlm) hi y_level(base_y, True) lo y_level(base_y, False) if not bits: bits [0] # 初值 current_y hi if bits[0] else lo draw.line((x0 - 35, current_y, x0, current_y), fillcolor, width4) for i, bit in enumerate(bits): x x0 i * STEP target_y hi if bit else lo if cpha 0: # bit开始就稳定 if current_y ! target_y: draw.line((x, current_y, x, target_y), fillcolor, width4) draw.line((x, target_y, x STEP, target_y), fillcolor, width4) current_y target_y else: # 第一半拍维持上一个bit的值leading edge后切到本bit值 draw.line((x, current_y, x STEP * 0.25, current_y), fillcolor, width4) if current_y ! target_y: draw.line((x STEP * 0.25, current_y, x STEP * 0.25, target_y), fillcolor, width4) draw.line((x STEP * 0.25, target_y, x STEP, target_y), fillcolor, width4) current_y target_y def draw_spi(config): mode config[mode] width config[width] mosi_bits config[mosi_bits] miso_bits config[miso_bits] cs_active_low config[cs_active_low] cpol 1 if mode in (2, 3) else 0 cpha 1 if mode in (1, 3) else 0 steps width width_px LEFT steps * STEP RIGHT height_px 610 img Image.new(RGB, (width_px, height_px), BG) draw ImageDraw.Draw(img) text(draw, (width_px // 2, 36), fSPI 自定义时序图Mode {mode}CPOL{cpol}CPHA{cpha}, fontFONT_TITLE, anchormm) text(draw, (width_px // 2, 80), fMOSI{.join(map(str, mosi_bits))} MISO{.join(map(str, miso_bits))}, fontFONT_SMALL, fillGRAY, anchormm) y_cs 165 y_clk 265 y_mosi 365 y_miso 465 draw_grid(draw, LEFT, steps, 120, 510) for i in range(steps): cx LEFT i * STEP STEP / 2 text(draw, (cx, 132), fBit{steps - 1 - i}, fontFONT_SMALL, fillGRAY, anchormm) # CS text(draw, (50, y_cs), CS, anchorlm) active y_level(y_cs, not cs_active_low) inactive y_level(y_cs, cs_active_low) draw.line((LEFT - 70, inactive, LEFT, inactive), fillRED, width4) draw.line((LEFT, inactive, LEFT, active), fillRED, width4) draw.line((LEFT, active, LEFT steps * STEP, active), fillRED, width4) draw.line((LEFT steps * STEP, active, LEFT steps * STEP, inactive), fillRED, width4) draw.line((LEFT steps * STEP, inactive, LEFT steps * STEP 70, inactive), fillRED, width4) draw_clock(draw, LEFT, y_clk, steps, cpol, BLUE, SCLK) draw_spi_bus(draw, LEFT, y_mosi, mosi_bits, GREEN, MOSI, cpha) draw_spi_bus(draw, LEFT, y_miso, miso_bits, ORANGE, MISO, cpha) # 采样边沿标记 # leading edge at 0.25, trailing at 0.75 if cpol 0: leading_edge_name 上升沿 trailing_edge_name 下降沿 else: leading_edge_name 下降沿 trailing_edge_name 上升沿 sample_on leading_edge_name if cpha 0 else trailing_edge_name update_on trailing_edge_name if cpha 0 else leading_edge_name for i in range(steps): x LEFT i * STEP (STEP * 0.25 if cpha 0 else STEP * 0.75) draw.line((x, 140, x, 500), fillLIGHT_BLUE, width1) draw.ellipse((x - 5, y_clk - 5, x 5, y_clk 5), fillPURPLE) text(draw, (width_px // 2, 545), f本图中接收端在 {sample_on} 采样在 {update_on} 更新/切换数据。, fontFONT_SMALL, fillGRAY, anchormm) out SCRIPT_DIR / custom_spi_timing.png img.save(out) print(f已生成: {out}) return img def draw_i2c(config): addr config[address] rw config[rw] data_bytes config[data_bytes] ack_bits config[ack_bits] addr_bits [(addr i) 1 for i in range(6, -1, -1)] rw_bit [0 if rw W else 1] sda_bits addr_bits rw_bit [ack_bits[0]] labels [fA{i} for i in range(6, -1, -1)] [R/W, ACK1] for idx, b in enumerate(data_bytes, start1): dbits [(b i) 1 for i in range(7, -1, -1)] sda_bits.extend(dbits) sda_bits.append(ack_bits[idx]) labels.extend([fD{i} for i in range(7, -1, -1)] [fACK{idx1}]) steps len(sda_bits) width_px LEFT (steps 1) * STEP RIGHT height_px 650 img Image.new(RGB, (width_px, height_px), BG) draw ImageDraw.Draw(img) ack_text .join(A if b 0 else N for b in ack_bits) data_text .join(f0x{b:02X} for b in data_bytes) text(draw, (width_px // 2, 36), I2C 自定义时序图, fontFONT_TITLE, anchormm) text(draw, (width_px // 2, 80), f地址0x{addr:02X} {rw} 数据{data_text} ACK序列{ack_text}, fontFONT_SMALL, fillGRAY, anchormm) y_scl 270 y_sda 420 draw_grid(draw, LEFT, steps 1, 140, 530) for i, lab in enumerate(labels): cx LEFT i * STEP STEP / 2 text(draw, (cx, 152), lab, fontFONT_SMALL, fillGRAY, anchormm) # SCL draw_clock(draw, LEFT, y_scl, steps, 0, BLUE, SCL) hi y_level(y_sda, True) lo y_level(y_sda, False) # SDA text(draw, (50, y_sda), SDA, anchorlm) draw.line((LEFT - 80, hi, LEFT, hi), fillGREEN, width4) # START draw.line((LEFT, hi, LEFT, lo), fillRED, width4) text(draw, (LEFT - 25, y_sda - 52), START, fontFONT_SMALL, fillRED, anchormm) current_y lo for i, bit in enumerate(sda_bits): x LEFT i * STEP target_y hi if bit else lo # SCL低期间允许变化 draw.line((x, current_y, x STEP * 0.25, current_y), fillGREEN, width4) if current_y ! target_y: draw.line((x STEP * 0.25, current_y, x STEP * 0.25, target_y), fillGREEN, width4) # SCL高期间必须稳定 draw.line((x STEP * 0.25, target_y, x STEP, target_y), fillGREEN, width4) current_y target_y # STOP: 在SCL高时 SDA 低-高 stop_x LEFT steps * STEP if current_y ! lo: draw.line((stop_x, current_y, stop_x STEP * 0.25, current_y), fillGREEN, width4) draw.line((stop_x STEP * 0.25, current_y, stop_x STEP * 0.25, lo), fillGREEN, width4) current_y lo else: draw.line((stop_x, lo, stop_x STEP * 0.25, lo), fillGREEN, width4) draw.line((stop_x STEP * 0.25, lo, stop_x STEP * 0.75, lo), fillGREEN, width4) draw.line((stop_x STEP * 0.75, lo, stop_x STEP * 0.75, hi), fillRED, width4) draw.line((stop_x STEP * 0.75, hi, stop_x STEP, hi), fillGREEN, width4) text(draw, (stop_x STEP * 0.8, y_sda - 52), STOP, fontFONT_SMALL, fillRED, anchormm) # ACK高亮 ack_positions [8] # 7bit地址 rw cursor 9 for _ in data_bytes: ack_positions.append(cursor 8) cursor 9 for idx, pos in enumerate(ack_positions): x LEFT pos * STEP STEP / 2 draw.rectangle((x - 34, 176, x 34, 510), outlineLIGHT_ORANGE, width2) label ACK if ack_bits[idx] 0 else NACK text(draw, (x, 552), label, fontFONT_SMALL, fillORANGE, anchormm) text(draw, (width_px // 2, 595), I2C 也有“采样”这个动作但它不是像 SPI 那样让你选 Mode核心规则是 SDA 在 SCL 高电平期间必须稳定。, fontFONT_SMALL, fillGRAY, anchormm) out SCRIPT_DIR / custom_i2c_timing.png img.save(out) print(f已生成: {out}) return img def combine(spi_img, i2c_img): gap 28 w max(spi_img.width, i2c_img.width) h spi_img.height i2c_img.height gap canvas Image.new(RGB, (w, h), BG) canvas.paste(spi_img, (0, 0)) canvas.paste(i2c_img, (0, spi_img.height gap)) out SCRIPT_DIR / custom_spi_i2c_timing.png canvas.save(out) print(f已生成: {out}) def ask(prompt, defaultNone): if default is None: s input(f{prompt}: ).strip() else: s input(f{prompt} [{default}]: ).strip() return s if s else default def collect_spi_config(): print(\n SPI 配置 ) mode parse_int_maybe_hex(ask(SPI mode 请输入 0/1/2/3, 0), 0) if mode not in (0, 1, 2, 3): raise ValueError(SPI mode 只能是 0/1/2/3) width parse_int_maybe_hex(ask(bit 数, 8), 8) mosi_raw ask(MOSI 数据支持 10100101 / 0b10100101 / 0xA5 / A5, 0xA5) miso_raw ask(MISO 数据同上, 0x5A) mosi_bits parse_bits_input(mosi_raw, width) miso_bits parse_bits_input(miso_raw, width) cs_active_low ask(CS 是否低有效Y/N, Y).strip().upper() ! N return { mode: mode, width: width, mosi_bits: mosi_bits, miso_bits: miso_bits, cs_active_low: cs_active_low, } def collect_i2c_config(): print(\n I2C 配置 ) addr parse_int_maybe_hex(ask(7bit 从机地址支持 0x50 或 50默认按十六进制理解建议写 0x50, 0x50), 0x50) if addr 0 or addr 0x7F: raise ValueError(I2C 7bit 地址范围应为 0x00~0x7F) rw ask(读写方向 W/R, W).strip().upper() if rw not in (W, R): raise ValueError(读写方向只能是 W 或 R) data_bytes parse_i2c_data_bytes(ask(数据字节多个字节可写 0xCA 0x55 或 CA,55, 0xCA)) if not data_bytes: data_bytes [0xCA] for b in data_bytes: if b 0 or b 0xFF: raise ValueError(数据字节必须在 0x00~0xFF 范围内) ack_count 1 len(data_bytes) ack_tips ACK 序列长度 地址阶段1位 每个数据字节1位。例如 1字节数据填 A A2字节填 A A A最后若NACK可填 N print(ack_tips) ack_bits parse_ack_pattern(ask(fACK/NACK 序列AACK, NNACK共 {ack_count} 位, A * ack_count), ack_count) return { address: addr, rw: rw, data_bytes: data_bytes, ack_bits: ack_bits, } def main(): print(可自定义 SPI / I2C 时序图生成器) print(直接回车可使用默认值。) choice ask(生成哪种图输入 spi / i2c / both, both).strip().lower() spi_img None i2c_img None if choice in (spi, both): spi_cfg collect_spi_config() spi_img draw_spi(spi_cfg) if choice in (i2c, both): i2c_cfg collect_i2c_config() i2c_img draw_i2c(i2c_cfg) if choice both and spi_img is not None and i2c_img is not None: combine(spi_img, i2c_img) print(\n完成。输出文件保存在脚本同目录。) if __name__ __main__: main()

更多文章