Zigbee Wireless Sensor Network CC2530+DHT11&DS18B20 Temperature and Humidity Collection Serial PC Display

1. Introduction

  1. Hardware: 4 CC2530 modules, 2 DS18B20 temperature sensors, 1 DHT11 sensor, and 1 pump (none).
  2. Software: Develop PC (.NET Framework 4.8), ZStack-2.5.1a protocol stack based on C#
  3. Star network is composed of coordinators and nodes, and can access up to six terminal nodes by on-demand communication (P2P), combined with the upper limit.
  4. Hardware Effect Diagram

2. Upper computer data collection

(1) Data collection

Open the serial port to show the situation and fluctuation.

(2) Topology

Displays the data of the node and its short address.

(3) New nodes join the network

(4) Node events

Node 4 humidity is higher than 70%, indicating that the topology graph hides the node while the pump stops working.

3. Realization Analysis

(1) Profile

  1. In f8wConfig. In CFG
    Set Channel: -DDEFAULT_CHANLIST=
    (Channel 11 seems to be susceptible to WIFI signals)
    Set PAN_ID:-DZDAPP_CONFIG_PAN_ID=
  2. In SamplleApp. H
    Data send interval 3 s
    #define SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT 3000

(2) Send

  1. In SamplleApp. C
  //Wireless Send to Coordinator
  if ( AF_DataRequest( &SampleApp_P2P_DstAddr, &SampleApp_epDesc,
                       SAMPLEAPP_P2P_CLUSTERID,
                       len,  // Data Length
                       str,	 // Data Content
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS ) == afStatus_SUCCESS )
  {
  }
}

(3) Short address and data acquisition

Short address pkt->srcAddr. Addr. ShortAddr is randomly assigned to the network.
The MAC address pkt->macDestAddr is more suitable as the primary key for data storage.
Data uint8 temperature=pkt->cmd. Data [0]; Uint8 humidity=pkt->cmd. Data [1];

  1. In AF.h
typedef struct
{
  union
  {
    uint16      shortAddr; // (short address)
    ZLongAddr_t extAddr;
  } addr;
  afAddrMode_t addrMode;
  uint8 endPoint;
  uint16 panId;  // used for the INTER_PAN feature
} afAddrType_t;


typedef struct
{
  osal_event_hdr_t hdr;     /* OSAL Message header */
  uint16 groupId;           /* Message's group ID - 0 if not set */
  uint16 clusterId;         /* Message's cluster ID (Cluster ID) */
  afAddrType_t srcAddr;     /* Source Address, if endpoint is STUBAPS_INTER_PAN_EP,
                               it's an InterPAN message */
  uint16 macDestAddr;       /* MAC header destination short address (MAC Address) */
  uint8 endPoint;           /* destination endpoint */
  uint8 wasBroadcast;       /* TRUE if network destination was a broadcast address */
  uint8 LinkQuality;        /* The link quality of the received data frame (Network Connection Quality) */
  uint8 correlation;        /* The raw correlation value of the received data frame */
  int8  rssi;               /* The received RF power in units dBm (Signal energy) */
  uint8 SecurityUse;        /* deprecated */
  uint32 timestamp;         /* receipt timestamp from MAC */
  uint8 nwkSeqNum;          /* network header frame sequence number */
  afMSGCommandFormat_t cmd; /* Application Data */
} afIncomingMSGPacket_t;
  1. In SamplleApp. In H
void SampleApp_ProcessMSGCmd( afIncomingMSGPacket_t *pkt )
{
  uint8 buff[50]={0};

  switch ( pkt->clusterId )
  {
  // Temperature and humidity data uploaded by receiving terminal
  case SAMPLEAPP_P2P_CLUSTERID: 
    {
      // Remove temperature and humidity data
      uint8 temperature = pkt->cmd.Data[0];
      uint8 humidity= pkt->cmd.Data[0];
      // Take out the short address
      uint16 shortAddress = pkt->srcAddr.addr.shortAddr;
      // Processing and data packaging upload serial interface
    }
    break;
  // Receiving temperature    
  case SAMPLEAPP_DS18B20_CLUSTER:
  	{
  	  // Left....
  	}
  	break;
  default:
  	break;

(4) Data package analysis

Serial data packaging format:

Length: 14;
Check bits: C4;
Function code: 02;
Data: 3B 31 3B 54 3A 32 37 2E 30 20 43 3B 34 34 31 3B
End: 0D 0A.

supplement

  1. The 3B of the data section acts as the data content separator (;): (Function Code)+(;)+ (Collect data)+(;)+ (short address)+(;).
  2. And end with a line break\rn

(5) Upper computer

        // Whether to open serial port
        bool isOpenSP;
        // Number of records
        private int recordNum = 0;
        // Recording the detection results of each node for topology
        private string[] pointsTopology = {"", "", "", "", "", ""};
        // Mapping
        private Graphics graphics;
        
        private void mainForm_Load(object sender, EventArgs e)
        {
            Resize += mainForm_Resize;

            refreshBtn_Click(null, null);
            // baud rate
            int[] BR =
            {
                4_800, 9_600, 14_400, 19_200, 38_400, 56_000, 57_600, 115_200, 128_000,
                256_000, 460_800, 512_000, 750_000, 921_600, 1_500_000
            };
            foreach (int val in BR)
            {
                BRComboBox.Items.Add(val);
            }
            
            // Manually add event handlers
            serialPort1.DataReceived += serialPort1_DataReceived;
            // Drawing Initialization
            graphics = topologyPanel.CreateGraphics();
        }
  1. Serial Port Part
    The upper machine developed by Rider seems to have problems with the serial ports in the VS (delege is needed at this point)
        /*
         * 3. Functional implementation
         *  Open serial key openBtn_Click 
         *  Serial port data receive serialPort1_DataReceived 
         *  Receive data clearBtn_Click 
         *  Refresh Serial Password Key refreshBtn_Click 
         */

        private void openBtn_Click(object sender, EventArgs e)
        {
            if (SPComboBox.Text.Equals("") || BRComboBox.Text.Equals(""))
            {
                return;
            }
            
            if (!isOpenSP)
            {
                try
                {
                    serialPort1.PortName = SPComboBox.SelectedItem.ToString();
                    serialPort1.BaudRate = Convert.ToInt32(BRComboBox.SelectedItem.ToString());
                    serialPort1.Open();
                }
                catch
                {
                    MessageBox.Show("Port error, please check the serial port" , "error");
                    return;
                }
            }
            else
            {
                serialPort1.Close();
            }

            openBtn.Text = isOpenSP ? "open" : "Close";
            SPComboBox.Enabled = !SPComboBox.Enabled;
            BRComboBox.Enabled = !BRComboBox.Enabled;
            isOpenSP = !isOpenSP;
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (isOpenSP)
            {
                try
                {
                    // Reading Serial Port Data
                    string revStr = serialPort1.ReadLine();
                    revRichTextBox.AppendText(revStr);
                    revRichTextBox.SelectionStart = revRichTextBox.Text.Length;
                    // display
                    string[] pointsData = revStr.Split('\n'); 


                    Label[] pointsLabel = {point1Label, point2Label, point3Label, point4Label, point5Label, point6Label}; 
                    // Node name
                    Label[] pointsName = {pointName1Label, pointName2Label, pointName3Label, pointName4Label, pointName5Label, pointName6Label};
                    foreach (string pointData in pointsData)
                    {
                        int preSplit = pointData.IndexOf(";") + 1;
                        int nextSplit = pointData.IndexOf(";", preSplit);
                            // Get collection node display id - 1
                        int index = Convert.ToInt32(pointData.Substring(preSplit,nextSplit - preSplit)) - 1;
                        preSplit = nextSplit + 1;
                        nextSplit = pointData.IndexOf(";", preSplit);
                        // Serial format parsing display
                        pointsLabel[index].Text = pointData.Substring(preSplit, nextSplit - preSplit);
                        // temperature
                        string temp = pointData.Substring(preSplit + 2, pointData.IndexOf(" C") - preSplit - 2);
                        



						chart1.Series[index].Points.AddXY(recordNum, temp);
                        // Node name of the curve
                        chart1.Series[index].Name = pointsName[index].Text + "temperature";
                        // humidity
                        string humidity = "50";
                        if (index % 2 != 0)
                        {
                            humidity = pointData.Substring(pointData.IndexOf("H:") + 2,
                                nextSplit - pointData.IndexOf("H:") - 2);
                            chart1.Series[pointsLabel.Length + index].Points.AddXY(recordNum, humidity);
                            // Node name of the curve
                            chart1.Series[pointsLabel.Length + index].Name = pointsName[index].Text + "humidity";
                        }
                        // Color tips given when treatment temperature is below 5 degrees and humidity is above 70 percent
                        if (Convert.ToDouble(temp) < 5 || Convert.ToDouble(humidity) > 70)
                        {
                            pointsLabel[index].BackColor = Color.FromArgb(74, 140, 218);
                            pointsTopology[index] = "";
                        }
                        else
                        {
                            pointsLabel[index].BackColor = Color.White;
                            // Record processable values for topological diagrams
                            pointsTopology[index] = pointData.Substring(pointData.IndexOf(";") + 1);
                        }
                        pointsName[index].BackColor = pointsLabel[index].BackColor;
                    }
               
               
                    recordNum++;
                    chart1.ChartAreas[0].AxisX.Title = "time";
                    chart1.ChartAreas[0].AxisY.Title = "data";
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.ToString());
                }
            }
        }
        
        private void clearBtn_Click(object sender, EventArgs e)
        {
            revRichTextBox.Text = "";

            point1Label.Text = "0";
            point2Label.Text = "0";
            point3Label.Text = "0";
            point4Label.Text = "0";
            point5Label.Text = "0";
            point6Label.Text = "0";
        }
        
        private void refreshBtn_Click(object sender, EventArgs e)
        {
            SPComboBox.Items.Clear();
            // Get the port number
            string[] PortNames = SerialPort.GetPortNames();
            for (int i = 0; i < PortNames.Length; i++)
            {
                //Load array contents into comboBox controls
                SPComboBox.Items.Add(PortNames[i]);
            }
        }
  1. Data Topology Part
        /*
         * 2 Functional Options
         *  Function list zoom funBtn_Click
         *  Key Initialization funBtnsInit 
         *  Data Acquisition Interface Key dataBtn_Click 
         *  Topology Diagram Interface Keys topologyBtn_Click 
         */
        private void funBtn_Click(object sender, EventArgs e)
        {
            funPanel.Width = funPanel.Width == 40 ? 250 : 40;
            titLabel.Width = funPanel.Width;
        }

        private void funBtnsInit()
        {
            dataBtn.BackColor = funPanel.BackColor;
            topologyBtn.BackColor = funPanel.BackColor;

            dataPanel.Visible = false;
            topologyPanel.Visible = false;
        }


        private void dataBtn_Click(object sender, EventArgs e)
        {
            funBtnsInit();
            dataBtn.BackColor = clickedBgColor;
            dataPanel.Visible = true;
        }

        private void topologyBtn_Click(object sender, EventArgs e)
        {
            funBtnsInit();
            topologyBtn.BackColor = clickedBgColor;
            topologyPanel.Visible = true;
            
            // Draw static topology
            graphics.Clear(topologyPanel.BackColor);
            graphics.FillRectangle(new SolidBrush(Color.Crimson),300, 300, 50, 50);
            Pen pen = new Pen(Color.Coral);
            Brush brush = new SolidBrush(Color.Coral);
            Point[] startPoint =
            {
                new Point(300, 300), new Point(325, 300), new Point(350, 300),
                new Point(350, 350), new Point(325, 350), new Point(300, 350)
            };
            Point[] endPoint =
            {
                new Point(100, 100), new Point(325, 200), new Point(450, 400),
                new Point(450, 450), new Point(325, 450), new Point(250, 200)
            };
            int index = 0;
            foreach (string pointTopology in pointsTopology)
            {
                if (pointTopology.Equals(""))
                {
                    continue;
                }
                
                graphics.DrawLine(pen,startPoint[index], endPoint[index]);
                
                graphics.FillEllipse(brush, endPoint[index].X, endPoint[index].Y, 20, 20);
                graphics.DrawString(pointTopology, 
                    new Font("Microsoft YaHei", 10), 
                    new SolidBrush(Color.Black),
                    endPoint[index].X + 5, endPoint[index].Y + 5);
                index++;
            }
            
            pointsTopology = new []{"", "", "", "", "", ""};
        }

IV. IAR

  1. There seems to be a corresponding link between the IAR software and the protocol stack, and the Z-stack 2.5.1 protocol stack compiled under the higher version of IAR had problems Reference resources
  2. IAR Settings External Editor
    Tools > Options

    Editor > External Editor > Check Use External Editor > Select External Editor Program Address > Fill in the Arguments column with'$FILE_PATH$'> Click Confirm

    By clicking on the file, you can edit it through other editors, but there will also be problems with Chinese random code.

Added by 01hanstu on Thu, 20 Jan 2022 05:53:55 +0200