160713
- 3. ◯RasberryPi ・Python2
import smbus
from time import sleep
bus = smbus.SMBus(1)
SLAVE_ADDRESS = 0x21
f = open("i2c.txt","a")
i = 0
def writeCommand(cmd):
bus.write_byte(SLAVE_ADDRESS, cmd)
print("send: ",cmd)
def readValue():
val = bus.read_byte(SLAVE_ADDRESS)
return val
while i<40:
writeCommand(0);
i+=1
val = readValue()
print(i,"received",val)
s = str(val)
f.write(s)
f.write('n')
sleep(0.5)
print("exit")
f.write("exitn")
f.close()
● テキストファイル”i2c.txt”に測定結果が
書き込まれる
●
測定が40回繰り返されると自動的に
終了
- 8. ◯RasberryPi ・Python2
import smbus
from time import sleep
bus = smbus.SMBus(1)
i=0
SLAVE_ADDRESS = 0x21
def writeCommand(cmd):
bus.write_byte(SLAVE_ADDRESS, cmd)
print("send: ",cmd)
def readValue():
val = bus.read_byte(SLAVE_ADDRESS)
return val
while i<40:
i+=1
writeCommand(0)
val0 = readValue()
writeCommand(1)
val1 = readValue()
writeCommand(2)
val2 = readValue()
writeCommand(3)
val3 = readValue()
print("A0:"val0,"A1:"val1,"A2:"val2,"A3:"val3)
sleep(0.5)
print("exit")
- 9. ◯Aruduino IDE
#define out1 3
#define out2 4
int SLAVE_ADDRESS = 0x21;
int cmd = 1;
int val = 0;
void setup() {
pinMode(out1,OUTPUT);
pinMode(out2,OUTPUT);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveAnalogReading);
Wire.onRequest(sendData);
Serial.begin(9600);
Serial.println("Ready!!");
}
void preheat() {
for (int i = 0; i <= 3; i++){
delay(242);
digitalWrite(out2,HIGH);
delay(8);
digitalWrite(out2,LOW);
}
#include <Wire.h>
delay(237);
digitalWrite(out1,HIGH);
}
void afterheat(){
val = analogRead(0);
delay(2);
digitalWrite(out1,LOW);
digitalWrite(out2,HIGH);
delay(8);
digitalWrite(out2,LOW);
}
void loop(){
delay(1000);
}
void receiveAnalogReading(int byteCount){
while(Wire.available()){
cmd = Wire.read();
if(cmd == 0){
preheat();
val = analogRead(A0);
afterheat();
}
}
}
void sendData(){
val = 1023 - val;
val = val * 5;
Serial.print("send data: ");
Serial.println(val);
Wire.write(val);
}
- 10. ◯Aruduino IDE
#define out1 3
#define out2 4
int SLAVE_ADDRESS = 0x21;
int cmd = 1;
int val = 0;
void setup() {
pinMode(out1,OUTPUT);
pinMode(out2,OUTPUT);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveAnalogReading);
Wire.onRequest(sendData);
Serial.begin(9600);
Serial.println("Ready!!");
}
void preheat() {
for (int i = 0; i <= 3; i++){
delay(242);
digitalWrite(out2,HIGH);
delay(8);
digitalWrite(out2,LOW);
}
#include <Wire.h>
delay(237);
digitalWrite(out1,HIGH);
}
void receiveAnalogReading(int byteCount){
while(Wire.available()){
cmd = Wire.read();
Serial.print("data received: ");
Serial.println(cmd);
switch(cmd){
case 0:
preheat();
val = analogRead(A0);
afterheat();
break;
case 1:
preheat();
val = analogRead(A1);
afterheat();
break;
case 2:
preheat();
val = analogRead(A2);
afterheat();
break;
case 3:
preheat();
val = analogRead(A3);
afterheat();
break;
default:
Serial.print("errorn");
break;
}
}
}