In the realm of Arduino Interface Buzzer, can bring your projects to life with sound. We’ll explore how to connect and control a buzzer, from simple beeps to complex melodies. Throughout this guide, we’ll cover wiring, coding, and examples, whether you’re new to Arduino or a seasoned maker. Let’s dive in and unlock the potential of Arduino buzzers together!
So, let’s embark on this sonic journey and unlock the potential of Arduino interfacing with buzzers!
This tutorial is “Arduino Interface UART(Serial)”. The Universal Asynchronous Receiver-Transmitter (UART) is a fundamental component in microcontroller communication, enabling data exchange between devices. In the realm of Arduino, mastering UART opens doors to interfacing with a plethora of sensors, actuators, and other devices.
In this guide, we’ll delve into the basics of UART communication with Arduino. Whether you’re a hobbyist embarking on your first Arduino project or an experienced developer seeking a refresher, this tutorial aims to demystify UART and equip you with the knowledge to integrate it seamlessly into your projects.
Let’s embark on this journey to unravel the intricacies of UART communication with Arduino, from understanding the principles behind UART to implementing it in your own circuits and code.
The Arduino microcontroller platform’s versatility in interfacing with various components has earned it renown, making it a go-to for electronics and DIY projects. This tutorial is about “Arduino Interface RGB LED”. One exciting application is controlling RGB (Red, Green, Blue) LEDs to create a spectrum of colors, perfect for beginners and enthusiasts alike.
This article is a continuation of the series on “Arduino Interface – LED” and carries the discussion on Turn ON/OFF, and blinking of LED in the Arduino Environment.
LED (light-emitting diode): LED is a simple diode that emits light in a forward bias
Arduino: is an open-source, board that has a Microchip ATmega328P microcontroller on it.
These are either normally on (Push-to-break0, or normally off(Push-to-make). They can be latched, So they stay pressed down after you remove your finger, like the switches on a torch.
The “Arduino Project Therimine” draws inspiration from the musical instrument known as the theremin. Utilizing Arduino microcontroller technology, this project aims to replicate the functionality of the theremin.
Participating in a C quiz can offer several benefits for individuals looking to improve their programming skills and knowledge of the C programming language. Here are some potential advantages:
Skill Enhancement: Quizzes often cover a range of topics within C programming, allowing participants to test and enhance their skills in areas such as syntax, data types, control structures, functions, and more.
Knowledge Validation: Quizzes can help individuals gauge their understanding of key concepts in C programming. By answering questions, participants can identify areas where they need to focus on improving their knowledge.
The ESP32 ArduinoCore Interface for OneWire (OW) communication protocol is a crucial aspect of interfacing with digital temperature sensors like the DS18B20. This interface allows the ESP32 microcontroller to communicate with one or more DS18B20 temperature sensors using the OneWire protocol.
Declares a function to print the temperature of a device with the given address.
void loop(void)
Begins the loop function, which runs continuously after setup.
sensors.requestTemperatures();
Requests temperature readings from all connected devices on the bus.
for(int i=0;i<numberOfDevices; i++)
Loops through each temperature device found on the bus.
printTemperature(tempDeviceAddress);
Prints the temperature of the i-th device.
void printAddress(DeviceAddress deviceAddress)
Declares a function to print the address of a device.
Functionality of
Initialization: The interface initializes the OneWire communication by defining the GPIO pin to which the OneWire data wire is connected. It also initializes the DallasTemperature library, which simplifies communication with DS18B20 sensors.
Device Detection: Upon initialization, the interface detects the number of DS18B20 sensors connected to the OneWire bus. It retrieves the unique address of each sensor and sets their resolution if detected.
Temperature Reading: The interface periodically requests temperature readings from all connected DS18B20 sensors. It then retrieves the temperature data and converts it to Celsius and Fahrenheit scales for further processing or display.
The “ESP32 ArduinoCore Interface – ADC” provides a seamless integration between the ESP32 microcontroller and the Arduino development environment, specifically focusing on the Analog-to-Digital Converter (ADC) functionality.
Analog-to-Digital Converter – A device or circuit that converts analog signals to digital data.
Functionality
Converts continuous analog signals into discrete digital values.
Process
Samples the analog input signal at regular intervals and quantizes the sampled values into digital values.
Applications
Used in microcontrollers, data acquisition systems, sensors, audio equipment, communication devices, and more.
Resolution
The number of digital bits used to represent the analog signal. Higher resolution ADCs provide more precise representations.
Sampling Rate
Determines how frequently the ADC samples the analog input signal. Higher sampling rates enable more accurate representation of fast-changing signals.
Types
Successive approximation, delta-sigma, pipeline, and flash ADCs are common types, each with specific advantages and applications.
Interface
Interfaces with digital systems such as microcontrollers or computers, where the digital output values can be processed or stored.
ADC Pins
Pin
ADC Channel
GPIO Number
GPIO32
ADC1_CH4
32
GPIO33
ADC1_CH5
33
GPIO34
ADC1_CH6
34
GPIO35
ADC1_CH7
35
GPIO36
ADC1_CH0
36
GPIO37
ADC1_CH1
37
GPIO25
ADC2_CH8
25
GPIO26
ADC2_CH9
26
This table lists the ADC pins available on the ESP32 microcontroller along with their corresponding ADC channels and GPIO numbers.
Code
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the serial monitor.
Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
Code Explanation of ESP32 ArduinoCore Interface ADC
Code Purpose: Reading an analog input from pin A0 and printing the value to the serial monitor.
Setup Routine: This part of the code initializes serial communication at a baud rate of 9600 bits per second.
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
Loop Routine:
This section continuously reads the analog value from pin A0 using the analogRead() function.
It then prints the value to the serial monitor using Serial.println().
A small delay of 1 millisecond is added between reads for stability using delay().
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
Overall Functionality: This code can be useful for testing analog sensors or for basic data-logging applications.
Advantage of ESP32 ArduinoCore Interface ADC
Advantage
Description
Analog Signal Processing
ADCs enable microcontrollers to process analog signals from the physical world, converting them into digital values that can be processed by digital systems.
Sensor Interfacing
ADCs facilitate interfacing with various sensors that produce analog output, such as temperature sensors, light sensors, and pressure sensors, allowing accurate measurement and response to real-world phenomena.
Signal Conditioning
ADCs can be used for signal conditioning tasks, including amplification, filtering, and noise reduction, before converting analog signals to digital form, improving accuracy and reliability of measured data.
Data Acquisition
ADCs enable microcontrollers to acquire data from analog sources at high speeds and with high precision, suitable for applications such as data logging, instrumentation, and control systems.
Versatility
ADCs come in various resolutions, sampling rates, and input voltage ranges, allowing developers to choose the most suitable ADC for their specific application requirements.
Integration
Many microcontrollers, including the ESP32, feature built-in ADCs, eliminating the need for external ADC components and reducing system complexity and cost.
ESP8266 is popular Wi-Fi chip and Internet of things is one of the fastest growing technologies. So we thought to conduct a technical workshop about IOT using ESP8266. You’ll learn the basic concepts and features of the Internet of Things and will be able to build projects using the ESP8266 NodeMCU platform. You’ll also discover fundamental concepts of cloud computing, sensor reading, connecting the ESP8266 to the Internet, wireless interfaces and controlling devices with Android phones. You’ll also learn to use the most popular open platforms for managing sensor data from the ESP8266, how to trigger actuators remotely, and how to read information on your Android Smart Phones. if you attend this workshop you will able to do IOT projects by you-self also you can help others to lean about IOT. Interested, can join this workshop. The duration is seven hours in a day and details are mentioned below and refer the image also.
Some More Experiments : PWM, WiFi, TCP, UDP, SNPT, RTC, MQTT.
Session-2 (Afternoon)
Real time Project 1 : Smart Device Control with monitor (Home Automation devices-Online/Offline).
Real Time Project 2 : Smart RGB Light (Online/Offline).
Project 3 : Network Status Indicator.
Project 4 : Data Logger.
Goal
Workshop is to make the students skill full and efficient for Internet of things related concepts.
The students to do their final year projects by them-self.
Apply Internet of things application in your day-to-day.
Participation Prerequisites
To participate in the workshop, you will need the following:
A laptop – Windows(Latest) and at least one free USB port with internet connection.
A micro-USB cable with data lines that fits your USB port.
A Mobile with WiFi, Host-spot feature and internet connection.
A breadboard and arduino board with cable.(Optional)
You will need a install this software( I will give at workshop)
Java
Windows Offline (32-Bit)
Windows Offline (64-bit)
Keep on this below software’s
ESPlorer
Notepad++. : Windows Offline (32-Bit)
Please note that the workshop will be in mostly English (Local Language-Prefers).
Participation will receive in additional, at the workshop!
Wi-Fi development board,
LED,
RGB LED,
Female-female connector cables,
Piezoelectric speaker,
Magnetic Reed Switch
Magnet
Certificate will provide end of the workshop to each participate,
End of the session we will provide all kind of workshop materials like PPT, documents, videos and source code.
Venue
Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.
Registration
Note : Once you registered, you will get a conformation message to registered mobile and e-mail.
This event was held. you can’t register. contact Mr.Arun.
Payment Method
Note : You can pay the workshop fee by two ways – Online/Offline. One we received your payment you will get a message to your registered mobile and e-mail.
Online : Pay using Paytm
Pay workshop fee (money) scan QR code image
In Optional description write “ArunEworld_Workshop_20170821” ,space. “You_Name”“ArunEworld_Workshop_20170821″<space>”You_Name” (Ex : ArunEworld_Workshop_20170821 Raja)
Offline : Pay to Workshop organizer
Contact: Mr.Giri.K , Assistant Professor, Mahendra College of Engineering,
Contact Number : +919003503908.
Attendees List
Once you complete registration successfully, then your name will be listed below automatically.
Contact Organizer
Mr. Giri. K (girik@mahendra.info, +919003503908)
Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.
Workshop full details and resource
Click this below link to see the syllabus, contents, videos and more, etc..
The ESP8266 NodeMCU is a popular development board based on the ESP8266 microcontroller, which offers built-in Wi-Fi capabilities, making it ideal for Internet of Things (IoT) projects. In this project, we’ll explore how to interface the ESP8266 NodeMCU with the ADXL345 accelerometer sensor.
The ADXL345 is a small, thin, ultralow power, 3-axis accelerometer with high resolution (13-bit) measurement at up to ±16 g. It’s suitable for various applications, including tilt sensing, motion detection, and vibration monitoring.
By combining the ESP8266 NodeMCU with the ADXL345 sensor, we can create IoT applications that can monitor and analyze motion or vibrations remotely over Wi-Fi. This interface allows us to gather data from the accelerometer sensor and transmit it to a server, cloud platform, or display it on a web page.
Throughout this project, we’ll cover the hardware setup, including connecting the ADXL345 sensor to the ESP8266 NodeMCU, and the software implementation, which involves programming the ESP8266 NodeMCU to communicate with the ADXL345 sensor and transmit the data. With this interface, you’ll be able to leverage the power of the ESP8266 NodeMCU and the capabilities of the ADXL345 sensor to create versatile IoT applications for motion sensing and monitoring.
Code
Make sure you have the necessary libraries and setup to run this code on your hardware.
-- www.ArunEworld.com
sda = 2 -- GPIO-4
scl = 1 -- GPIO-5
print("ArunEworld")
-- Initialize the ADXL345 sensor
adxl345.init(sda, scl)
-- Delay for 3000000 microseconds (3 seconds)
tmr.delay(3000000)
-- Read data from the ADXL345 sensor
print(adxl345.read())
-- Define a function to read accelerometer data
function ADXL_read()
-- Read accelerometer data
local x, y, z = adxl345.read()
-- Print accelerometer data
print("X-axis:", x)
print("Y-axis:", y)
print("Z-axis:", z)
-- Alternatively, you can print all axes at once using the following line:
-- print(string.format("X = %d, Y = %d, Z = %d", x, y, z))
end
-- Set up a timer to call the ADXL_read function every 1000 milliseconds (1 second)
tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)
Code Explanation
Line
Code
Explanation
1
sda = 2
Assigns pin 2 to the variable sda, representing the Serial Data (SDA) pin.
2
scl = 1
Assigns pin 1 to the variable scl, representing the Serial Clock (SCL) pin.
4
print("ArunEworld")
Prints the message “ArunEworld” to the console.
7
adxl345.init(sda, scl)
Initializes the ADXL345 sensor with the SDA and SCL pins defined earlier.
10
tmr.delay(3000000)
Delays the execution of the program for 3 seconds (3000000 microseconds).
13
print(adxl345.read())
Reads data from the ADXL345 sensor and prints it to the console.
16
function ADXL_read() ... end
Defines a function named ADXL_read to read accelerometer data from the ADXL345 sensor.
19
tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)
Sets up a timer to call the ADXL_read function every 1000 milliseconds (1 second) repeatedly.
The “ESP8266 NodeMCU Module NET” introduces a comprehensive set of functionalities for network communication on the ESP8266 platform using the NodeMCU firmware. This module empowers developers to create versatile IoT applications by enabling connections over Wi-Fi, TCP/IP, and UDP protocols.
With the NET module, developers can perform various networking tasks such as creating clients and servers, establishing UDP sockets, managing multicast groups, and interacting with DNS servers. This module provides a wide range of functions for initiating, managing, and terminating network connections, as well as for resolving hostnames and configuring DNS servers.
Whether it’s setting up a web server, connecting to cloud services, or implementing peer-to-peer communication, the ESP8266 NodeMCU Module NET offers the necessary tools and capabilities to facilitate seamless networking operations. It serves as a foundational component for building connected devices and IoT solutions powered by the ESP8266 platform.
Throttle data reception by placing a request to block the TCP receive function.
net.socket:on()
Register callback functions for specific events.
net.socket:send()
Sends data to remote peer.
net.socket:ttl()
Changes or retrieves Time-To-Live value on socket.
net.socket:unhold()
Unblock TCP receiving data by revocation of a preceding hold().
net.udpsocket:close()
Closes UDP socket.
net.udpsocket:listen()
Listen on port from IP address.
net.udpsocket:on()
Register callback functions for specific events.
net.udpsocket:send()
Sends data to specific remote peer.
net.udpsocket:dns()
Provides DNS resolution for a hostname.
net.udpsocket:getaddr()
Retrieve local port and IP of socket.
net.udpsocket:ttl()
Changes or retrieves Time-To-Live value on socket.
net.dns.getdnsserver()
Gets the IP address of the DNS server used to resolve hostnames.
net.dns.resolve()
Resolve a hostname to an IP address.
net.dns.setdnsserver()
Sets the IP of the DNS server used to resolve hostnames.
Example :1 TCP Connection in local
The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends a message to the server. It also includes event handlers to handle Wi-Fi connection events.
Create a TCP connection and communicate with TCP server
Certainly! Here’s an explanation of the provided Lua code:
Print Statement:
print("ArunEworld : TCP Example")
This line prints out the string "ArunEworld : TCP Example". It serves as an informational message indicating the purpose of the code.
Wi-Fi Configuration:
wifi.setmode(wifi.STATIONAP)
This line sets the Wi-Fi mode to STATIONAP, allowing the device to connect to an existing Wi-Fi network as a station while also creating an access point.
This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which prints out the connection payload.
This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.
Sending Data:
TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")
This line sends a message to the TCP server after the connection is established.
Wi-Fi Event Monitoring:
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
-- Event handler for when the Wi-Fi station is connected
-- Print out details about the connection
end)
-- Similar event handlers are registered for other Wi-Fi events like disconnection and obtaining an IP address.
Example :1 TCP Connection to httpbin.org site (Onlin)
print("ww.ArunEworld.com")
print("wifi init")
--wifi.start() -- commented out
wifi.setmode(wifi.STATIONAP) -- connect to Access Point (DO NOT save config to flash)
station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c)
print(c)
end)
-- Wait for connection before sending.
srv:on("connection", function(sck, c)
-- 'Connection: close' rather than 'Connection: keep-alive' to have server
-- initiate a close of the connection after final response (frees memory
-- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6
sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)
srv:connect(80, 'httpbin.org')
Explanation
The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends an HTTP GET request to retrieve data from httpbin.org. Any received data is printed to the console.
Print Statements:
print("ww.ArunEworld.com")
print("wifi init")
These lines print out the strings "ww.ArunEworld.com" and "wifi init". They are for informational purposes and help indicate the progress of the program.
Wi-Fi Configuration:
wifi.setmode(wifi.STATIONAP)
This line sets the Wi-Fi mode to STATIONAP, which allows the device to connect to an existing Wi-Fi network as a station while also creating an access point.
These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.
TCP Connection Setup:
srv = net.createConnection(net.TCP, 0)
This line creates a TCP connection object named srv.
srv:on("receive", function(sck, c)
print(c)
end)
This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.
srv:on("connection", function(sck, c)
sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)
This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which sends an HTTP GET request to httpbin.org. The request includes the path /get and necessary headers.
Connect to Server:
srv:connect(80, 'httpbin.org')
This line initiates the connection to the server at httpbin.org on port 80 (the standard HTTP port).
In Lua on the ESP8266 NodeMCU module, you can use the tmr module to work with a timer. Here’s a basic guide on using the ESP8266 NodeMCU Module – Timer. The tmr Module provides 7 (0-6) static timer functions of the timer module. we can’t use more than 7. Also, you can create an object-based timer function with a custom name.
we can use this timer function in the following applications
To blink an LED for a certain time duration its like a repeated process.
mqtt.client:close() – Closes connection to the broker.
mqtt.client:connect() – Connects to the broker specified by the given host, port, and secure options.
mqtt.client:lwt( ) – Setup Last Will and Testament (optional).
mqtt.client:on() – Registers a callback function for an event.
mqtt.client:publish() – Publishes a message.
mqtt.client:subscribe() – Subscribes to one or several topics.
mqtt.client:unsubscribe() – Unsubscribes from one or several topics.
MQTT Example
MQTT subscribe and publish the data to
-- Required Modules :Mqtt,Wifi
-- https://www.aruneworld.com/
-- Tested By : Arun(20170527)
-- Example Name : AEW_Mqtt.lua
---------------------------------------------------------------------------------
station_cfg={}
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "ArunEworld.com" --please change your SSID and Passworld
print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()
--Initializing Mqtt
DEVICE_NAME = "ArunEworld-"..node.chipid()
PUBLISH_TOPIC = "ArunEworld/"..DEVICE_NAME.."-Result"
SUBSCRIBE_TOPIC = "ArunEworld/"..DEVICE_NAME
CLIENT_ID = DEVICE_NAME
USERNAME = "username" -- please change your username
PASSWORD = "Password" -- please change your Password
HOSTNAME = "mqtt.aruneworld.com" -- Please change your port
PORT = "Port_Number" -- Please change your port number
-- Mqtt Setup
m = mqtt.Client(CLIENT_ID, 120, USERNAME, PASSWORD, 0)
m:connect(HOSTNAME, PORT, 0, function(conn)
m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Online", 1, 0, function(conn) end)
m:subscribe(SUBSCRIBE_TOPIC, 1, function(conn) end)
end)
--Mqtt Receive function
m:on("message", function(client, topic, payload)
if payload ~= nil then
print(payload)
else
print("Mqtt Reccived nill payload message")
end
collectgarbage("collect")
end)
--Mqtt Send function
local function Send_MQTT(strings)
m:publish(PUBLISH_TOPIC,strings, 1, 0, function(conn) end)
end
--Wifi Event Monitoring
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\tChannel: "..T.channel)
end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\treason: "..T.reason)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
end)
Read and Write files using MQTT
transfer files over mqtt
-- For More info :- https://www.aruneworld.com/
-- Tested By : Arun(20170527)
-- Required Modules : CJSON, FILE, MQTT, WiFi,
station_cfg={}
DEVICE_NAME = node.chipid()
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "Arun"
PUBLISH_TOPIC = "MQTT_File_Ex_PUB"
SUBSCRIBE_TOPIC = "MQTT_File_Ex_SUB"
CLIENT_ID = DEVICE_NAME
USERNAME = ""
PASSWORD = ""
HOSTNAME = "iot.eclipse.org"
PORT = 1883
print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()
-- test transfer files over mqtt.
m_dis={} --Created the table and name is m_dis
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](m,pl)
end
end
function pubfile(m,filename)
file.close()
file.open(filename)
repeat
local pl=file.read(1024)
if pl then m:publish("/topic2",pl,0,0) end
until not pl
file.close()
end
-- payload(json): {"cmd":xxx,"content":xxx}
function topic1func(m,pl)
print("get1: "..pl)
local pack = cjson.decode(pl)
if pack.content then
if pack.cmd == "open" then file.open(pack.content,"w+")
elseif pack.cmd == "write" then file.write(pack.content)
elseif pack.cmd == "close" then file.close()
elseif pack.cmd == "remove" then file.remove(pack.content)
elseif pack.cmd == "run" then dofile(pack.content)
elseif pack.cmd == "read" then pubfile(m, pack.content)
end
end
end
m_dis["/topic1"]=topic1func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
--m=mqtt.Client()
m = mqtt.Client(CLIENT_ID, 20, USERNAME, PASSWORD, 0)
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Live", 1, 0, function(m) print("[LOG]:- Mqtt "..DEVICE_NAME.." is Live in Online Mode") end)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
--m:connect(192.168.18.88,1883,0,1)
--host = "iot.eclipse.org"
m:connect(HOSTNAME,1883,0,1)
-- usage:
-- another client(pc) subscribe to /topic2, will receive the test.lua content.
-- and publish below message to /topic1
-- {"cmd":"open","content":"test.lua"}
-- {"cmd":"write","content":"print([[hello world]])\n"}
-- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
-- {"cmd":"write","content":"test.lua"}
-- {"cmd":"run","content":"test.lua"}
-- {"cmd":"read","content":"test.lua"}
MQTT to cloud
-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](m,pl)
end
end
function topic1func(m,pl)
print("get1: "..pl)
end
function topic2func(m,pl)
print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:subscribe("/topic2",0,function(m) print("sub done") end)
m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time()
m:publish("/topic1",pl,0,0)
end)
You must be logged in to post a comment.