LOL. i was hoping you would say a setting i didn't activate in the editor that's hidden somewhere. i believe the PSM is good, i should be able to read from the w1_slave file, for some reason im always reading 0, if i cat that file i have a good value i was thinking a permission issue but im unsure now. Learning as i go here.
# --- Library Imports ---
import psm
import time
from gpiozero import DigitalInputDevice, DigitalOutputDevice, PWMOutputDevice
from gpiozero.exc import BadPinFactory
# Import the os library to run a system command to check permissions
import os
# --- Global Variables ---
# Define the BCM pin numbers for all your GPIO connections.
# This example uses some common, unused pins.
# NOTE: Pin BCM4 was removed from this list because the previous log showed
# a "GPIO busy" error for this pin, which indicates it's being used by another
# service. You should check your system to see what is using this pin.
INPUT_PINS = [2, 3, 14, 15] # Example BCM pin numbers for inputs
OUTPUT_PINS = [17, 27, 22, 10, 9] # Example BCM pin numbers for outputs
PWM_PIN = 18 # Example BCM pin number for the single PWM output
# --- 1-Wire Sensor Variables ---
# The ID of your 1-Wire sensor. You must get this from your system.
# You can find the ID by running `ls /sys/bus/w1/devices/` in your terminal.
# It will be a string like '28-00000a20f925'.
ONE_WIRE_SENSOR_ID = "28-4340d4457d83" # <<< YOUR SENSOR ID
# Lists to hold the gpiozero device objects
input_devices = []
output_devices = []
pwm_output = None
# Variable to hold the file path to the sensor's temperature data.
# This is a much more robust way to read the sensor's data directly.
one_wire_sensor_file = None
def hardware_init():
"""
Initializes all the GPIO hardware devices.
This function runs once when the PSM driver starts.
"""
global input_devices
global output_devices
global pwm_output
global one_wire_sensor_file
print("PSM: Initializing hardware with gpiozero...")
try:
# Check for necessary dependencies. On Raspberry Pi 5, the preferred
# method is the 'lgpio' library, which replaces 'pigpio'.
# Your logs show gpiozero trying to fall back to 'pigpio', which fails
# because the service doesn't recognize the Pi 5.
# To fix this, you should install 'lgpio' in your virtual environment:
# pip install lgpio
# With this library installed, gpiozero will automatically use it
# as a backend, and your code will run correctly.
# Initialize all digital input devices
for pin in INPUT_PINS:
# The 'pull_up=True' argument enables the internal pull-up resistor,
# which is useful for connecting simple push buttons.
# You can change this to 'pull_down=True' or remove it if not needed.
device = DigitalInputDevice(pin, pull_up=True)
input_devices.append(device)
print(f"PSM: Initialized input pin BCM{pin}")
# Initialize all digital output devices
for pin in OUTPUT_PINS:
device = DigitalOutputDevice(pin)
output_devices.append(device)
print(f"PSM: Initialized output pin BCM{pin}")
# Initialize the single PWM output device
pwm_output = PWMOutputDevice(PWM_PIN)
print(f"PSM: Initialized PWM output pin BCM{PWM_PIN}")
# Initialize the 1-Wire temperature sensor file path
one_wire_sensor_file = f"/sys/bus/w1/devices/{ONE_WIRE_SENSOR_ID}/w1_slave"
except BadPinFactory as e:
# This specific error indicates the gpiozero library couldn't talk to the GPIO pins.
print("\nPSM Error: Failed to initialize hardware! The GPIO pin factory is not working.")
print("Please check that the 'pigpio' library is installed and running on your system.")
print("You can try running the following commands in your terminal to fix this:")
print("sudo apt-get install pigpio python3-pigpio")
print("sudo systemctl enable pigpiod")
print("sudo systemctl start pigpiod\n")
# Set the error value to 1 before stopping.
psm.set_var("IW0.0", 1)
# Stop the PSM gracefully to prevent continuous errors.
try:
psm.stop()
except NameError:
# This handles the case where the PSM library throws a NameError on stop().
# It's a bug in the PSM library that we are now handling gracefully.
pass
return False
except Exception as e:
print(f"PSM Error: Failed to initialize hardware. Check your pin numbers and wiring. Error: {e}")
# Set the error value to 1 before stopping.
psm.set_var("IW0.0", 1)
try:
psm.stop()
except NameError:
pass
return False
# Debugging Check: Send a value to the PLC to confirm communication is working.
psm.set_var("IW0.0", 999)
# Add a short delay to allow the value to be written before a read attempt.
time.sleep(1)
print("PSM: Successfully initialized and sent debug value to PLC.")
psm.start()
return True
def update_inputs():
"""
Reads the state of the physical input pins and updates the
corresponding OpenPLC variables.
This function runs cyclically.
"""
# The 'index' in OpenPLC's %IX0.0, %IX0.1 corresponds to the
# index of the pin in our INPUT_PINS list.
try:
for i, device in enumerate(input_devices):
# Read the value from the gpiozero input device.
# 'device.is_active' is True if the pin is high.
# We use 'psm.set_var' to write this value to the OpenPLC variable.
psm.set_var(f"IX0.{i}", device.is_active)
except Exception as e:
print(f"PSM Error: Failed to update inputs. Error: {e}")
# Read and update 1-Wire sensor value by reading the system file directly.
try:
if one_wire_sensor_file is not None:
# The new read_temperature function handles retries and returns the temp or None
temperature_c = read_temperature()
if temperature_c is not None:
# Convert the float temperature to an integer by rounding.
temperature_int = int(round(temperature_c))
psm.set_var("IW0.0", temperature_int)
else:
# If the temperature could not be read, send 1 to check for errors
psm.set_var("IW0.0", 1)
except Exception as e:
print(f"PSM Error: Failed to update 1-Wire sensor. Error: {e}")
# If any other error occurs, also send 1
psm.set_var("IW0.0", 1)
def read_temperature():
"""
Attempts to read the temperature from the 1-Wire sensor file.
Includes a retry mechanism for transient errors.
Returns the temperature in Celsius or None if reading fails.
"""
for i in range(5): # Try up to 5 times
try:
with open(one_wire_sensor_file, "r") as f:
lines = f.readlines()
# The first line must end with YES for a valid reading
if lines[0].strip().endswith("YES"):
temp_output = lines[1].find("t=")
if temp_output != -1:
temp_string = lines[1].strip()[temp_output + 2:]
return float(temp_string) / 1000.0
# If CRC check fails, print a message and retry
print(f"PSM: Sensor reading attempt {i+1} failed, CRC check failed. Retrying...")
time.sleep(0.5)
except FileNotFoundError:
print(f"PSM: Sensor file not found at {one_wire_sensor_file}. Is the sensor connected and the 1-Wire interface enabled?")
return None # Don't retry if the file doesn't exist.
except Exception as e:
print(f"PSM Error: An error occurred while reading sensor file. Retrying... Error: {e}")
time.sleep(0.5)
print("PSM: Failed to get a valid sensor reading after multiple attempts.")
return None
def update_outputs():
"""
Reads the state of the OpenPLC output variables and sets the
state of the physical output pins.
This function runs cyclically.
"""
# Digital Outputs (DO)
# The 'index' in OpenPLC's %QX0.0, %QX0.1 corresponds to the
# index of the pin in our OUTPUT_PINS list.
try:
for i, device in enumerate(output_devices):
# Read the value from the OpenPLC variable.
# psm.get_var returns a boolean (True/False).
value = psm.get_var(f"QX0.{i}")
if value:
device.on() # Turn the physical pin on
else:
device.off() # Turn the physical pin off
except Exception as e:
print(f"PSM Error: Failed to update digital outputs. Error: {e}")
# PWM Output (AO)
# The PWM value in OpenPLC is handled by a 16-bit unsigned integer (%QW0.0).
# We need to convert this value (0-65535) to a duty cycle (0.0-1.0).
try:
# Check if the PWM output device was initialized successfully.
if pwm_output is not None:
# Get the 16-bit value from OpenPLC.
pwm_value = psm.get_var("QW0.0")
# Ensure the value is within the expected range.
if 0 <= pwm_value <= 65535:
# Normalize the value to a range of 0.0 to 1.0.
duty_cycle = pwm_value / 65535.0
# Set the duty cycle of the physical PWM pin.
pwm_output.value = duty_cycle
except Exception as e:
print(f"PSM Error: Failed to update PWM output. Error: {e}")
if __name__ == "__main__":
if hardware_init():
try:
while (not psm.should_quit()):
update_inputs()
update_outputs()
time.sleep(0.1) # PSM cycle time. Adjust if needed.
except Exception as e:
print(f"PSM Error: An unexpected error occurred in the main loop. Error: {e}")
finally:
psm.stop()