M2M technology example-detailed explanation of wired data transmission between cc2530 (including experiments)

Preface

The author wanted to write some articles about Zigbee a long time ago to help latecomers learn related hardware knowledge. I know that hardware learning takes a long time to accumulate, because you will be debugging or Various problems were encountered during the experiment... Therefore, if someone can help you use some vivid sentences, understand obscure professional terms, and give more example codes when you are just learning, At the same time, if you leave your experience behind, it will be of great help to those who come after you! This article will take the wired data transmission between cc2530 microcontrollers as the starting point, and explain in detail what M2M technology is, as well as the function and use of cc2530 microcontrollers, as the starting point of our Zigbee series of articles !

Article audience:Students who want to understand M2M technology, systematically learn the cc2530 development board and are learning zigbee technology

1. Introduction to M2M technology

M2M technology (Machine-to-Machine technology), it is a technology that allows devices to communicate and exchange data. If we analyze the English name word by word, we will find that M2M, in which the "2" refers to "to", is translated in the most appropriate words "Communication between machines ”, “communication” here refers to data transmission. It is important to note that M2M technology often involves connecting sensors, devices, and other Internet of Things (IoT) devices to the Internet so that they can exchange data and collaborate automatically without human intervention. This communication can bewired or wireless and is designed to enable automation, monitoring, control and data collection to increase efficiency, reduce costs and improve a variety of application. In summary, M2M technology provides a powerful way to connect devices and systems to achieve automation, monitoring and control, thereby improving various fields efficiency and productivity. This area has played a key role in the rapid development of the Internet of Things (IoT) and will continue to play an important role in the future.

Some key features and aspects of M2M technology

  1. Automated communication: M2M technology aims to achieve automation through automatic communication between devices. Devices can automatically send and receive data, trigger actions, or perform tasks without human intervention. This has applications in many areas such as industrial automation, smart homes, agriculture and traffic management.

  2. Data collection and transmission: M2M technology enables devices to collect various data, such as temperature, humidity, location, status, etc., and then transmit these data to a central server or other devices for further processing and analysis. This facilitates real-time monitoring and data-driven decision-making.

  3. Application fields: M2M technology is widely used, including smart homes, smart cities, industrial automation, healthcare, logistics and transportation, agriculture, etc. It can improve energy management, remote monitoring, equipment maintenance and many more applications.

  4. Communication technology: M2M communication can be based on various communication technologies, including wireless technologies such as cellular networks (such as 2G, 3G, 4G, 5G), Wi-Fi, Bluetooth, Zigbee , as well as wired technologies such as Ethernet, power line communications, etc. The communication technology chosen depends on the application requirements and environment.

  5. Data security: Since a large amount of sensitive data is involved, M2M technology needs to emphasize data security. This includes encrypted communications, authentication, access control and data privacy protection.

  6. Cloud integration: M2M is often integrated with cloud computing, uploading data to the cloud for remote access and analysis. This allows for more flexible data processing, as well as remote monitoring and control.

  7. Standardization: There are many M2M standards and protocols, such as MQTT, CoAP, OPC UA, etc., to ensure interoperability between different devices and systems.

2. CC2530 and Zigbee technology

The CC2530 is a wireless SoC (system-on-chip) produced by Texas Instruments and is mainly used for Internet of Things (IoT) and embedded wireless communication applications. Zigbee is a low-power, short-range, self-organizing wireless communication protocol commonly used in IoT applications. It has the characteristics of reliable communication, low energy consumption, automatic networking and interoperability, and is suitable for connecting various IoT devices.

And CC2530 is usually used in Zigbee technology and is a chip that supports Zigbee communication protocol. This means that subsequent related articles will be inseparable from this chip. Developers can use CC2530 to build Zigbee terminal devices, coordinators (Coordinators) and routers (Router), thus Build Zigbee networks with self-organization and scalability.

Introduction to CC2530 chip

  1. Chip Overview: The CC2530 is a powerful RF system-on-chip with a built-in 802.15.4 RF transceiver and microcontroller unit. It is based on 8051 core microcontroller and integrates IEEE 802.15 .4 Standard wireless communication protocol stack, usually used for low-power, short-range wireless communication applications.

  2. Wireless communication: CC2530 supports the IEEE 802.15.4 standard, a protocol for low-power, low-data-rate, short-range communications. It is suitable for a variety of IoT applications, including smart homes, industrial automation, sensor networks, and monitoring systems.

  3. Microcontroller: The CC2530 integrates a powerful 8051 microcontroller unit to handle application and communication tasks. It also has rich peripherals such as UART, SPI, I2C, timers and GPIO pins to meet the needs of different applications.

  4. Low power design: The design of CC2530focuses on low power performance, which makes it very Suitable for battery powered devices. It consumes very little power in standby mode and supports quick wake-up to reduce energy consumption.

  5. Integration: CC2530 has a high level of integration, with built-in RF front-end, RF transceiver, clock and microcontroller, thereby reducing the cost and complexity of the system. In addition, it provides some easy-to-use development tools and software support to help developers design and deploy wireless applications more easily.

  6. Application fields: CC2530 is widely used in various IoT devices, including smart home controllers, sensor nodes, medical equipment, industrial sensors and wireless control systems. It can be used to establish self-organized sensor networks to achieve data exchange and remote control between devices.

  7. Ecosystem Support:Texas Instruments provides extensive documentation, software tools and development kits to support developers building applications on the CC2530. These resources help streamline the development process and reduce time to market.

Detailed introduction to Zigbee technology

1. Zigbee overview

Zigbee is a wireless communication standard designed to support short-range communication between devices, typically within a range of 10 to 100 meters . It uses low-power communication and is suitable for battery-operated devices that need to run for long periods of time. The Zigbee standard is managed by the Zigbee Alliance and aims to promote the development of the Internet of Things.

2、Special point harmony

  • Low power consumption: Zigbee devices are typically very power efficient and can run on battery power for months or even years.
  • Short-distance communication: Zigbee is used for short-distance communication between devices and is suitable for local networks and home automation applications.
  • Self-organizing network: Zigbee devices can automatically build and manage their own networks without the need for a central controller. This self-organization facilitates large-scale device interconnection.
  • Low data rate: Zigbee is typically used to transmit small amounts of data, such as sensor readings and control instructions.
  • Interoperability: The Zigbee standard ensures that devices from different manufacturers can communicate with each other, promoting interoperability between multi-vendor devices.
  • Security: Zigbee provides data encryption and security authentication functions to protect the security of communication.

3,Zigbee protocol stack (2007_ZStack-CC2530-2.5.1a)

  • Physical layer (PHY): Determines the transmission characteristics of wireless signals, such as frequency, modulation, and power.
  • Media Access Control (MAC): Handles the transmission of frames, device sleep and wake-up, and network topology.
  • Network layer: Manages routing, address allocation, and data transfer between devices.
  • Application layer: Defines application-specific data formats and communication protocols.

 Note: Since the protocol stack is mentioned here, I will explain it in detail first, and we will take our time in the specific details later. Our current article only introduces zigbee technology and lets us first become familiar with the use of its chip cc2530. In fact, it is not difficult for us to understand that the core of zigbee lies in long-distance wireless transmission, and the role of the zigbee protocol stack: defines the communication rules and protocols between devices, and provides low-level communication between devices. Power-consumption, self-organizing communication provides a structured and regulated approach.

In short, the operation and use of this protocol stack will be the top priority for us to learn zigbee technology! Our subsequent articles will focus on the ZStack-CC2530-2.5.1a (2007 version) protocol stack. (ZStack is the Zigbee protocol stack provided by Texas Instruments (TI) for its wireless chips (such as CC2530) )< /span>

4. Application areas

  • Smart Home: Control smart lighting, smart thermostats, security systems and more.
  • Industrial Automation: Monitor and control factory equipment, sensor networks, wireless monitoring, and more.
  • Smart city: Urban lighting, parking management, trash can monitoring, etc.
  • Healthcare: Remote health monitoring, medical device interconnection.
  • Agriculture: Agricultural sensor networks, irrigation control, farm monitoring.

 3. Wired communication between CC2530

The wired communication mentioned here is wired data transmission within the scope of M2M technology. Our purpose is to become familiar with the IO port, register, USART, etc. of cc2530 through this wired communication. Then I will start from basic knowledge and must know , personal experience Share summary, Detailed analysis of relevant experiments to explain these three modules! !

1. Basic knowledge must be known and mastered

(First of all, let me state that we assume that readers already have certain hardware knowledge. I will not explain some particularly basic content, for example, what is a serial port?These questions, Study on your own!!)

 1) Common appearance and chip schematic diagram display

  Common appearance of cc2530 development board

cc2530 schematic diagram

2) Register description of I/O port

The difference between general-purpose IO and peripheral IO:General-purpose I/O (GPIO) pins are multi-purpose, flexibly configurable general-purpose pins, suitable for various tasks, and Peripheral I/O pins are pins specifically used to connect to specific external devices or perform specific tasks, and their functions are limited by hardware design.

The general I/O port here can be set as an input interface or an output interface through register configuration. The commonly used registers of I/O pin ports are shown in the figure below.

1. I/O setting register

2. Port direction register

 

3) Summary of basic concepts (limited energy, will continue to update later, leave a message in the comment area if you don’t understand...)

1. Bit addressing

usually refers to the operation of retrieving and obtaining values ​​for specific bits in binary data. In the computer field, bit search is often used to extract or check the value of a certain bit from binary data for further processing or decision-making. This operation can involve bitwise operations and bit masks. Bit search is often used in computer programming and embedded systems for bit-level operations, such as setting and clearing flag bits, and operating on bits in registers or data structures. It is a fundamental building block of bit operations. In short, cc2530 is an 8051 microcontroller that supports direct alignment operation.

Simple bit-finding example:

Suppose there is an 8-bit binary number: 11011011

If you want to find the value at position 4 (numbered from right to left, starting from 0), you can use bit operations to perform a bit search, for example:

  • Get the value of bit 4: 11011011 & 00001000
  • The result is 0, indicating that bit 4 is 0.
2. DMA controller

The DMA controller is a hardware module used to transfer data directly from memory without CPU intervention. The main purpose of DMA is to improve the efficiency of data transmission, reduce the burden on the CPU, and allow the CPU to continue performing other tasks during data transmission. To understand it in a simple way, The DMA controller is like an automatic porter, which can help you automatically move data from one place to another. , without the need for the CPU to be personally involved. It can independently transfer data from memory to peripherals, or from one peripheral to another, without requiring the CPU to keep an eye on it. This way, the CPU can focus on performing other important tasks rather than having to handle every data transfer request personally. This increases the efficiency and performance of computer systems. Therefore, the role of the DMA controller is to reduce the burden on the CPU and make data transmission more efficient.

2. Sharing summary of personal experience (continuously updated...)

1. The wired communication between two microcontrollers is to connect the RXD of machine A to the TXD of machine B. One data output and one data input. The specific process is as shown in the figure:

2. Before starting development, carefully read the CC2530 data sheet, user guide, reference manual and other documents (included in the materials required for the experiment). These documents provide detailed information about the chip, including pin definitions, register configuration, communication protocols, and more.

3, Detailed analysis of relevant experiments

Preparation for the experiment

Related hardware: 1 wireless sensor network comprehensive experiment box, as shown below (theoretically, all development boards can complete the experiment)

Software: IAR software, serial port assistant

Data link:Data required for the experiment


Experiment 1: Button experiment

Experimental principle:When the I/O pin is used as an I/0 port, the pin can form three 8-bit ports, defined as P0, P1 and P2, P0 And P1 is 8 bits, P2 is 5 bits, a total of 21 pins, all ports can achieve bit addressing. All port pins can be configured and initialized through the SFR registers PxSEL and PxDIR.

Content: Realize different flashing effects of button control lights LED2 and LED3, specifically: the number of times the button is pressed, the light flashes several times in succession, and then the button is pressed. Repeat in this manner (the number of light flashes does not exceed 5 times) (the circuit diagram is shown below)

Implementation code:

#include<iocc2530.h>
#define  key1 P1_1
#define  led2 P0_1
#define  led3 P0_4

void delay(unsigned int time)
{
    unsigned char  n;
   while(time>0)
    {
    for(n=0;n<187;++n)           
  { 
asm("nop");
}
time--;
}
}

void main()
{
  P0SEL=~0X12;
  P1SEL=~0X02;
  P0DIR|=0X12;

  P1DIR|=0X00;
  int i=0;
  led2=1;
  led3=1;
  int j;
  while(1)
  {
	 
    if(key1==0)
    {
	while(key1==0);
      i++;
      for(j=0;j<i;j++)
      {
        led2=0;
        led3=0;
        delay(500);//延时函数的调用
        led2=1;
        led3=1;
        delay(500);
      }
      if(i==5)
      {
        i=0;
      }
    }
}
}


Experiment 2:External interrupt experiment

Experimental principle:CC2530 has 18 interrupt sources, each interrupt source has its own interrupt request flag located in a series of registers. Each interrupt can be enabled or disabled individually. Enable or disable by setting the interrupt enable bit of the interrupt enable register IEN0, IEN1 or IEN2. Some external devices generate interrupt requests due to several interrupt events. These interrupt requests can act on the P0 port, P1 port, P2 port, DMA, counter or RF. For each special function register corresponding to the internal interrupt source, these external devices have interrupt mask bits. When an interrupt occurs, whether the interrupt is enabled or disabled, the CPU will set the interrupt flag bit in the interrupt flag register. In the program, the interrupt flag bit can be used to determine whether a corresponding interrupt has occurred. If the interrupt flag is set, then In the next instruction cycle, the hardware forcibly generates a long call instruction LCALL to the corresponding vector address to run the interrupt service routine. Interrupt response takes different times, depending on the state of the CPU when the interrupt occurs. When the priority of the interrupt service routine that the CPU is running is greater than or equal to the new interrupt, the new interrupt will not be executed until the priority of the new interrupt is higher than the interrupt service routine that is running.

Experimental content: Start the base plate so that the lights D2 and D3 are all off, and the digital tube displays 0. After pressing the button S3 once, the lights D2 and D3 are on, and the digital tube displays 1; Press button S3 again, D2 and D3 will go out, and the digital tube will display 2; the following logic will be deduced in the same way, until it displays 9, and then returns to the initial state. It is required that changes in the status of the LED and digital tube must be implemented in the external interrupt function. (The circuit is shown in Figure 1 and Figure 2)

Implementation code:

#include <ioCC2530.h>
#define  LS164_DATA    P1_3
#define  LS164_CLK     P1_2
#define  UCHAR  unsigned char
#define   led1 	P0_1 
#define   led2 	P0_4  
#define   key  	P1_1 
int count =1;
static   UCHAR LED_Map[] = {0x3f,0x06,0x5b,0x4f, 0x66,0x6d,
0x7d,0x07, 0x7f,0x6f,0x00}; 

void delay(){
 for(int i=0; i<500; i++){
  for(int j=0; j<300; j++){
  }
 }
}

void LS164_Cfg()//I/O引脚初始化
{
    P1SEL  &= ~0x0C;//xxxx 00xx 
    P1DIR  |= 0x0C;//xxxx 11xx  
}

void LS164_BYTE(UCHAR Index)//数码管显示字形
{   UCHAR  i = 0;
    UCHAR  Data = LED_Map[Index];
    for(;i<8;i++)
    {
        if(0x80 & Data)
        {
          LS164_DATA = 1;    //传1位数据“1”           
        }
        else
        {
          LS164_DATA = 0;    //传1位数据“0” 
        }
        Data = Data << 1;
        LS164_CLK = 0;
        LS164_CLK = 1;    //时钟形成上升沿
    }
}

#pragma vector = P1INT_VECTOR   //端口P0的中断处理函数
 __interrupt void P1_ISR(void)
 {
    if(P1IFG>0)            //按键中断
   {  
       led1=!led1;
       led2=!led2;	
       delay();
       LS164_BYTE(count++);
       if(count+1==11){
         count=0;}
       P1IFG = 0;          //清除P0_0中断标志
       P1IF = 0;             //清除P0中断标志
    }
 }



void main(){
  P0SEL &= ~0X12;
  P0DIR |=  0x12;
  P1SEL &= ~0X0E;
  P1DIR |=  0x0C;	
  
  P0INP |= 0x02; //上拉
  P1IEN |= 0x02;   //P01设置为中断方式

  PICTL |= 0X02;   //下降沿触发

  EA = 1;
  IEN2 |= 0X10;
  P0IFG |= 0x00;   //初始化中断标志位
  
  key=1;
  led1=1;
  led2=1;
  LS164_BYTE(0);
  while(1){
  }
}


Experiment 3:Serial communication experiment

Experimental principle:CC2530 has two serial ports USART0 and USART1, which can run in asynchronous mode (UART) or synchronous mode (SPI) respectively. When the register bit UxCSR.MODE is set to 1, the UART mode is selected, where x is the USART number and its value is 0 or 1. The two USARTs have the same function and can set separate I/O pins. Once determined, when programming, the USART I/O pins need to be set according to the hardware circuit. Register bit PERCFG.U0CFG selects whether position 1 or alternate position 2 is used. In UART mode, you can use a two-wire connection (containing pins RXD, TXD) or a four-wire connection (containing pins RXD, TXD, RTS and CTS), where the RTS and CTS pins are used for hardware flow control. UART mode provides full-duplex transmission, and bit synchronization in the receiver does not affect the transmit function. Transmitting a UART byte consists of a start bit, 8 data bits, an optional 9th ​​data bit or parity bit plus one or two stop bits.

Experimental content:Realize serial communication between microcontroller and PC. Send characters (0~9) to CC2530 in the sending window of the PC serial port assistant, and control the number of flashes of the two LEDs and the font displayed on the digital tube. If other characters are entered, (error) will be displayed in the serial port assistant and the serial port is required to receive To write interrupt function. (The circuit diagram of the serial port is shown below)

Implementation code:

#include <ioCC2530.h>
#include <string.h>

#define  LS164_DATA  P1_3
#define  LS164_CLK   P1_2
#define  led2 	P0_1 
#define  led3 	P0_4
#define  uchar  unsigned char
#define  uint unsigned int
  

uchar str1[6]="error\n";
uchar str2[10]="0123456789";
uchar temp;//中断标志位
static uchar LED_Map[] = {0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x00}; 
//静态全局变量,分别输出的值是0、1、2、3、4、5、6、7、8、9、无显示					
void delay(){
  for(int m=0;m<500;m++){
      for(int n=0;n<300;n++){
}}}

//数码管显示字形
void LS164_BYTE(uchar Index)//数码管显示字形	
{   
    uchar  i = 0;
    uchar  Data = LED_Map[Index];
    for(;i<8;i++)
    {
        if(0x80 & Data)
        {
          LS164_DATA = 1;    //传1位数据“1”           
        }
        else
        {
          LS164_DATA = 0;    //传1位数据“0” 
        }
        Data = Data << 1;
        LS164_CLK = 0;
        LS164_CLK = 1;    //时钟形成上升沿
    }
}

//串口初始化
void InitUART0(){
    CLKCONCMD &=~0x40;//设置系统时钟源为32MHZ晶振
    while(CLKCONSTA & 0x40);//等待晶振
    CLKCONCMD &=~0x47;//设置系统主时钟频率为32MHZ
    
    PERCFG = 0x00;//位置1p0口
    P0SEL = 0x3c;//P0做串口
    P2DIR &= ~0xc0;//p0优先作为UART0
    U0CSR |= 0x80;//串口设置为UNRT方式

    U0GCR |= 9;
    U0BAUD |= 59;//这两步用于设置波特率
    UTX0IF = 1;//标记初始位置1
    U0CSR |= 0x40;//允许接受
    IEN0 |= 0x84;//开总中断,接受中断
}


//串口发送字符串函数 发送error
void UartTX_Send_String(uchar *Data,int len)
{
  uint j;
  for(j=0;j<len;j++)
  {
    U0DBUF=*Data++;
    while(UTX0IF==0);//检测字符是否发送完毕
    UTX0IF=0;
  }
} 

//灯光闪烁
void LED_flash(uchar temp){
       	int count = 0;
	while(count<temp){
       	led2=!led2;
       	led3=!led3;
      	delay();
       	led2=!led2;
      	led3=!led3;
      	delay();
      	count++;
	}
}

//接收中断  U0DBUF接受  UTX0IF发送 
#pragma vector = URX0_VECTOR
__interrupt void UART0_ISR(void){
    uint n, i;//用于调用数组中的值
    URX0IF=0;
    temp = U0DBUF;
    UartTX_Send_String(temp,sizeof(temp));
/*
    for(n=0;n<10;n++){
          if(temp==str2[n]){
            LS164_BYTE(n);
            LED_flash(n);
            break;}
          else if(n>=0&&n<10) continue;  //用于判断是否继续执行
          else UartTX_Send_String(str1,6);}}
*/
    for(n=0;n<10;n++){
    if(temp==str2[n]){ i = 1; break;}
    else i = 2;}
    switch(i){
     case 1: LS164_BYTE(n); LED_flash(n); delay();delay();delay();delay(); break;
     case 2: UartTX_Send_String(str1,6); break;
     default:break;
    }
}
void Iint_IO()
{
//初始化P0端口
  P0SEL&=0X12;//led2 led3 P0_1 p0_4为IO
  P0DIR|=0X12;//方向是输出
  P1SEL  &= ~0x0c;//xxxx 00xx  配置为普通IO模式                          
  P1DIR  |= 0x0c;//xxxx 11xx   配置为输出模式 
}

//主函数
void main(void)
{
  Iint_IO();
  InitUART0();//串口初始化
}



Experiment 4:Timer 1 Experiment

Experimental principle:CC2530 has a total of 4 timers T1, T2, T3, and T4. The timers are used in a wide range of control and measurement applications. Timer 1 is a 16-bit timer/counter that supports input sampling, output comparison and PWM functions. Timer 1 contains the main registers T1CCxH (the value of The initial value is not 65535), count up/down (the initial value of the count is not 65535); Timer 1 increments or decrements on each active edge. The active clock edge period is defined by the register CLKCONCMD.TICKSPD, which sets the division of the global system clock and provides different clock mark frequencies from 0.25MHz to 32MHz (32MHzXOSC can be used as the clock source). In addition, Timer 1 can be used in T1CTL.DIV Carry out the second frequency division, the frequency division value can be 1, 8, 32 and 128; when the count value reaches the overflow value, the counter generates an interrupt request, and then the interrupt function of timer 1 can be executed.

Experiment content

Use timer 1 to control the flashing interval of two LEDs. Assume that it is on for 750ms and off for 250ms, and the digital tube countdown is implemented for 9 seconds (9~0). Timer 1 is required to use the up/down count mode for timing (need to write an interrupt function, The circuit diagram of the digital tube is shown in the figure below).

Implementation code:

#include<ioCC2530.h>
#include<string.h>

#define  LS164_DATA    P1_3
#define  LS164_CLK     P1_2
#define  led1 	P0_1 
#define  led2 	P0_4  
#define  key  	P1_1 
#define  uchar  unsigned char
#define  uint  unsigned int

uint counter=0;
int count = 9;

static uchar LED_Map[] = {0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x00};
//静态全局变量,分别输出的值是0、1、2、3、4、5、6、7、8、9、无显示	

//初始化函数声明
void Init_T1()
{
	P1SEL &= ~0XC0;
	P1DIR = 0XC0;
	
	CLKCONCMD &= ~0X7f;//晶振设置为32HZ
	while(CLKCONSTA & 0x40);//等待晶振稳定
	
	EA=1;//打开中断	
	T1IE=1;//开T1溢出中断
	T1CTL = 0x0F;//启动,设128分频,设正计数/倒计数模式定时模式
	T1CC0H = 0x7A;
	T1CC0L = 0x12;
        //31250*128*(1/32MHZ)=0.125s  (其中62500是——7A12(16进制数)化成的10进制数)
        //故而由于正/倒计数,每周期0.25秒
	
	led1 = 0;//led灯初始化
	led2 = 0;//亮
	
	//初始化P0端口
	P0SEL&=0x12;//led2 led3 P0_1 p0_4为IO
	P0DIR|=0x12;//方向是输出
	P1SEL  &= ~0x0c;//xxxx 00xx  配置为普通IO模式                          
	P1DIR  |= 0x0c;//xxxx 11xx   配置为输出模式 
}

void LS164_BYTE(uchar Index)//数码管显示字形
{   
    uchar  i = 0;
    uchar  Data = LED_Map[Index];
    for(;i<8;i++)
    {
        if(0x80 & Data)
        {
          LS164_DATA = 1;    //传1位数据“1”           
        }
        else
        {
          LS164_DATA = 0;    //传1位数据“0” 
        }
        Data = Data << 1;
        LS164_CLK = 0;
        LS164_CLK = 1;    //时钟形成上升沿
    }
}

void LED_Flash()
{
  if(counter%4==1 || counter%4==2 || counter%4==3)//0.75s
	{
	  led1 = 0;
	  led2 = 0;
	}
	
  else//0.25s
	{
	  led1 = 1;
	  led2 = 1;
	 }
}

#pragma vector = T1_VECTOR
__interrupt void Time1(void)
{
	T1STAT &= ~0X20;
	IRCON = 0x00; //清除中断标志,也可由硬件自动完成	
	if(counter<=40)
	{
		counter++;//4次中断LED闪烁一轮(约为1s)
                LED_Flash();
                if(counter%4 == 0)
                {
                  LS164_BYTE(count--);
                }
	}
	
	else
		counter = 0;//计数清零
}

void main()
{
	Init_T1();	
	while(1)
        {
          if(count !=0 )
          {
            count = 9;
          }
        }
}

Experiment 5:Sleep wake-up experiment

Experimental principle:

1. Sleep timer register

The sleep timer (SLEEP TIMER) of CC2530 is a 24-bit counter that can be used as a wake-up interrupt (only PM0-2). The counting clock of ST is 32.768K, counting up, can be compared with a 24-bit number to generate an interrupt. PM2 is still working and can generate interrupts and trigger DMA. ST0, ST1, and ST2 are readable and writable. These three registers are similar to the BUFFER of the serial port. They are actually two registers. Therefore, in terms of counting, ST (referring to ST0, ST1, ST2, the same below) is not writable, and is called STa here. For setting the comparison number, ST is unreadable, and is called STb. In this case, if you want to achieve scheduled wake-up, you need to use the number difference between STb and STa. The difference of 32768 means waking up once every second, and the difference n*32768 means waking up once every n seconds. n here can be a decimal. In addition, there are two other important registers PCON and SLEEPCMD.

The function of register PCON is to enable different power supply modes, and the function of register SLEEPCMD is to set different power supply modes.

     The system clock used by the sleep timer is low-frequency, and there are two low-frequency oscillators: 32kHz XOSC crystal oscillator and 32kHz RC oscillator. The 32kHz XOSC is used to run at 32768Hz to provide a stable clock signal for the time accuracy required by the system. The 32kHz RC oscillator runs at 32753Hz, and the two 32kHz oscillators run at different times at the same time.

The power supply has 5 different power supply modes, namely active mode, idle mode, PM1, PM2, and PM3. Active mode is a general mode, and PM3 has the lowest power consumption. The impact of different power supply modes on the system is shown in Table 1 below, and the voltage regulator and oscillator selections are given.

Table 1

Active mode: Fully functional mode. The digital core of the regulator is on and either the 16 MHz RC oscillator or the 32 MHz crystal oscillator is running, or both. 32kHz RCOSC oscillator or 32kHz XOSC operation.

Idle mode: Same as active mode except that the CPU core stops running (i.e. idle).

PM1: The digital part of the voltage regulator is on. Neither the 16 MHz RC oscillator nor the 32 MHz crystal oscillator is running, the 32kHz RCOSC oscillator or the 32kHz XOSC is running. The system will go to active mode on reset, external interrupt or sleep timer expiration.

PM2: The digital part of the voltage regulator is on. Neither the 16 MHz RC oscillator nor the 32 MHz crystal oscillator is running, the 32kHz RCOSC oscillator or the 32kHz XOSC is running. The system will go to active mode on reset, external interrupt or sleep timer expiration.  

PM3:The digital core of the voltage regulator is turned off. All oscillators are not running. The system will go to active mode on reset and external interrupt.

 Experiment content: The initial state of D2 and D3 is all off. Use the sleep timer to make the two lights on at the same time for 2 seconds and off for 1 second. (The LED circuit diagram is shown below).

Implementation code:

#include<iocc2530.h>

#define uchar unsigned char
#define uint unsigned int
#define uint32 unsigned long

#define CRYSTAL 0
#define RC 1

#define  LS164_DATA    P1_3
#define  LS164_CLK     P1_2
#define  led1 	P0_1 
#define  led2 	P0_4  
#define  key1  	P1_1 
#define  key2   P2_0

uchar LEDBLINK;
uint time;

//delay()延时函数
void delay(uint n)
{
	uint jj;
	for(jj = 0;jj<n;jj++);
	for(jj = 0;jj<n;jj++);
	for(jj = 0;jj<n;jj++);
	for(jj = 0;jj<n;jj++);
	for(jj = 0;jj<n;jj++);
}

void InitLEDIO()
{
	P0SEL&=0x12;//led2 led3 P0_1 p0_4为IO
	P0DIR |= 0x12;//P0_1\4定义为led输出
	led1 = 1;
	led2 = 1;//led初始时为关
}

//设定系统主时钟函数
void SET_MAIN_CLOCK(uint source)
{
	if(source)
	{
	CLKCONCMD |= 0x40;//x1xx xxxx 选择16MHz RC振荡器,CLKCONCMD是时钟频率控制寄存器
		while(!(CLKCONSTA & 0x40));//16MHz待稳,CLKCONSTA是时间频率状态寄存器
	}
	else
	{
		CLKCONCMD &= ~0x47;//选择32MHz晶振
		while((CLKCONSTA & 0x40));
	}
}

//三目运算实现设定系统低速时钟函数
void  SET_LOW_CLOCK(uint source)
{
	(source == RC)?(CLKCONCMD |= 0x80):(CLKCONCMD &= ~0x80);
	//if(source==RC)
	//CLKCONCMD |= 0x80;
	//else
	//CLKCONCMD &= ~0x80;	//也就是说如果时钟源是RC,那么就将CLKCONCMD寄存器的第7位置1;否则将第7位清零
}


//设置睡眠时间,sec = 1时为一秒
void Set_ST_Period(uint sec)
{
	long sleepTimer = 0;//读睡眠定时器当前值到变量sleepTimer中,先读ST0的值
	sleepTimer |= ST0;
	sleepTimer |= (long)ST1 << 8;
	sleepTimer |= (long)ST2 << 16;
	
	sleepTimer += ((long)sec *(long)32768);//用于确定增加一次的时间
	//睡眠定时器的时钟频率为32.768kHz,故而1s需要增加32 768次
	//将睡眠时间加到sleepTimer上
	
	ST2 = (char) (sleepTimer >> 16);//强制字符,转换右移后的结果
	ST1 = (char) (sleepTimer >> 8);
	ST0 = (char)  sleepTimer;
}

//初始化睡眠定时器
void Init_SLEEP_TIMER()
{
	ST2 = 0x00;
	ST1 = 0x0F;
	ST0 = 0x0F;
	
	EA = 1;//开中断
	STIE = 1;//睡眠定时器中断使能
	STIF = 0;//睡眠定时器状态设置0
}
	
#pragma vector = ST_VECTOR
__interrupt void ST_ISR()
{
	STIF = 0;//清除睡眠定时器标志位
	LEDBLINK = 1;//设置LED1闪烁标志
}




int Time_confirm()//确定睡眠定时器的时间
{
        led1 =! led1;
        led2 =! led2;
	if(led1 == 1 && led2 == 1 )//当灯灭时,返回1,实现1秒灭
	return 1;
	else //当灯亮时,返回2,实现两秒亮
        return 2;
}

void LED_state(uint n)
{
	if(n == 1)//当返回的值为1时,实现灯灭
	{
		led1 = 1;
		led2 = 1;
	} 
	else if(n == 2)//当返回的值为2时,实现灯亮
	{
		led1 = 0;
		led2 = 0;
	}
}

void main(void)
{
	SET_MAIN_CLOCK(CRYSTAL);//设定系统主时钟函数
	SET_LOW_CLOCK(CRYSTAL);//设定系统低速时钟函数
	InitLEDIO();//led灯初始化,两个灯全灭
	LEDBLINK = 0;
	
	Init_SLEEP_TIMER();//初始化睡眠定时器
	time = Time_confirm();
	Set_ST_Period(time);//设置睡眠时间
	while(1)
	{
		if(LEDBLINK)
		{
            LED_state(time);//led灯状态确定
			time = Time_confirm();
			Set_ST_Period(time);
			LEDBLINK = 0;//清除led灯的标志位
		}
		delay(100);//短暂时延,用于缓冲
	}
}

Experiment 6:Temperature and humidity sensor experiment

Experimental principle: Temperature and humidity sensor SHT10 is a temperature and humidity composite sensor with calibrated digital signal output. The sensor includes a capacitive polymer moisture measuring element and a bandgap temperature measuring element, and is seamlessly connected with a 14-bit A/D converter and serial interface circuit on the same chip. Therefore, this product has the advantages of excellent quality, ultra-fast response, strong anti-interference ability, and high cost performance. For detailed operating instructions of SHT10, please refer to its chip data sheet.

Experimental content:Use an experimental board with a temperature and humidity sensor SHT10, and display the measured temperature through the serial port assistant (the temperature value is kept to one decimal place). If the temperature If it exceeds a certain upper limit, the serial port assistant will change the line and display "too high" (LED1 and LED2 flash together, measure the current humidity and retain one decimal place, and display it in the serial port), otherwise the serial port assistant will change the line and display "normal" (it will not be displayed at this time). Display temperature value), all lights go out (the circuit is shown in the figure below)

Implement core code:

#include "ioCC2530.h"     
#define uint8 unsigned char 
#define uint16 unsigned int
#define uint32 unsigned long
#define LED1 P0_0
#define LED2 P2_0 

extern void Sensor_PIN_INT(void);
extern uint32 ReadSHT1(uint8 Addr);


void delay(void)
{
    unsigned int i;
    unsigned char j;

    for(i=0;i<1500;i++)
    {
        for(j=0;j<200;j++)
        {
              asm("NOP");
              asm("NOP");
             asm("NOP");
        }
    }

void UartTX_Send_String(unsigned char *Data,int len)   //串口发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
        U0DBUF = *Data++;   
        while(UTX0IF == 0);
        UTX0IF = 0;
    }
}

void UartTX_Send_Data(unsigned char Data,int len)   //串口发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
        U0DBUF = Data;   
        while(UTX0IF == 0);
        UTX0IF = 0;
    }
}

/*
#pragma vector=URX0_VECTOR   //uart0中断函数
__interrupt void uart0(void){
    URX0IF = 0; //清中断标志
    P0_0=~P0_0;
    uart_buffer = U0DBUF;
    UartTX_Send_Data(uart_buffer,1);
}*/

void main( void )
{     unsigned long lTemp;     float RHTValue;     float wendu;     unsigned char buf[ 9];     unsigned int dbuf;     P0DIR |= 0x01; //Set P0.0 as the output mode; P0.4 and P0.5 as the input mode     P2DIR |= 0x01; //Set P2.0 as the output mode     P0_0 = 1;      P2_0 = 1; / /Turn off LED     CLKCONCMD &= ~0x40;     U0CSR |= 0X40; //Allow reception< /span>     Sensor_PIN_INT();     IEN0 |= 0x84; //Enable total interrupt, receive interrupt           UTX0IF = 1;     U0BAUD |= 216; //The baud rate is set to 57600     PERCFG = 0x00; 0x3c; ;     CLKCONCMD = 0xb8; //TICHSPD is divided by 128, CLKSPD is not divided




















    UartTX_Send_String("Testing...\r\n",12);//Serial port output test signal
    while(1){ 
    lTemp = ReadSHT1(3);//14bit temperature
        lTemp = lTemp >> 8;
        RHTValue = lTemp;
        RHTValue = 0.01 * RHTValue - 39.64;
        wendu = RHTValue;//Assign the data collected by the sensor to the set value
        buf[0] = ( uint8)RHTValue;//Temperature and humidity sensor temperature 
    buf[0] = ( ((buf[0]/10)<<4) + (buf[0]%10) ) ;
        
        buf[1] = (buf[0]>>4)&0xf;
    buf[1] = buf[1] + & #39;0';
        
    buf[2] = (buf[0])&0xf;
    buf[2] = buf[2] + 0 a i=15> dbuf = dbuf%10;         buf[7] = dbuf;         buf[7] = buf[7] +'0& #39;;         /*Decimal part*/         lTemp = ReadSHT1(5);//12bit humidity         lTemp = lTemp > a i=23> //Calculate the corresponding data value by collecting data         buf[3] = (uint8)RHTValue;//Temperature and humidity sensor humidity      buf[ 3] = ( ((buf[3]/10)<<4) + (buf[3]%10) );     buf[4] = (buf[3]> ;>4)&0xf;     buf[4] = buf[4] + '0';     buf[5] = (buf[3])&0xf;     buf[5] = buf[5] + '0';          /* Decimal part*/         dbuf = (uint16)(RHTValue*10);         dbuf = dbuf%10;         buf[ 8] = dbuf;         buf[8] = buf[8] +'0';          /*Decimal part*/          a>          UartTX_Send_String(&buf[7],1);          UartTX_Send_String(".",1);          UartTX_Send_String(&buf[2],1);          UartTX_Send_String(&buf[1],1);          UartTX_Send_String("Temperature = ",14);        {        else        }          UartTX_Send_String("\r\n",2);          UartTX_Send_String(&buf[8],1); UartTX_Send_String(".",1);          UartTX_Send_String(&buf [5],1);          UartTX_Send_String(&buf[4],1);          UartTX_Send_String("humidity = ",11);          UartTX_Send_String(" ",4);          UartTX_Send_String(&buf[7],1);          UartTX_Send_String("." ,1);          UartTX_Send_String(&buf[2],1);          UartTX_Send_String(&buf[1],1);          UartTX_Send_String("Temperature = ",14);          delay();          LED2 = !LED2;          LED1 = !LED1;          delay();          LED2 = !LED2;          LED1 = !LED1;          UartTX_Send_String("   ",4);          UartTX_Send_String("too high",8);        {        if(wendu > 26)
        






        
        





        


    


        


        






        










         






         














         UartTX_Send_String("    ",4);
            
         UartTX_Send_String("humidity = ",11);
         UartTX_Send_String(&buf[4],1);
         UartTX_Send_String(&buf[5],1);
         UartTX_Send_String(".",1);
         UartTX_Send_String(&buf[8],1);
         UartTX_Send_String("\r\n",2);
            
            delay();
       }
        
        delay();
    }


Experiment 7: Ultrasonic ranging experiment

Experimental principle:

The function of the ultrasonic ranging module S906 is to use ultrasonic waves to measure distance. Its effective detection range is 2cm-500cm, the detection accuracy is 3mm, and the working voltage is 5V; the module contains 5 pins, namely VCC, trig (control terminal) , echo (receiving end), out (empty pin), GND. How to use this module is:

1. Use I/O trigger ranging and give a high-level signal for at least 10 microseconds (actually 25 microseconds is optimal)

2. The module automatically sends 8 40Hz square waves and automatically detects whether there is a signal returned.

3. When a signal returns, a high level is output through the I/O. The duration of the high level is the time from emission to return of the ultrasonic wave. The distance tested = (high level time * speed of sound (340m/s)) / 2;

The module is simple to use. Once a control port sends a high level for more than 10 microseconds, you can wait for the high level output at the receiving port. Once there is an output, you can start the timer. When this port becomes low level, You can read the value of the timer, which is the time of this ranging measurement, and then you can calculate the distance. By continuously measuring periodically, you can reach the value of mobile measurement.

Experiment content:Use an experimental board with an ultrasonic sensor, and display the measured distance (in cm) in the serial port assistant. If the distance is less than 10cm, then The serial port displays "L", and D2 and D3 keep flashing; if the distance is higher than 30cm, the serial port displays "H", D2 keeps flashing, the distance is between 10~30cm, the two LEDs are off, and the serial port shows "Normal" (The initial state of D2 and D3 is off, the circuit diagram of the ultrasonic module is shown below)

Implementation code:

#include "ioCC2530.h"
#include<string.h>
   
#define led1 P0_0
#define led2 P2_0//配置灯的端口

unsigned char counter;
unsigned char buf[3];
float distance;
	
void SendASignal()
{
  unsigned char i;
  P1 &= ~(1<<0);//P1_0口先给一个低电平,给出一个至少10μs的高电平
  //P1 |= (1<<0);  
  for(i=0;i<33;i++){
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
    asm("NOP");
  }
 P1 |= (1<<0); //高电平结束
}

 
void delay(void)
{
  unsigned int i;
  unsigned char j;

  for(i=0;i<5000;i++)
  {
    for(j=0;j<200;j++)
    {
      asm("NOP");
      asm("NOP");
      asm("NOP");
    }
  }
}

 
void UartTX_Send_String(unsigned char *Data,int len)   //串口字符串发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
    	U0DBUF = *Data++;   
    	while(UTX0IF == 0);
    	UTX0IF = 0;
    }
}

void UartTX_Send_Data(unsigned char Data,int len)   //串口数据发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
    	U0DBUF = Data;   
    	while(UTX0IF == 0);
    	UTX0IF = 0;
    }
}


#pragma vector=URX0_VECTOR   //uart0中断函数
__interrupt void uart0(void){
    URX0IF = 0; //清中断标志
}

#pragma vector=T1_VECTOR   //定时器1中断函数 50us
__interrupt void Timer1(void){
    counter++;

    //P0_0=~P0_0;
}

void LED_flash()
{
	if(counter<10)
	{
                UartTX_Send_String("L\r\n",3);
		led1 =!led1;
		led2 =!led2;
	}
	else if(counter>30)
	{
                UartTX_Send_String("H\r\n",3);
		led1 =!led1;
	}
	else 
	{
                UartTX_Send_String("Normal\r\n",8);
		led1 = 1;
		led2 = 1;//其他情况全灭
	}
}

void DATA_Init()
{
  P0DIR |= 0x01;  //设置P0.0为输出方式
  P2DIR |= 0x01;  //设置P2.0为输出方式
  P1SEL &= ~((1<<0)|(1<<1));//P1.0,P1.1为GPIO        
  P1DIR |= ((1<<0));        //P1_0为OUTPUT
  P1DIR &= ~(1<<1);         //P1_1为INPUT
  P1 &= ~(1<<0);

  P0_0 = 1; 
  P2_0 = 1;                    //LED初始为灭
  
  
  counter = 0;
  CLKCONCMD &= ~0x40;          //选择32M晶振
  while(CLKCONSTA & 0x40);     //等待XSOC稳定
  CLKCONCMD = 0xb8;            //TICHSPD 128分频,CLKSPD 不分频
  //SLEEPCMD |= 0x04;            //关闭不用的RC 振荡器
  T1CC0L = 6;
  T1CC0H = 0x00;               //比较值
  T1CTL = 0x33;                //通道0,不分频,up/down模式
  PERCFG = 0x00;               //位置1 P0 口
  P0SEL = 0x3c;                //P0 用作串口
  U0CSR |= 0x80;               //UART 方式
  U0GCR |= 10;                 //baud_e = 10;
  U0BAUD |= 216;               //波特率设为57600
  UTX0IF = 1;
  U0CSR |= 0X40;               //允许接收
  IEN0 |= 0x84;                //开总中断,接收中断   
  EA = 1;                      //开总中断
  T1IE = 1;                    //开定时器T1中断
}


void main( void )
{
  
  DATA_Init();
  while(1){        
    P2_0=~P2_0;//led2闪烁
    SendASignal();
    while(1){
      if(P1_1==1) break;
    }
    counter = 0;
    
    while(1){
      if(P1_1==0) break;
    }
    distance = counter;
    distance = (distance*50/1000000*340/2*100);
    counter = (unsigned int)distance;
    //counter保存高电平长度,单位为50us
    buf[0] = counter/100;
    buf[1] = (counter%100)/10;
    buf[2] = (counter%10);
	if(buf[0] > 0x9)
      buf[0] = buf[0] - 0xA + 'A'; 
    else
      buf[0] = buf[0] + '0';		      
    if(buf[1] > 0x9)
      buf[1] = buf[1] -0xA + 'A';
    else
      buf[1] = buf[1] + '0';
    if(buf[2] > 0x9)
      buf[2] = buf[2] -0xA + 'A';
    else
      buf[2] = buf[2] + '0';
    
    LED_flash();
    //D_estimateOutput();//距离测试判断输出
    UartTX_Send_String("Ultrasonic = ",13);
    UartTX_Send_String(&buf[0],1);
    UartTX_Send_String(&buf[1],1);
    UartTX_Send_String(&buf[2],1);
    UartTX_Send_String("cm",2);
    UartTX_Send_String("\r\n",2);
    delay();
  }
} // end of main()

 

Experiment 8:Light sensor experiment

Experimental principle:

The ADC of the CC2530 wireless microcontroller supports up to 14-bit analog-to-digital conversion and includes an analog multiplexer with up to 8 individually configurable channels and a reference voltage generator. The conversion results are written to memory via DMA and also have different operating modes. The block diagram of the ADC module is shown below:

All 8 bits of parallel port P0 can be used for DA conversion. There is also a temperature and humidity sensor inside CC2530, which is also an input for DA conversion. The accuracy of AD conversion can be set from 8 bits to 14 bits. The relevant registers are ADCL, ADCH, ADCCON1 and ADCCON3.

Experiment content:

Use an experiment board with a light sensor to measure the intensity of light. If it is lower than a certain value, the LED will be on, otherwise it will be off. (The circuit diagram is shown below).

Implementation code:

#include "ioCC2530.h"     
#define uint8 unsigned char 
#define uint16 unsigned int
#define uint32 unsigned long
extern void Sensor_PIN_INT(void);
extern uint16 ReadAdcValue(uint8 ChannelNum,uint8 DecimationRate,uint8 RefVoltage);
char uart_buffer;

void delay(void)
{
    unsigned int i;
    unsigned char j;

    for(i=0;i<1500;i++)
    {
    	for(j=0;j<200;j++)
    	{
      	    asm("NOP");
      	    asm("NOP");
     	    asm("NOP");
    	}
    }
} 

void UartTX_Send_String(unsigned char *Data,int len)   //串口发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
    	U0DBUF = *Data++;   
    	while(UTX0IF == 0);
    	UTX0IF = 0;
    }
}

void UartTX_Send_Data(unsigned char Data,int len)   //串口发送函数
{
    int j;
    for(j=0;j<len;j++)
    {
    	U0DBUF = Data;   
    	while(UTX0IF == 0);
    	UTX0IF = 0;
    }
}

#pragma vector=URX0_VECTOR   //uart0中断函数
__interrupt void uart0(void){
    URX0IF = 0; //清中断标志
    P0_0=~P0_0;
    uart_buffer = U0DBUF;

    UartTX_Send_Data(uart_buffer,1);
}

void main( void )
{
    unsigned char buf[8];
    uint16 temp;
    Sensor_PIN_INT();
    
    UartTX_Send_String("Testing...\r\n",12);
    while(1){    		 	
        //P2_0=~P2_0;
        temp = ReadAdcValue(0x1,3,2);//P0.1采集光照度,12bit,AVDD5作为参考
        temp = (temp>>6);
        buf[0] = (uint8)(temp&0xff);
        buf[1] = (buf[0]>>4)&0xf;
        buf[2] =  buf[0]&0xf;
        if(buf[1] > 0x9)
            buf[1] = buf[1] - 0XA + 'A';
	else
	    buf[1] = buf[1] + '0';
        if(buf[2] > 0x9)
            buf[2] = buf[2] - 0XA + 'A';
	else
	    buf[2] = buf[2] + '0';
        if(temp>0x32)//光强是否大于50
        {
          P0_0=0;
          P2_0=0;
        UartTX_Send_String("LIGHT = ",8);
      	UartTX_Send_String(&buf[1],1);
        UartTX_Send_String(&buf[2],1);
	UartTX_Send_String("\r\n",2);	
        }
	else{
          P0_0=1;
          P2_0=1;
        }
    	
    	delay();
    }
} // end of main()

 at last

Finally, the author has something to say:The summary content of the article will be continuously updated. This is also the first article in our Zigbee series, except for The code has nearly 10,000 words written eloquently. I hope it can help everyone! If during the learning process, you encounter a professional term that you don’t understand, or you don’t understand its function, you can leave a message in the comment area,I won’t laugh at you hahahahahahahahahahahahahahaha,< /span>Of course, you are not allowed to cause trouble. Where can I ask the serial port? What... Hahahahahahaha. above! After I see it, I will answer it for you in the "Continuous Update" as quickly as possible.

Guess you like

Origin blog.csdn.net/Uncoverlove/article/details/134087836