Skip to content

Instantly share code, notes, and snippets.

@Hypnopompia
Created May 29, 2018 21:45
Show Gist options
  • Save Hypnopompia/406302917b78f6e553586311155f0a33 to your computer and use it in GitHub Desktop.
Save Hypnopompia/406302917b78f6e553586311155f0a33 to your computer and use it in GitHub Desktop.
Particle Photon pressure transducer firmware
// On the photon, analog reading values are: 0 = 0.0V and 4095 = 3.3V.
// Do NOT put more than 3.3V into an analog input pin on a photon or you'll damage the photon.
// Since the pressure tranducer can output more than 3.3V (up to 4.5V), we'll need to create a voltage divider to protect the photon:
// https://learn.sparkfun.com/tutorials/voltage-dividers/all
const float PHOTON_VOLTAGE_COEFFICIENT = 3.3 / 4096;
const float SENSOR_MIN_V = 0.5;
const float SENSOR_MAX_V = 4.5;
const float SENSOR_MIN_PSI = 0.0;
const float SENSOR_MAX_PSI = 150.0;
const int READ_DELAY_MS = 100; // Do a reading and print to the serial port every 100 ms
const int PUBLISH_DELAY_MS = 5000; // Publish the PSI every 5 seconds
int analogvalue = 0;
float voltage = 0;
float pressure = 0;
unsigned long lastReadTime = 0; // Keep track of the last time we did a reading
unsigned long lastPublishTime = 0; // Keep track of the last time we published the PSI
void setup() {
Serial.begin();
}
void loop() {
unsigned long time = millis();
if (time < lastReadTime) { // handle millis() rollover (every 49 days)
lastReadTime = 0;
lastPublishTime = 0;
}
if (time > (lastReadTime + READ_DELAY_MS)) {
lastReadTime = time;
analogvalue = analogRead(A0);
voltage = PHOTON_VOLTAGE_COEFFICIENT * analogvalue;
// voltage = map(voltage, 0.0, 3.3, 0.0, 5.0); // Uncomment this when we have a voltage divider
// Values without a voltage divider:
// 0.0V = 0 (MIN)
// 0 PSI = 0.5V = 620
// 105 PSI = 3.3V = 4095 (MAX)
// 150 PSI = 4.5V = 5585* DANGER!
// Calculating PSI from the analog reading:
// pressure = (analogvalue - 620) * SENSOR_MAX_PSI / ( 5585 - 620 ); // Not compatible with voltage divider
// Calculating the PSI from the voltage:
// pressure = (voltage - SENSOR_MIN_V) * SENSOR_MAX_PSI / (SENSOR_MAX_V - SENSOR_MIN_V);
pressure = map(voltage, SENSOR_MIN_V, SENSOR_MAX_V, SENSOR_MIN_PSI, SENSOR_MAX_PSI);
pressure = constrain(pressure, SENSOR_MIN_PSI, SENSOR_MAX_PSI);
Serial.print(" Value: ");
Serial.println(analogvalue);
Serial.print(" Voltage: ");
Serial.print(voltage);
Serial.println(" Volts");
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println(" PSI");
Serial.print("\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (time > (lastPublishTime + PUBLISH_DELAY_MS)) {
lastPublishTime = time;
Particle.publish("psi", String(pressure), PRIVATE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment