9: Spark Core/Imitation Arduino
I've managed to build a sketch for the Core that lights an LED, switches relays, reads a photo sensor and reads temperature from a TMP36. These activities are controlled from a Raspberry Pi and the results are posted on the Web. Here's a messy pic of the Spark setup powered by a battery.
(the cludged-up 9V flashlight (lower-left) is to prove the switch is working)
Here's the sketch:
int led = D0;
int relay1 = D7;
int relay2 = D6;
int photo = A0;
int tmp36 = A1;
int rval;
int r1state = 0;
int r2state = 0;
void setup()
{
Spark.function("spark", getSpark);
pinMode(led,OUTPUT);
pinMode(photo, INPUT);
pinMode(relay1, OUTPUT);
digitalWrite(relay1, HIGH); // backwards for "normally closed" relay
pinMode(relay2, OUTPUT);
digitalWrite(relay2, HIGH);
pinMode(tmp36pin, INPUT);
}
void loop() {
// not used
}
int getSpark(String command)
{
int raw, f;
float v, c;
int cmd = command.toInt();
blink(cmd); // for my visible feedback
switch(cmd) {
case 1: // return photo sensor analog reading
rval = analogRead(photo);
return rval;
case 2: // switch relay 1
if(r1state == 0) {
digitalWrite(relay1, LOW);
r1state = 1;
} else {
digitalWrite(relay1, HIGH);
r1state = 0;
}
return r1state;
case 3: // switch relay 2
if(r2state == 0) {
digitalWrite(relay2, LOW);
r2state = 1;
} else {
digitalWrite(relay2, HIGH);
r2state = 0;
}
return r2state;
case 4: // return TMP36 temperature in F
raw = analogRead(tmp36);
v = (raw * 3.3) / 4095;
c = (v - 0.5) *100;
f = (c * 9.0/5.0 + 32.0);
return f;
default:
break;
}
return cmd;
}
void blink(int n)
{
int i;
for(i = 0; i < n; ++i) {
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
}
No comments:
Post a Comment