linuxbashgpio

PWM Fan Control Script `unary operator expected`


My twin RPi fan has some inertia at startup. So it will not start at duty_cycle ~20000 however it can start at 30000 & then can be lowered to 20000. So we need some kick-start mechanism as well

I am having this error [: -eq: unary operator expected in line 30

#!/bin/bash
echo 0 > /sys/class/pwm/pwmchip1/export
echo 50000 > /sys/class/pwm/pwmchip1/pwm0/period #20kHz PWM period in nanoseconds
echo normal > /sys/class/pwm/pwmchip1/pwm0/polarity
# Set initial fan speed
duty_cycle=30000
min_duty_cycle=20000
echo $duty_cycle > /sys/class/pwm/pwmchip1/pwm0/duty_cycle
sleep 1  # Give the fan some time to start

while true
do
  # Read CPU temperature
  temp=$(cat /sys/devices/virtual/thermal/thermal_zone0/temp)

  # Convert temperature to integer (divide by 1000)
  temp=$((temp / 1000))

  # Set PWM duty cycle based on temperature
  if [ $temp -gt 73 ]; then
    duty_cycle=40000
  elif [ $temp -gt 68 ]; then
    duty_cycle=30000
  elif [ $temp -gt 65 ]; then
    duty_cycle=$min_duty_cycle
  else
    duty_cycle=0
  fi

  if [ $duty_cycle -eq $min_duty_cycle ] && [ $(cat /sys/class/pwm/pwmchip2/pwm0/duty_cycle) -eq 0 ]; then
    echo 30000 > /sys/class/pwm/pwmchip1/pwm0/duty_cycle
    sleep 2
  fi

  echo $duty_cycle > /sys/class/pwm/pwmchip1/pwm0/duty_cycle

  # Add a small delay to avoid excessive CPU usage
  sleep 3
done



Solution

  • The error [: -eq: unary operator expected means that you are trying to compare two numbers using -eq, but one of them is missing or empty. And it's pwmchip2.

    You initialized and wrote to /sys/class/pwm/pwmchip1, not pwmchip2:

    echo $duty_cycle > /sys/class/pwm/pwmchip1/pwm0/duty_cycle
    

    So when you do:

    if [(...) ] && [ $(cat /sys/class/pwm/pwmchip2/pwm0/duty_cycle) -eq 0 ]; then
    

    It's trying to read something that is empty.

    Your if should be this instead:

    if [(...) ] && [ $(cat /sys/class/pwm/pwmchip1/pwm0/duty_cycle) -eq 0 ]; then