Arduino's case of realizing digital thermometer through RXTX Unicom JAVA

Relevant projects have been uploaded to the personal blog project for learning

key word

  1. OLED display
  2. RXTX, IIC communication
  3. Database connection storage
  4. Real time detection (1s / time)
  5. Data analysis
  6. Any temperature and humidity upper and lower limit alarm
  7. Use of Arduino u8glib and DHT Libraries

The design studies the design and implementation of digital electronic thermometer, and uses javaRXTX to transmit data to the database in real time, which makes data analysis possible and makes our temperature and humidity digitization more specific and feasible.
IIC communication mode is adopted to display the data on the OLED digital display. With the development of technology, the trace of digital thermometer can also be felt in some occasions with bad environment. In this design, the design of thermometer is mainly discussed from the aspects of function combination, hardware combination, software algorithm and so on. Digital thermometer has many advantages in modern temperature measurement application, which is worthy of further study and research

System overview

System structure
In this design, DHT11 sensor is used as the main data acquisition party to realize the function. Arduino is used as the lower computer to read the converted data and display it on the OLED screen, and RXTX is used for serial communication to collect the data in real time into the computer database of the upper computer, so as to realize the monitoring, reading and storage of data, which makes the data analysis of temperature and humidity data convenient and simple.

General structure:

DHT11 module:
DHT11 digital temperature and humidity sensor is a temperature and humidity composite sensor with calibrated digital signal output. It applies special digital module acquisition technology and temperature and humidity sensing technology to ensure that the product has high reliability and excellent long-term stability. The sensor includes a resistive humidity sensing element and an NTC temperature measuring element, which are connected with a high-performance 8-bit single chip microcomputer. Therefore, the product has the advantages of excellent quality, ultra fast response, strong anti-interference ability and high cost performance. Each DHT11 sensor is calibrated in an extremely accurate humidity calibration chamber. The calibration coefficients are stored in OTP memory in the form of program, and these calibration coefficients should be called during the processing of detection signal inside the sensor. Single line serial interface makes system integration simple and fast. Its ultra-small size and extremely low power consumption make it the best choice in this kind of applications and harsh applications. The product is packaged with 4-pin single row pins, which is convenient for connection.

Design principle of DHT11:

DHT11 is composed of resistive humidity sensing element and NTC resistance sensing element. After measurement, it is transmitted to micro control unit (MCU) for conversion (the measured conversion is completed by the corresponding conversion program of fixed resistance value electric quantity value written in OTP memory), and then transmitted to DATA port and output to MCU for display.
Among them, the principle of resistive humidity sensing element: the resistive humidity sensor is a sensor for humidity measurement based on the principle that the electrical characteristics of the humidity sensing element change with the change of humidity. The humidity sensing element is generally made by impregnating hygroscopic substances on the insulation or separated by a layer of metal, semiconductor, polymer film and powder particles through evaporation, coating and other processes. In the process of moisture absorption and dehumidification of the humidity sensing element, The conduction state of ion H + decomposed by water molecules changes, so that the resistance value of the element changes with humidity.
It has an exponential function relationship with ambient relative humidity (RH) and ambient temperature (T), and the formula can be expressed as R=Roexp α ( Φ-Φ 0)-Rtexp β (t-t0) Ro is the initial resistance, α Is humidity constant, Rt is initial resistance, β Is the temperature constant.
Principle of NTC resistance measuring element: NTC is the abbreviation of Negative Temperature Coefficient, which means Negative Temperature Coefficient. It generally refers to semiconductor materials or components with large Negative Temperature Coefficient. The so-called NTC thermistor is a Negative Temperature Coefficient thermistor. It is made of metal oxides such as manganese, cobalt, nickel and copper by ceramic process. These metal oxide materials have semiconductor properties because they are completely similar to semiconductor materials such as germanium and silicon in terms of conductive mode. When the temperature is low, the number of carriers (electrons and holes) of these oxide materials is small, so their resistance value is high; With the increase of temperature, the number of carriers increases, so the resistance value decreases.
The resistance temperature characteristic of thermistor can be approximately expressed by equation 1.
(formula 1) R=Ro exp {B(I/T-I/To)}
R: resistance value at temperature T(K)
Ro: resistance value at temperature T0(K)
B: b value
*T(K)= t(º C)+273.15 is the official temperature measured conversion formula.

After connecting to the system, because dht11 is a strain sensor, add a stable Vcc power supply of 3~5V to pin 2 and reduce the power input with resistance. On the premise of not interfering with the correctness of the measured value of DATA input and providing a stable power supply, the transmitted physical quantity can be converted into the DATA to be displayed.

Serial interface (single line and two-way)
DATA is used for communication and synchronization between MCU and DHT11
Single bus data format is adopted
One communication time is about 4ms
The data is divided into decimal part and integer part. The current decimal part is used for future expansion. Now it is read as zero.
Data transmission format:
A complete data transmission is 40bit, high bit first out.
Data format:
8bit humidity integer data + 8bit humidity decimal data + 8bit temperature integer data + 8bit temperature decimal data + 8bit checksum

Transmission mode:

The bus idle state is high
When it is necessary to collect data, the host pulls down the bus and waits for the response of DHT11 (it must be greater than 18 milliseconds to ensure that DHT11 can detect the start signal.)
After receiving the start signal from the host, DHT11 waits for the end of the host start signal.
After the host sends the start signal, it changes to the input mode (i.e. pull high level) and waits for 20-40us.
The host reads the response signal of DHT11. If the bus is at low level, it indicates that DHT11 begins to respond.
DHT11 starts to respond to 80us and then pulls up the bus 80us
Then start transmitting 0_ 1 signal
Wiring port:

System hardware design:

System host computer design:

Functions of the system

The data collected by DHT11 is displayed on the OLED screen in real time after being sent to Arduino for real-time viewing. Then, the data is uploaded to the PC through RXTX and stored in the database using JDBC. The data can be analyzed by making a data table through Origin software or Excel, and then the temperature and humidity of the directly connected environment can be improved to their own suitable temperature.
development environment

  1. Arduino: as the lower computer, it is responsible for data acquisition, display and serial port upload.
    (1) Arduino.U8glib: used for character variable display of SSD1306 128x64 OLED screen and IIC communication with the screen
    (2) Arduino.DHT: general library for DHT11 data collection
  2. Eclipse (java): as the upper computer, it is responsible for data collection, sorting and storage into the database.
    (1) Java.RXTX: RXTX.jar is used for serial communication to transfer the data of Arduino to the serial port and upload it to the java program.
    (2) Java.JDBC: JDBC.jar is used to connect java data and database storage.
  3. MySql: used to store temperature and humidity collection data.

sensor technology

DHT11 sensor module:
Design principle of DHT11:

DHT11 is composed of resistive humidity sensing element and NTC resistance sensing element. After measurement, it is transmitted to micro control unit (MCU) for conversion (the measured conversion is completed by the corresponding conversion program of fixed resistance value electric quantity value written in OTP memory), and then transmitted to DATA port and output to MCU for display.
Principle of resistive humidity sensor: resistive humidity sensor is a sensor for humidity measurement based on the principle that the electrical characteristics of humidity sensor change with the change of humidity. Humidity sensor is generally made by impregnating hygroscopic substances on insulation, or separating a layer of metal, semiconductor, polymer film and powder particles through evaporation, coating and other processes. In the process of moisture absorption and dehumidification of humidity sensor, The conduction state of ion H + decomposed by water molecules changes, so that the resistance value of the element changes with humidity.
It has an exponential function relationship with ambient relative humidity (RH) and ambient temperature (T), and the formula can be expressed as R=Roexp α ( Φ-Φ 0)-Rtexp β (t-t0) Ro is the initial resistance, α Is humidity constant, Rt is initial resistance, β Is the temperature constant.
Principle of NTC resistance measuring element: NTC is the abbreviation of Negative Temperature Coefficient, which means Negative Temperature Coefficient. It generally refers to semiconductor materials or components with large Negative Temperature Coefficient. The so-called NTC thermistor is a Negative Temperature Coefficient thermistor. It is made of metal oxides such as manganese, cobalt, nickel and copper by ceramic process. These metal oxide materials have semiconductor properties because they are completely similar to semiconductor materials such as germanium and silicon in terms of conductive mode. When the temperature is low, the number of carriers (electrons and holes) of these oxide materials is small, so their resistance value is high; With the increase of temperature, the number of carriers increases, so the resistance value decreases.
The resistance temperature characteristic of thermistor can be approximately expressed by equation 1.
(formula 1) R=Ro exp {B(I/T-I/To)} R: resistance value at temperature T(K); Ro: resistance value at temperature T0(K); B: B
*T(K)= t(º C)+273.15 is the official temperature measured conversion formula.

After connecting to the system, because dht11 is a strain sensor, add a stable Vcc power supply of 3~5V to pin 2 and reduce the power input with resistance. On the premise of not interfering with the correctness of the measured value of DATA input and providing a stable power supply, the transmitted physical quantity can be converted into the DATA to be displayed.

This code is used to convert the collected data to realize the output data;

The data receiving at Arduino end is used to separate the temperature and humidity after conversion into two arrays; The last sentence is used to set the upper and lower limits of buzzer alarm.

Arduino has an internal lCD/LED screen library u8glib, which uses IIC/SPI communication to enable data variables to be displayed on the screen.

Used to start IIC communication

128x64 nixie tube for lighting the screen

This function is used for data display location and data transmission

When starting the OLED screen with Arduino, the do... while... Function is required for data display

Other related technologies

IIC communication:

RXTX communication:

rxtx data connection dll file provided for java;

Call rxtx Jar package is used to open and close the specified serial port;

Used to display all openable serial ports

Used to open the specified serial port

Information for setting serial communication

For communication, convert the data obtained from the serial port into recognizable GBK basic display standard, and then read and display it on the upper software side.

Open serial port for event trigger monitoring

It is used to transcode and display the information read by the serial port, convert it into a string and assign it to t for display

It is used to obtain the system time during data acquisition and record it into the database to achieve real-time recording effect

JDBC communication:
DBUtil.java is used for JDBC programming to call MySql database to add, delete, modify and query data

Used to set the basic database connection information and call the driver

For query operation

Used for adding, deleting, querying and modifying

The system uses statements to transfer data into the database, in which the temperature and humidity to be transmitted are used

Use the split function to separate into two arrays and store them separately.

Hardware implementation

OLED wiring: A5  SCL
A4SDA
VCC3.3V
GNDReset/GND

DHT11 wiring: DAT  D2
GNDGND
VCC3.3V
Buzzer wiring: S  D6
GNDGND
VCC3.3V

Arduino code implementation

#include <dht11.h>
#include <U8glib.h>
  U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C / TWI 
//U8GLIB_SSD1306_128X64 u8g(10, 9);
dht11 DHT11;
#define DHT11PIN 2

//float temp=0;// Temperature display


void setup() {
//temp
  Serial.begin(9600);
  //Serial.println("begin!");

//!
  pinMode(6,OUTPUT);
 
//oled display
  if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }

}

void draw(void) {
  u8g.setFont(u8g_font_8x13);
  u8g.setPrintPos(0,20);
  u8g.print("HUMI(%):");
  u8g.setPrintPos(73,20);
  u8g.print((float)DHT11.humidity);
  u8g.setPrintPos(0,40);
  u8g.print("TEMP(℃):");
  u8g.setPrintPos(73,40);
  u8g.print((float)DHT11.temperature);
}

void sound(){
  for(int i=500;i<600;i++)
  {
    digitalWrite(6,HIGH);
    delay(5);
  }
  digitalWrite(6,LOW);
}

void loop() {

//temp
  //Serial.println("\n");
  int chk=DHT11.read(DHT11PIN);
  //Serial.print("Humidity (%): ");
  Serial.print((float)DHT11.humidity, 2);
  Serial.print("\t");
  //Serial.print("Temperature (oC): ");
  Serial.print((float)DHT11.temperature, 2);
  if(((float)DHT11.humidity>=94)&&((float)DHT11.temperature>=30)){
    sound();
  }
 //oled
  u8g.firstPage();  
  do {
    draw();
  } while( u8g.nextPage() );
  delay(1000); 

}

JAVA software code

//OpenerAndCloser.java
package com.serialPort.writer;

import java.util.Enumeration;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;


/**
 * This class implements three functions
 * 1.List all local serial ports;
 * 2.Open all serial ports (but no data is written to the serial port);
 * 3.Close the open serial port.
 */
public class OpenerAndCloser {
    public static void main(String[] args){
        //1. Obtain all local ports and output their names:
        //1.1. Variable used to identify the port
        CommPortIdentifier portIdentifier = null;

        //1.2. Record variables for all ports
        Enumeration<?> allPorts 
            = CommPortIdentifier.getPortIdentifiers();

        //1.3. Output each port
        while(allPorts.hasMoreElements()){
            portIdentifier 
                = (CommPortIdentifier) allPorts.nextElement();
            System.out.println("Serial port:" + portIdentifier.getName());
        }

        //2. Open COM3 and COM21 ports
        //2.1. Get two ports
        CommPortIdentifier com3 = null;
        try {
            com3 = CommPortIdentifier.getPortIdentifier("COM3");
        } catch (NoSuchPortException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //2.2. Open two ports, but do nothing
        SerialPort serialCom3 = null;
        try {
            //The first parameter of the open method indicates the owner name after the serial port is opened,
            //The second parameter indicates the maximum waiting time of the program if the serial port is occupied, in milliseconds.
            serialCom3 
                = (SerialPort)com3.open("OpenerAndCloser", 1000);
        } catch (PortInUseException e) {
            //This exception is thrown when the port to be opened is occupied
            e.printStackTrace();
        }

        //2.3. Two port settings
        try {
            serialCom3.setSerialPortParams(
                    9600, //Baud rate
                    SerialPort.DATABITS_8,//Data bits
                    SerialPort.STOPBITS_1,//Stop bit
                    SerialPort.PARITY_NONE//Parity bit
            );
        } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
        }

        //3. Close COM3 and COM21 ports
        //The method to close the port is in the SerialPort class
        serialCom3.close();

    }
}
//Com3EventListener.java
package com.serialPort.writer;
import java.awt.HeadlessException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TooManyListenersException;

import javax.swing.JOptionPane;

import db.DBUtil;
import src.a;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
@SuppressWarnings("unused")
public class Com3EventListener implements SerialPortEventListener {

	public static String t0;
	public static String t1;
	//1. Define variables
    CommPortIdentifier com3 = null;//Undocked port
    SerialPort serialCom3 = null;//Open port
    InputStream inputStream = null;//Input stream
    //2. Constructor:
    //Realize the initialization action: obtain the serial port COM3, open the serial port, obtain the serial port input stream object, and add an event monitoring object for the serial port
    public Com3EventListener(){
        try {
            //Obtain the serial port, open the window serial port, and obtain the input stream of the serial port.
            com3 = CommPortIdentifier.getPortIdentifier("COM3");
            serialCom3 = (SerialPort) com3.open("Com3EventListener", 1000);
            inputStream = serialCom3.getInputStream();
            //Add an event listening object to the serial port.
            serialCom3.addEventListener(this);
            //This setting is necessary to set the event to be triggered when data is available on the port.
            serialCom3.notifyOnDataAvailable(true);
        } catch (NoSuchPortException e) {
            e.printStackTrace();
        } catch (PortInUseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
    }
    //Override inherited listener methods
    @Override
    public void serialEvent(SerialPortEvent event) {
        //Defines an array for caching read in data
        byte[] cache = new byte[1023];
        //Record the number of bytes of data that has reached the serial port COM3 and has not been read.
        int availableBytes = 0;

        //If the data is sent when it is available, read and write the data
        if(event.getEventType() == SerialPortEvent.DATA_AVAILABLE){
            try {
                availableBytes = inputStream.available();
                while(availableBytes > 0){
                    inputStream.read(cache);
                    String t="";
                    for(int i = 0; i < cache.length && i < availableBytes; i++){
                        //Decode and output data
                     t=t+String.valueOf((char)cache[i]);
                     t = t.replaceAll("\r|\n", "");
                      //  GUI.txtUser.setText("1");
                    }
                    //System.out.print(t);
                    
                    DBUtil db=new DBUtil();
    				Connection conn=null;
    					try {
    						conn=db.getConnection();
    					} catch (ClassNotFoundException e3) {
    						// catch block automatically generated by TODO
    						e3.printStackTrace();
    					} catch (SQLException e3) {
    						// catch block automatically generated by TODO
    						e3.printStackTrace();
    					} catch (InstantiationException e3) {
    						// catch block automatically generated by TODO
    						e3.printStackTrace();
    					} catch (IllegalAccessException e3) {
    						// catch block automatically generated by TODO
    						e3.printStackTrace();
    					}
    				Statement stmt = null;
    				try {
    					stmt = conn.createStatement();
    				} catch (SQLException e2) {
    					// catch block automatically generated by TODO
    					e2.printStackTrace();
    				}
    				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//Format date
    				//*************************Storage database***************************
    				String [] temp;
    				temp=t.split("\t");
    				t0=temp[0];
    				t1=temp[1];
    				System.out.println(t0);
    		        
    		        System.out.println(df.format(new Date()));// new Date() is the current system time
    				
       				String tempsql="insert into t(humi,temp,time) values('"+t0+"','"+t1+"','"+df.format(new Date())+"')";
    				
    				System.out.println("SQL:"+tempsql);
    				int addtest=0;
    				try {
    					addtest=stmt.executeUpdate(tempsql);
    				} catch (SQLException e1) {
    					// catch block automatically generated by TODO
    					e1.printStackTrace();
    				} 
    				a.timeshow.setText(df.format(new Date()));
    				a.ttext.setText(temp[1]);
    				a.htext.setText(temp[0]);
                    availableBytes = inputStream.available();
                }
                System.out.println();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //Create an instance of the class in the main method
    public static void main(String[] args) {
        new Com3EventListener();
    }
}
 

Function use



Tags: Java IoT Sensor

Posted by jagdpenta on Thu, 12 May 2022 16:38:43 +0300