How to read I2C without specified device from FB

yledermann
2018-01-25
2021-02-15
  • powertrick

    powertrick - 2021-02-15

    Yiedermann thank you for the snippet as my codesys is reading an i2c slave.....any chance you know how to write to a slave as I tried anything I could think of. Seems the usage mimics the I2C method comparing the read so for write I tried below:

    datatoread:  ARRAY [0..1] OF BYTE  := [2(0)];
    
            I2C_master.write(16#68, 16#15, 1);  
            I2C_master.write(16#68, ADR(datatostore), 2);
    
     
    πŸ‘
    1
  • eschwellinger

    eschwellinger - 2018-01-26

    Hi,

    for I2C guess this example here would do the job:
    l viewtopic.php?f=23&t=6247&p=19944#p19944 l

    for SPI:
    "c:\Users\<yourwindowsusername>\CODESYS Control for Raspberry PI\3.5.12.0\Examples\PiFace_FB.project"
    BR
    Edwin</yourwindowsusername>

     
  • yledermann

    yledermann - 2018-01-26

    Hi Edwin

    Thank you for the fast answer.
    That was the example i already tried.
    But i found another one...
    https://forum-raspberrypi.de/forum/thread/32601-neubau-hardware/?postID=304583#post304583
    This example was the missing point.
    i need to write to the register before i read it back...

    just in case someone else is fighting with the basics of i2c here is my working code:

    FUNCTION_BLOCK UPSHAT
    VAR_INPUT
    Β  Β usiAddress : USINT := 16#36;
    END_VAR
    VAR_OUTPUT
    Β  Β rVoltage : REAL := 0;
    END_VAR
    VAR
    Β  Β // Registers
    Β  Β byRegVoltage Β  Β : BYTE := 16#02;
    Β  Β baReadBufferV : ARRAY [0..1] OF BYTEΒ  := [2(0)];
    Β  Β nReadLenght: DINT;
    END_VAR
    // Register Spannung auf Bus schreiben...
    I2C_master.write(usiAddress, ADR(byRegVoltage), 1);Β  
    // ... und Wert lesen.
    nReadLenght := I2C_master.read(usiAddress, ADR(baReadBufferV), 2);
    // wenn zwei Bytes gelesen worden sind die Spannung berechnen uns ausgeben
    IF nReadLenght = 2 THEN
    // Daten zwischenspeichern
    //swap_word := MEM.PackBytesToWord(baReadBuffer[1],baReadBuffer[0]);
    //rVoltage := (swap_word * 78.125 / 1000000);
    rVoltage := (MEM.PackBytesToWord(baReadBufferV[1],baReadBufferV[0]) * 78.125 / 1000000);
    END_IF;
    
     

    Related

    Talk.ru: 1

  • eschwellinger

    eschwellinger - 2018-01-26

    Hi,
    thanks for the feedback,
    if you want you could publish your application here:
    Raspberry Pi: List of available example applications
    think other user would be very thankful for these kind of Information and applications.
    BR
    Edwin

     

Log in to post a comment.