' File: I2C_Scan.bas
' By COS, 2025/07/19, Pic18 Basic Oshonsoft, v5.89
' *****************************************************************************
' Requires: I2CLib.bas (for START_I2C, STOP_I2C, WRITE_I2C)
' Requires: initializing hardware serial port for data output, can be changed To another system To display data.
' Description:
'   Scans the I2C bus for devices by attempting to write to each address
'   from 0x03 to 0x77. If a device responds with ACK, the address is printed
'   via UART1. Returns the total number of detected devices.

'------------------------------------------------------------------------------
' Function: I2C_Ping
' Sends a START condition, then the 7-bit address (with write bit = 0),
' and a STOP condition. Returns 0 if the device acknowledges (ACK), or a non-zero value if not.
'------------------------------------------------------------------------------
Function I2C_Ping(addr As Byte) As Byte
    Dim err As Byte
    START_I2C()
    err = WRITE_I2C((addr << 1) | 0)  ' Send address with write bit
    STOP_I2C()
    ReturnValue err
End Function

'------------------------------------------------------------------------------
' Function: I2C_Scan
' Loops through valid 7-bit I2C addresses (0x03 to 0x77),
' calls I2C_Ping for each, and prints out the found devices over UART1.
' Returns the number of devices found.
'------------------------------------------------------------------------------
Function I2C_Scan() As Byte
   Dim found As Byte
   found = 0
   Dim addr As Byte
   CFor (addr = 0x03; addr <= 0x90; addr++) '77
      If I2C_Ping(addr) == 0 Then 'ANK
         UART_Write "I2C device on: 0x", HexStr(addr), CrLf
         found++
      Endif
   CNext
   UART_Write "Total devices: ", #found, CrLf, "End scan", CrLf
End Function
