1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Raspberry Pi と PLC(KV-7500) をPythonで接続してリアルタイム監視する仕組み

Last updated at Posted at 2025-11-21

はじめに

本記事では、Raspberry PiKeyence PLC(KV-7500) をPythonで接続し、
リアルタイムで工場データを監視・取得する仕組みを構築する方法を解説します。

Raspberry Pi の低コスト性と拡張性、Keyence PLC の工場現場での信頼性を組み合わせることで、
高機能な監視システムやダッシュボードを安価に構築できます。


全体構成

[Raspberry Pi 5]  ←→  [LAN]  ←→  [Keyence PLC KV-7500]
       ↓
  Pythonプログラム
       ↓
  MariaDB / ダッシュボード(FastAPI)

1. Raspberry Pi 側の準備

1-1. 必要なライブラリをインストール

sudo apt update
sudo apt install python3-pip
pip install pymodbus fastapi uvicorn pymysql

2. Keyence PLC 側の設定

2-1. Ethernetポートの有効化

KV-7500 の ユニット設定 → Ethernet設定 で以下を確認します:

  • IPアドレス(例:192.168.1.20)
  • 送受信ポート番号(通常は 502 でOK)
  • Modbus-TCP を使用可能に設定

3. Python で PLC に接続する(Modbus-TCP)

3-1. 最小コード例(DM 読み取り)

from pymodbus.client import ModbusTcpClient

PLC_IP = "192.168.1.20"
PORT = 502

client = ModbusTcpClient(PLC_IP, port=PORT)
client.connect()

# DM100 を 1ワード読み出す
result = client.read_holding_registers(100, 1, unit=1)
print("DM100 =", result.registers[0])

client.close()

3-2. 複数データをまとめて読む

# DM6000-6010 をまとめて読み出す
res = client.read_holding_registers(6000, 10, unit=1)

for i, v in enumerate(res.registers):
  print(f"DM{6000+i} = {v}")

4. リアルタイム監視ループ

以下のコードは、PLCの DM6002 (CT秒), DM6003 (NGフラグ) を
1秒ごとに取得し、画面に表示するシンプルな監視サンプルです。

import time
from pymodbus.client import ModbusTcpClient

client = ModbusTcpClient("192.168.1.20", port=502)
client.connect()

while True:
  try:
    r = client.read_holding_registers(6000, 10, unit=1)
    dm = r.registers

    ct = dm[2]        # DM6002
    ng = dm[3]        # DM6003

    print(f"CT={ct}, NG={ng}")

    time.sleep(1)
  except Exception as e:
    print("Error:", e)
    time.sleep(2)

5. MariaDB に保存してダッシュボード化(FastAPI)

5-1. テーブル設計(log)

CREATE TABLE log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  timestamp DATETIME,
  ct INT,
  ng INT
);

5-2. FastAPI 経由でログを保存

from fastapi import FastAPI
import pymysql
import datetime

app = FastAPI()

db = pymysql.connect(
  host="localhost"
  user="xxxxxx",
  password="yyyyyy",
  database="log",
  autocommit=True
)

@app.get("/api/save")
def save(ct: int, ng: int):
  with db.cursor() as cur:
    cur.execute(
      "INSERT INTO log (timestamp, ct, ng) VALUES (%s, %s, %s)",
      (datetime.datetime.now(), ct, ng)
    )
  return {"status": "ok"}

6. ダッシュボード表示(/dashboard)

FastAPI のテンプレート機能を使うと、
リアルタイムラインチャートや NG率解析などのダッシュボードが簡単に作れます。


7. Raspberry Pi + PLC 連携のメリット

  • Keyence の高信頼性プラットフォームをそのまま活用できる
  • Raspberry Pi で低コストなダッシュボード化
  • Python で柔軟に処理(AI 判定・画像解析も可)
  • Modbus-TCP でリアルタイム取得が簡単
  • MariaDB と組み合わせて履歴データも蓄積可能

まとめ

本記事では Raspberry Pi × Keyence KV-7500
Python でリアルタイム接続する方法を一通り紹介しました。

工場DX・IoT化の第一歩として最もコスパの良い組み合わせです。
応用次第で AI 画像判定・品質管理・OEE監視などにも発展できます!

質問や追加パートの依頼があれば、ぜひコメントしてください

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?