//Particle Photon code
//the other side will be the reverse. i.e subscribe_channel = "diot2018/tictactoe/particle2" ;
const char *subscribe_channel = "diot2018/smiley/particle1" ;
const char *publish_channel = "diot2018/smiley/particle2" ;
const int FLEX_PIN = A0; // Pin connected to voltage divider output
// Measure the voltage at 5V and the actual resistance of your
// 47k resistor, and enter them below:
const float VCC = 4.98; // Measured voltage of Ardunio 5V line
const float R_DIV = 47500.0;
// Upload the code, then try to adjust these values to more
// accurately calculate bend degree.
const float STRAIGHT_RESISTANCE = 37300.0; // resistance when straight
const float BEND_RESISTANCE = 90000.0; // resistance at 90 deg
Servo myservo;// create servo object using the built-in Particle Servo Library
int button = D1; //declare variable for button
int servoPin = D0; //declare variable for servo
// Read the ADC, and calculate voltage and resistance from it
float getFlexAngle() {
int flexADC = analogRead(FLEX_PIN);
float flexV = flexADC * VCC / 1023.0;
float flexR = R_DIV * (VCC / flexV - 1.0);
Serial.println("Resistance: " + String(flexR) + " ohms");
// Use the calculated resistance to estimate the sensor's
// bend angle:
float angle = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE,
0, 90.0);
Serial.println("Bend: " + String(angle) + " degrees\n");
return angle ;
}
//drives the motor to correct angle
void setFlexAngle(float angle) {
Serial.print("Setting servo to " + String(angle) + "degrees\n") ;
myservo.attach(servoPin) ;
myservo.write(angle) ;
delay(200) ; //short delay to allow motor to move
mysevo.detach() ;
}
//publish to cloud
void publishAngle(float angle) {
s = String(angle) ;
Particle.publish(publish_channel, s) ;
return ;
}
void subscribeHandler(const char *event, const char *data) {
if(!data) {
return ; // nothing sent
}
float angle = String(data).toFloat() ;
setFlexAngle(angle) ;
return ;
}
void setup()
{
Serial.begin(9600);
//setup flex sensor
pinMode(FLEX_PIN, INPUT);
//setup servo
myservo.attach(servoPin); //Initialize the servo attached to pin D0
//quick servo test
myservo.write(90); //set servo to furthest position
delay(100); //delay to give the servo time to move to its position
myservo.write(0); //reset servo position
myservo.detach(); //detach the servo to prevent it from jittering
//subscripe to channel
Particle.subscribe(subscribe_channel, subscribeHandler) ;
}
void loop()
{
int delay_period = 1000 ; // set to desired amount to prevent too many messages sent
float curr_angle = getFlexAngle() ; //get angle of the flex sensor
publishAngle(curr_angle) ; //publish angle to other device
delay(delay_period);
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .