guild icon
Toit
#Hi, trying to fill a list, below is my code and result.
Thread channel in help
Macca
Macca 04/04/2023 06:27 AM
import gpio
import gpio.adc show Adc


SampleSize := 3
Sample := 0
SampleTotal := 0.0
adc := Adc (gpio.Pin 34)
Readings := []

main:

for i := 0; i < SampleSize; i += 1:
Readings[i] = adc.get
sleep --ms=1
//print Readings[i]
Calculate_RMS
sleep --ms=10000

Calculate_RMS:
Readings.do: SampleTotal = SampleTotal + it.SampleTotal
print SampleTotal
print Sample

Decoding by jag, device has version <2.0.0-alpha.69>
**
EXCEPTION error.
OUT_OFBOUNDS
0: List
.[]= <sdk>/core/collections.toit:1865:24
1: main adc_test.toit:14:17
**
Macca
Macca 04/04/2023 06:30 AM
line 14 is Readings[i] = adc.get
Macca
Macca 04/04/2023 06:57 AM
After much trial & error I fixed it. My answer was:
Macca
Macca 04/04/2023 06:57 AM
for i := 0;i < SampleSize - 1; i += 1:
Reading = adc.get
Readings.add Reading
bitphlipphar
bitphlipphar 04/04/2023 09:11 AM
i < SampleSize was correct.
bitphlipphar
bitphlipphar 04/04/2023 09:12 AM
... and an alternative to calling add (which grows the list) is to do Readings := List SampleSize before the loop.
bitphlipphar
bitphlipphar 04/04/2023 09:13 AM
You can even try Readings := List SampleSize: adc.get and drop the loop.
bitphlipphar
bitphlipphar 04/04/2023 09:13 AM
It calls the block passed to the list constructor SampleSize times.
bitphlipphar
bitphlipphar 04/04/2023 09:14 AM
You can sleep from within there too.
Macca
Macca 04/05/2023 07:46 AM
Thanks @bitphlipphar, yes I discovered that Readings kept growing, so cleared it after each "loop" I will try your suggestion.(edited)
10 messages in total