# Fetching the latest value from external sources using Channel

**URL:** <https://discourse.julialang.org/t/fetching-the-latest-value-from-external-sources-using-channel/126901>\
**Category:** General Usage\
**Tags:** async\
**Created:** [March 13, 2025, 9:54am UTC](https://discourse.julialang.org/t/fetching-the-latest-value-from-external-sources-using-channel/126901 "2025-03-13T09:54:14Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![leejm516](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/leejm516/32/8219_2.png) [@leejm516](https://discourse.julialang.org/u/leejm516)\
**Post date:** [March 13, 2025, 9:54am UTC](https://discourse.julialang.org/t/fetching-the-latest-value-from-external-sources-using-channel/126901/1 "2025-03-13T09:54:14Z")

</div>

Hi!

Sorry for my bad English to describe the title.

I am trying to make a small code which fetches a value from a MCU (Arduino, ESP32, etc.) upon request.

The MCU periodically saves the sensor value measured into its variable, and it sends the value of the variable to Julia upon receving a predefined serial message.

On the Julia side, I decided to use Channel to fetch the value.

```julia
using LibSerialPort

sp = LibSerialPort.open("COM4", 115200)

chnl = Channel()

function getsensorval(c::Channel, p::SerialPort)
    while true
        write(sp, "1\n")
        sleep(0.01)
        if bytesavailable(p) > 0
            t = String(read(p))
            t = split(t)[end]
            put!(c, t)
        end
    end
end

```

One problem is that the loop in `getsensorval` helds before `put!` until task!(chnl) is executed, and the value stored in `t` remains old. As a result, I only could get an old value of t when executing `task!(chnl)` after a long period. This makes me run `task!` again to update the latest value.

One WE mimicking this problem without MCUs is:

```julia
x = 0

function genval() # increases x by 1 a second
    while true
        global x += 1        
        sleep(1)
    end
end

function readval(c::Channel)
    while true
        t = string(x)
        put!(c, t)
    end
end

chnl = Channel()
@async genval()
@async readval(chnl)

```

```julia
julia> take!(chnl) # executed immediately
"1"   

julia> take!(chnl) # executed again after about one minute from the first take! (expecting "50"~"70")
"1"   

julia> take!(chnl) # executed immediately after the second execution
"53"

```

Is there a way to solve the issue?  
Always appreciate comments from the community.
