Search code examples
arraysbashshellsyntax-errorarithmetic-expressions

Problem with Bash Script array arithmetic for simple sine wave generator


I'm fairly new to bash scripting and linux in general. I'm trying to send a series of rapid commands to pressure regulator (half a second apart), which I normally do so with simple square pulse using bash scripts. However I can't seem to get the syntax correct for a sine wave shaped pulse instead. I couldn't find a way to use an actual sine function, but a series of small discrete steps would work just as well.

Here's my script:

#!/bin/bash

Pmax="90"
Pmin="10"
Rcor="7.91"  #This converts the pressure setting into the devices scaled range.
declare -a Sinewave20=(0 0.309 0.588 0.809  0.951  1  0.951  0.809  0.580 0.309 0 -0.309 -0.588 -0.809 -0.951 -1 -0.951 -0.809 -0.588 -0.309)
Amplitude=$(( $Pmax-$Pmin ))
Offset=$(( $Pmin+$Amplitude/2  ))

# 6 cycles of Sinewave20 corresponds to 1 min of .1 hz sine wave
for i in {0..6}
do
        # Let's send the commands for a 20 pt sine wave
        for x in "${!Sinewave20[@]}";
        do
                Value=$(( $Amplitude*$Rcor*$Sinewave20[x]+{Offset*$Rcor ))

                echo -e "SET ${Value}\r"  > /dev/ttyUSB1
                sleep 0.5
        done
done

This results in the following error msg:

line 18: 80*7.91*0[x]+{Offset*7.91: syntax error: invalid arithmetic operator (error token is ".91*0[x]+{Offset*7.91")

I've tried various ways of writing it but haven't found one that works. The command to change the pressure is simply:

echo -e "SET 100\r" > /dev/ttyUSB1


Solution

  • Bash arithmetic is limited to integers.

    Consider using a scripting engine that has built-in support for floating point numbers. Either the light weight awk or bc, or one of the full languages: Python, Perl, etc.

    See: How do I use floating-point division in bash? and https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks/40787#40787