1+ using System ;
2+ using System . Device . I2c ;
3+ using System . Threading ;
4+
5+ class Program
6+ {
7+ // I2C address (default for IS31FL3731/IS31FL3741, check your board)
8+ const int I2cAddress = 0x74 ;
9+ // Register addresses
10+ const byte PageSelect = 0xFD ; // Function register page select
11+ const byte ConfigReg = 0x00 ; // Configuration register
12+ const byte LedControlBase = 0x00 ; // LED control base (Page 0)
13+
14+ // Matrix dimensions
15+ const int Width = 13 ; // Columns
16+ const int Height = 9 ; // Rows
17+
18+ static void Main ( )
19+ {
20+ // Open I2C bus 1 (Raspberry Pi default)
21+ I2cConnectionSettings settings = new ( 1 , I2cAddress ) ;
22+ using I2cDevice device = I2cDevice . Create ( settings ) ;
23+
24+ // Initialize the chip
25+ Initialize ( device ) ;
26+
27+ // Turn on some LEDs (e.g., at (0,0), (6,4), (12,8))
28+ SetLedState ( device , 0 , 0 , true ) ; // Top-left
29+ SetLedState ( device , 6 , 4 , true ) ; // Middle-ish
30+ SetLedState ( device , 12 , 8 , true ) ; // Bottom-right
31+
32+ Console . WriteLine ( "LEDs on! Press Ctrl+C to exit." ) ;
33+ Thread . Sleep ( Timeout . Infinite ) ;
34+ }
35+
36+ static void Initialize ( I2cDevice device )
37+ {
38+ // Select Function Register page
39+ device . Write ( new byte [ ] { PageSelect , 0x0B } ) ;
40+ // Set to normal operation (disable shutdown)
41+ device . Write ( new byte [ ] { ConfigReg , 0x01 } ) ;
42+
43+ // Select LED Control page (Page 0)
44+ device . Write ( new byte [ ] { PageSelect , 0x00 } ) ;
45+ // Enable LEDs for 13x9 matrix (117 LEDs, 15 bytes needed)
46+ for ( byte i = 0 ; i < 15 ; i ++ ) // 117 bits = 14.625 bytes, round up to 15
47+ {
48+ device . Write ( new byte [ ] { ( byte ) ( LedControlBase + i ) , 0xFF } ) ;
49+ }
50+ }
51+
52+ static void SetLedState ( I2cDevice device , int x , int y , bool state )
53+ {
54+ if ( x < 0 || x >= Width || y < 0 || y >= Height )
55+ {
56+ Console . WriteLine ( $ "Invalid coordinates: ({ x } , { y } )") ;
57+ return ;
58+ }
59+
60+ // Map 13x9 coordinates to LED register
61+ int ledIndex = x + ( y * Width ) ; // Linear index for 13x9
62+ byte register = ( byte ) ( LedControlBase + ( ledIndex / 8 ) ) ;
63+ byte bit = ( byte ) ( ledIndex % 8 ) ;
64+ byte mask = ( byte ) ( 1 << bit ) ;
65+
66+ // Read current state, modify, write back
67+ byte [ ] readBuffer = new byte [ 1 ] ;
68+ device . WriteRead ( new byte [ ] { register } , readBuffer ) ;
69+ byte current = readBuffer [ 0 ] ;
70+ byte newValue = state ? ( byte ) ( current | mask ) : ( byte ) ( current & ~ mask ) ;
71+ device . Write ( new byte [ ] { register , newValue } ) ;
72+ }
73+ }
0 commit comments