-2

I have the following code:

regRead8: function(address){ 

        wire.write([address & 0xFF, address >> 8], function(err){
          if (!err == null) {
            console.log(err)
          } 
        })

       wire.read(1, function(err, res){
        if (!err == null) {
          console.log(err)
        }
          
        }) 

    }

regRead8 is a function that takes a parameter (address) and is doing two things:

  1. Is writing to an FPGA the address from where the next command should read.
  2. The read command reads 1 byte of information from the latter selected register

Now, I want that function regRead8() to return the value obtained in the second function (i.e wire.read()...

regRead8(registerValueGoesHere) will be part another function that would return the value of the register specified.

I'm using a library called i2c that forces me to use this way of function with a callback, otherwise it errors.

What should I do?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
iBus
  • 1
  • 1
  • In that post seemed to be so many alternatives but haven't found one to match my case, just a generic asyc-callback-promise that doesn't necessarily apply directly to my code. Or I don't know what to look for? – iBus Feb 09 '23 at 19:06

1 Answers1

-2

Assuming that wire.read is synchronous

 regRead8: function(address){ 
    let result;
    wire.write([address & 0xFF, address >> 8], function(err){
      if (!err == null) {
        console.log(err)
      } 
    })

   wire.read(1, function(err, res){
    if (!err == null) {
      console.log(err)
    }
      result=res;
    }) 
    // eventually do check if result is empty and handle it
    return result;
}
koalaok
  • 5,075
  • 11
  • 47
  • 91
  • wouldn't "const result;" make it unable to be changed later in the code? It seems like that when I tried to run the function with the following error: "Missing initializer in const declaration" – iBus Feb 09 '23 at 19:03