Coding it all together

In a file in the same folder, create mqtt-button-lcd.js. Put in the usual Johnny-Five and Raspi-IO constructors, and in the board-ready handler:

Then, add the client constructor for AdafruitIO's MQTT connection from mqtt-test.js. We'll also set up our LCD and button objects here:

let LCD = new five.LCD({
controller: "PCF8574",
rows: 2,
cols: 16
})
let button = new five.Button('P1-29')

After that, we're ready to code the sending of messages on the press of the button, and the printing of messages received on the LCD:

client.on('connect', () => {
console.log('Connected to AdafruitIO')
client.subscribe(process.env.ADAFRUIT_IO_FEED, () => {
client.publish(process.env.ADAFRUIT_IO_FEED, 'Hello from the Pi!')

button.on('press', () => {
client.publish(process.env.ADAFRUIT_IO_FEED, 'Button pressed!')
})

client.on('message', (topic, message) => {
LCD.clear().home().print(topic).setCursor(1,0).print(message)
})
})
})

Now, move the folder over to the Pi, go into your Pi session, navigate to the folder, run the following command: 

npm i --save johnny-five raspi-io

Then, run the program (be sure to use sudo !)

sudo node mqtt-lcd-button.js

Now, press the button and you should see the message pop up in the AdafruitIO feed dashboard:

And your LCD (remember, MQTT events are published to all, even the client that published them, if they are subscribed!):

While we're there, click Actions, then Add Data, and type Hello from Adafruit! in the data box, and hit Create. It should show up on your LCD:

And there you have it! You now have a bot that communicates with the internet via MQTT!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.166.98