Created
February 2, 2017 15:47
-
-
Save ligun/b255798dabc835849268a069bf2ecff1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Raspberry Pi + Groovy + Pi4JでAM2320温湿度センサーを使うサンプル | |
pi4j参考:https://github.com/Pi4J/pi4j/blob/master/pi4j-example/src/main/java/I2CExample.java | |
AM2320参考:http://wizqro.net/%E6%B8%A9%E6%B9%BF%E5%BA%A6%E3%82%BB%E3%83%B3%E3%82%B5am2320%E3%82%92raspberry-pi-3%E3%81%A7%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B/ | |
*/ | |
@Grab("com.pi4j:pi4j-core") | |
import com.pi4j.io.i2c.I2CBus | |
import com.pi4j.io.i2c.I2CDevice | |
import com.pi4j.io.i2c.I2CFactory; | |
/* AM2320のI2Cアドレス */ | |
final int AM2320_ADDR = 0x5C | |
/* Pi4JのI2Cデバイス */ | |
def am2320 | |
try { | |
am2320 = I2CFactory.getInstance(I2CBus.BUS_1).getDevice(AM2320_ADDR) | |
}catch(Exception e) { | |
System.exit 1 | |
} | |
while(true) { | |
byte[] buffer = new byte[6] //受信バッファ | |
/* sleep解除 */ | |
try{am2320.write 0x00}catch(Exception e){} | |
/* 読み取り */ | |
Thread.sleep 1 //sleep解除の後は最低30us待つ | |
am2320.write([(byte)0x03,(byte)0x00,(byte)0x04] as byte[]) //データ要求(機能コードRead[0x03]で0番地から4バイト) | |
Thread.sleep 2 //受信要求の後は最低1.5ms待つ | |
am2320.read(buffer, 0, 6) | |
/* 表示 */ | |
def hum = ((buffer[2]&0xff) << 8 | (buffer[3]&0xff))/10.0 //2,3バイト目は湿度データ | |
def tmp = ((buffer[4]&0xff) << 8 | (buffer[5]&0xff))/10.0 //4,5バイト目は温度データ | |
println "${new Date().format("HH:mm:ss")} 温度:${tmp}度 湿度:${hum}%" | |
Thread.sleep 1000 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment