1
votes

I am writing an extreme simple lua script about counting how many time an led flash

However, it keep giving me error when i try to assign a return value from previous function to a local variable in a different function.

function ReadADC1()
    local adc_voltage_value = 0
    adc_voltage_value = tonumber(adc.readadc()) * 2 -- 0.10 --get dec number out of this -- need to know where package adc come from
    --convert to voltage
    adc_voltage_value = adc_voltage_value *0.000537109375 --get V
    adc_voltage_value = math.floor(adc_voltage_value *1000 +0.5) --since number is base off resolution

    --print (adc_voltage_value)
    return adc_voltage_value

end
-- end of readADC1() TESTED

function counter()

    local ledValue = readADC1()
    --local interval -- interval between led on and off. If interval larger than 1 second, reset counter 

    --TODO add interval definition

    local interval = os.clock()
    while (true) do
        if ((ledValue >= OnThreshHold) and (interval < 1000)) then -- if value exceed threshhold, mean it on 
                ledCounter = ledCounter + 1
        elseif ((ledValue < OnThreshHold) and (os.clock() - interval > 1000)) then -- if led off for longer than 1 second
                ledCounter = 0  -- reset counter to one and prepare for next flashing
        else
            ledCounter = ledCounter -- not sure if we need this. Doing this might cause bug later on
        end
    end
    --return ledCounter
    print (ledCounter,"\r\n")
    end
-- end of counter()

As you can see, i am trying to assigned ledValue with adc_voltage_value from ReadADC1 function. I thought it suppose to work but turn out it didnt. It give me this error:

> +LUA ERROR: LEDcounter.lua:29: attempt to call global 'readADC1' (a nil value)
> 
> stack traceback:
> 
>     LEDcounter.lua:29: in main chunk
> 
>     [C]: ?

I have use blackbox debugging and test each function independently and ReadADC1 give me a nice number value. but when i test the counter() function, it gave me that error

Any suggestion or fix are welcome. I am trying to learn

1

1 Answers

2
votes

Looking closely at your error, it's clear to see that Lua is having trouble finding a function (or indeed any other variable) by that name. If you look a bit closely, you can see that the call to readADC1 is invalid because there is no such function. This is because the function you defined is called ReadADC1 instead. Notice the capital letter and remember that variables are case-sensitive in Lua.