/* * Pot and LED for MQTT * * The Arduino reads an input (in the form of a potentiometer) * and writes an output (in the form of an LED). * * The potentiometer's value is mapped to a 0-99 range, saved * into "outVal," and printed to the serial port every half second. * * Incoming serial data is saved into "inVal," assumed to be in * the 0-99 range, and used to drive the LED's brightness. * * This is a sample sketch meant to be used with the qt_arduino_mqtt_bridge * program, available at: * https://courses.ideate.cmu.edu/16-223/f2020/text/code/Arduino-MQTT-Bridge.html * * Robert Zacharias, rzachari@andrew.cmu.edu, Sept. 2020 * Released to the public domain by the author */ const int POTPIN = A0; const int LEDPIN = 5; const unsigned long WAIT = 500; unsigned long timer; int inVal, outVal; void setup(){ pinMode(POTPIN, INPUT); pinMode(LEDPIN, OUTPUT); Serial.begin(115200); // qt_arduino_mqtt_bridge uses this rate Serial.setTimeout(50); // wait ≤ 50 milliseconds to parse incoming data } void loop(){ int LEDbrightness = map(inVal, 0, 99, 0, 255); analogWrite(LEDPIN, LEDbrightness); if (millis() - timer > WAIT){ int potRead = analogRead(POTPIN); outVal = map(potRead, 0, 1023, 0, 99); transmitSerialSignal(); timer = millis(); } } void serialEvent(){ /* You do *not* need to call this function in your loop; it is a special function that will run whenever serial data flows into the Arduino. */ /* The function assumes your machine's input value is called "inVal" (change that variable name as needed) */ // if there is incoming serial data, read it while (Serial.available() > 0){ // interpret incoming digits as integer and save into inVal inVal = Serial.parseInt(); } } void transmitSerialSignal(){ /* You should call this function 2-4 times/second in your main loop to transmit information to the next Arduino in the transmission chain. */ /* Assumes your machine's outgoing value is called outVal (change that variable name as needed) */ Serial.println(outVal); }