Monday, April 16, 2018

I2C Scanner

[pastacode lang="c" manual="%2F%2F%20--------------------------------------%0A%2F%2F%20i2c_scanner%0A%2F%2F%0A%2F%2F%20Version%201%0A%2F%2F%20This%20program%20(or%20code%20that%20looks%20like%20it)%0A%2F%2F%20can%20be%20found%20in%20many%20places.%0A%2F%2F%20For%20example%20on%20the%20Arduino.cc%20forum.%0A%2F%2F%20The%20original%20author%20is%20not%20know.%0A%2F%2F%20Version%202%2C%20Juni%202012%2C%20Using%20Arduino%201.0.1%0A%2F%2F%20Adapted%20to%20be%20as%20simple%20as%20possible%20by%20Arduino.cc%20user%20Krodal%0A%2F%2F%20Version%203%2C%20Feb%2026%202013%0A%2F%2F%20V3%20by%20louarnold%0A%2F%2F%20Version%204%2C%20March%203%2C%202013%2C%20Using%20Arduino%201.0.3%0A%2F%2F%20by%20Arduino.cc%20user%20Krodal.%0A%2F%2F%20Changes%20by%20louarnold%20removed.%0A%2F%2F%20Scanning%20addresses%20changed%20from%200...127%20to%201...119%2C%0A%2F%2F%20according%20to%20the%20i2c%20scanner%20by%20Nick%20Gammon%0A%2F%2F%20http%3A%2F%2Fwww.gammon.com.au%2Fforum%2F%3Fid%3D10896%0A%2F%2F%20Version%205%2C%20March%2028%2C%202013%0A%2F%2F%20As%20version%204%2C%20but%20address%20scans%20now%20to%20127.%0A%2F%2F%20A%20sensor%20seems%20to%20use%20address%20120.%0A%2F%2F%20Version%206%2C%20November%2027%2C%202015.%0A%2F%2F%20Added%20waiting%20for%20the%20Leonardo%20serial%20communication.%0A%2F%2F%0A%2F%2F%0A%2F%2F%20This%20sketch%20tests%20the%20standard%207-bit%20addresses%0A%2F%2F%20Devices%20with%20higher%20bit%20address%20might%20not%20be%20seen%20properly.%0A%2F%2F%0A%0A%23include%20%3CWire.h%3E%0A%0Avoid%20setup()%0A%7B%0AWire.begin()%3B%0A%0ASerial.begin(9600)%3B%0Awhile%20(!Serial)%3B%20%2F%2F%20Leonardo%3A%20wait%20for%20serial%20monitor%0ASerial.println(%22%5CnI2C%20Scanner%22)%3B%0A%7D%0A%0Avoid%20loop()%0A%7B%0Abyte%20error%2C%20address%3B%0Aint%20nDevices%3B%0A%0ASerial.println(%22Scanning...%22)%3B%0A%0AnDevices%20%3D%200%3B%0Afor(address%20%3D%201%3B%20address%20%3C%20127%3B%20address%2B%2B%20)%0A%7B%0A%2F%2F%20The%20i2c_scanner%20uses%20the%20return%20value%20of%0A%2F%2F%20the%20Write.endTransmisstion%20to%20see%20if%0A%2F%2F%20a%20device%20did%20acknowledge%20to%20the%20address.%0AWire.beginTransmission(address)%3B%0Aerror%20%3D%20Wire.endTransmission()%3B%0A%0Aif%20(error%20%3D%3D%200)%0A%7B%0ASerial.print(%22I2C%20device%20found%20at%20address%200x%22)%3B%0Aif%20(address%3C16)%0ASerial.print(%220%22)%3B%0ASerial.print(address%2CHEX)%3B%0ASerial.println(%22%20!%22)%3B%0A%0AnDevices%2B%2B%3B%0A%7D%0Aelse%20if%20(error%3D%3D4)%0A%7B%0ASerial.print(%22Unknown%20error%20at%20address%200x%22)%3B%0Aif%20(address%3C16)%0ASerial.print(%220%22)%3B%0ASerial.println(address%2CHEX)%3B%0A%7D%0A%7D%0Aif%20(nDevices%20%3D%3D%200)%0ASerial.println(%22No%20I2C%20devices%20found%5Cn%22)%3B%0Aelse%0ASerial.println(%22done%5Cn%22)%3B%0A%0Adelay(5000)%3B%20%2F%2F%20wait%205%20seconds%20for%20next%20scan%0A%7D" message="" highlight="" provider="manual"/]

No comments: