Línea directa de servicio
6
Programación de microcontroladores
Existe una gran diferencia entre la programación de microcontroladores y la de PC. Si bien las herramientas de desarrollo de microcontroladores basadas en C son cada vez más populares, para los diseñadores que cuentan con un código de programa eficiente y prefieren usar lenguaje ensamblador, este sigue siendo el lenguaje de programación más conciso y eficaz.
For MCU programming, the basic framework can be said to be roughly the same, which is generally divided into three parts: the initialization part (this is the biggest difference between MCU programming and PC), the main program loop body and the interrupt handler, which are explained as follows:
1. Inicialización:For the design of all MCU programs, initialization is the most basic and important step, which generally includes the following:
Mask all interrupts and initialize the stack pointer:The initialization part generally does not want any interrupts to occur.
Clear the system's RAM area and display Memory:Although sometimes it may not be completely necessary, from the perspective of reliability and consistency, especially to prevent unexpected errors, it is recommended to develop good programming habits.
Initialization of IO port:According to the application requirements of the project, set the input and output mode of the relevant IO port. For the input port, you need to set its pull-up or pull-down resistor; for the output port, you must set its initial level output to prevent unnecessary errors.
Interrupt settings:For all interrupt sources that need to be used in the project, they should be turned on and the trigger conditions for the interrupt should be set, while redundant interrupts that are not used must be turned off.
Initialization of other functional modules:For all peripheral function modules of the MCU that need to be used, the corresponding settings must be made according to the requirements of the project application. For example, for UART communication, the Baud Rate, data length, verification method, and Stop Bit length need to be set. For the Programmer Timer, its clock source, frequency division number, and Reload Data must be set.
Initialization of parameters:After completing the initialization of the MCU hardware and resources, the next step is to initialize some variables and data used in the program. The initialization of this part needs to be designed according to the specific project and the overall arrangement of the program. For some applications that use EEPROM to save project prefabricated data, it is recommended to copy the relevant data to the RAM of the MCU during initialization to improve the program's access speed to data and reduce the power consumption of the system (in principle, accessing external EEPROM will increase the power consumption of the power supply).
2. Main program loop body:Most MCUs run continuously for a long time, so their main program bodies are basically designed in a loop. For applications with multiple working modes, there may be multiple loop bodies, which are converted through status flags. For the main program body, the following modules are generally arranged:
Calculation procedure:Calculation programs are generally time-consuming, so we are firmly opposed to processing them in any interrupt, especially multiplication and division operations.
Procesamiento de programas con requisitos de tiempo real bajos o nulos;
Show transfer procedure:Mainly aimed at applications with external LED and LCD Drivers.
3. Interrupt handler:Interrupt programs are mainly used to handle tasks and events with high real-time requirements, such as detection of external sudden signals, detection and processing of buttons, timing counting, LED display scanning, etc.
Under normal circumstances, the interrupt program should keep the code as concise and short as possible. For functions that do not need to be processed in real time, the trigger flag can be set in the interrupt, and then the main program will perform specific transactions. This is very important, especially for low-power, low-speed MCUs, which must ensure timely response to all interrupts.
4. Para la organización de los diferentes cuerpos de tareas, los distintos microcontroladores tienen diferentes métodos de procesamiento:
Por ejemplo, para aplicaciones de MCU de baja velocidad y bajo consumo (Fosc=32768Hz), considerando que estos proyectos son dispositivos portátiles y utilizan pantallas LCD comunes, la respuesta a las pulsaciones de teclas y la respuesta de la pantalla requieren un alto rendimiento en tiempo real, por lo que generalmente se utilizan interrupciones temporizadas para procesar las pulsaciones de teclas, las acciones y la visualización de datos; para MCU de alta velocidad, como aplicaciones Fosc>1MHz, dado que el MCU tiene tiempo suficiente para ejecutar el cuerpo del bucle del programa principal en este momento, solo puede establecer varios indicadores de disparo en las interrupciones correspondientes y colocar todas las tareas en el cuerpo del programa principal para su ejecución.
5. En la programación de microcontroladores, hay algo que requiere especial atención:
Es necesario evitar que se acceda o modifique la misma variable o dato simultáneamente en los cuerpos del programa principal y de las interrupciones. Un método eficaz consiste en organizar el procesamiento de dichos datos en un módulo y determinar si se deben realizar operaciones relacionadas con ellos mediante el indicador de activación; en otros cuerpos del programa (principalmente interrupciones), solo se activan los indicadores de activación donde se necesite procesar los datos. Esto garantiza que la ejecución de los datos sea predecible y única.
7
Resumen de programación de microcontroladores para ingenieros
1,Develop a good habit of summarizing. Summarizing is not only a summary of your own learning, but also a review and deepening of the learning process. It can also avoid making mistakes the second time.
2,Before writing a program, you must first have a familiar understanding of the project, be aware of it, and outline a general framework. It is very important to carefully consider how to lay out and what is the most reasonable layout. It is necessary to analyze which module to do first, the specific steps of this module, how to name each function, the connection with other modules, etc. It’s a good idea to get a piece of paper and jot down important processes.
3,For modular programming in C language, you must first divide each module, program module by module, determine a sequence, follow the sequence, and then write the next module after the module is successful. For header files, write the module's header file after the module is written.
4,Do not ignore warnings when they appear. It means that there must be something unreasonable about the program. It is necessary to understand its source and find a solution. Be specific when looking for sources. You can search the Internet for information in this area, or ask others for advice. For example, the main function in another project was actually added to this project. There are actually duplicate function names. There are also reasons to analyze the experimental phenomena and progress step by step. There was also the wrong interface selected when defining the port. Sometimes, it’s good to take a break and think about it if you really can’t solve it. No matter how simple it is, you should pay attention to it, as there may be mistakes.
En el desarrollo de aplicaciones para microcontroladores, persisten problemas como la eficiencia en el uso del código, el rendimiento frente a interferencias y la fiabilidad. A continuación, resumimos algunas habilidades básicas que deben dominarse en el desarrollo de microcontroladores.
8
Habilidades de desarrollo de microcontroladores
1.How to reduce bugs in programs
En cuanto a cómo reducir los errores del programa, primero debe considerar los siguientes parámetros de administración fuera de rango que deben tenerse en cuenta durante el funcionamiento del sistema.
-
Parámetros físicos: Estos parámetros son principalmente parámetros de entrada del sistema, que incluyen parámetros de excitación, parámetros de funcionamiento durante el procesamiento de adquisición y parámetros de resultado al final del procesamiento.
-
Parámetros de recursos: Estos parámetros son principalmente los recursos de los circuitos, dispositivos y unidades funcionales del sistema, como la capacidad de memoria, la longitud de la unidad de almacenamiento y la profundidad de apilamiento.
-
Parámetros de aplicación: Estos parámetros suelen aparecer como condiciones de uso de algunos microcontroladores y unidades funcionales. Parámetros de proceso: Se refieren a los parámetros que cambian de forma ordenada durante el funcionamiento del sistema.
2.How to improve the efficiency of C language programming code
El uso del lenguaje C para la programación de microcontroladores es una tendencia inevitable en el desarrollo y la aplicación de estos. Para lograr la máxima eficiencia al programar en C, es fundamental familiarizarse con el compilador que se utiliza. Primero, se debe probar la cantidad de líneas de instrucciones en lenguaje ensamblador que genera cada compilación en C, para así determinar su eficiencia. Al programar en el futuro, se debe usar la instrucción con la mayor eficiencia de compilación. Cada compilador de C presenta diferencias, por lo que la eficiencia de compilación también varía. La longitud del código y el tiempo de ejecución de un excelente compilador de C para sistemas embebidos son solo entre un 5 % y un 20 % mayores que los de la misma función escrita en lenguaje ensamblador.
Para proyectos complejos con plazos de desarrollo ajustados, se puede utilizar el lenguaje C, pero es imprescindible tener un conocimiento profundo del lenguaje C y del compilador del sistema MCU. Preste especial atención a los tipos de datos y algoritmos compatibles con el sistema de compilación de C. Si bien C es el lenguaje de alto nivel más común, los distintos fabricantes de MCU utilizan sistemas de compilación de C diferentes, especialmente en lo que respecta al funcionamiento de algunos módulos de funciones especiales. Por lo tanto, si no comprende estas características, surgirán numerosos problemas durante la depuración, lo que resultará en una menor eficiencia de ejecución que con el lenguaje ensamblador.
3.How to solve the anti-interference problem of microcontrollerLa forma más eficaz de prevenir las interferencias es eliminar la fuente de interferencia y bloquear su trayectoria, pero esto suele ser difícil. Por lo tanto, solo podemos comprobar si la capacidad antiinterferencias del microcontrolador es lo suficientemente robusta. Si bien se está mejorando la capacidad antiinterferencias de los sistemas de hardware, la protección antiinterferencias por software está ganando cada vez más atención debido a su diseño flexible, el ahorro de recursos de hardware y su buena fiabilidad.
El fenómeno más común de interferencia en microcontroladores es el reinicio. En caso de que el programa se descontrole, se pueden usar trampas de software y temporizadores de vigilancia para devolverlo al estado de reinicio. Por lo tanto, lo más importante para que el software del microcontrolador resista la interferencia es gestionar el estado de reinicio.
Generalmente, los microcontroladores cuentan con registros de indicadores que permiten determinar la causa del reinicio. Además, también es posible almacenar indicadores en la memoria RAM. Cada vez que se reinicia el programa, se pueden identificar diferentes causas de reinicio analizando estos indicadores. Asimismo, se puede acceder directamente al programa correspondiente según dichos indicadores. Esto permite que el programa se ejecute de forma continua, sin que el usuario note el reinicio.
4.How to test the reliability of microcontroller systemCuando se completa el diseño de un sistema de microcontrolador, habrá diferentes elementos y métodos de prueba para los diferentes productos del sistema de microcontrolador, pero algunos deben ser probados:
- Comprueba la integridad de la función del software del microcontrolador.
- Prueba de encendido y apagado
- Test de envejecimiento
- Pruebas como ESD y EFT
En ocasiones, también podemos simular los daños que podrían producirse durante el uso humano. Por ejemplo, frotar deliberadamente el puerto de contacto del sistema microcontrolador con el cuerpo humano o con la ropa para comprobar su capacidad antiestática. Utilizar un taladro eléctrico de alta potencia cerca del sistema microcontrolador para comprobar su resistencia a las interferencias electromagnéticas.
In summary, single-chip microcomputer has become an important aspect of computer development and application. The important significance of single-chip microcomputer application is that it fundamentally changes the traditional control system design ideas and design methods.
Most functions that previously had to be implemented by analog circuits or digital circuits can now be implemented through software methods using microcontrollers. This kind of control technology in which software replaces hardware is also called micro-control technology, which is a revolution in traditional control technology.
Además, durante el proceso de desarrollo y aplicación, debemos dominar ciertas habilidades y mejorar la eficiencia para que pueda utilizarse para una gama más amplia de propósitos.
9
Resumen del funcionamiento del chip
Las operaciones en el chip se centran principalmente en los registros del mismo. Estos registros tienen direcciones únicas asignadas en la memoria, y cada dirección se opera sobre la dirección correspondiente. Al analizar el chip, primero se debe examinar el diagrama de temporización, luego comprender los registros correspondientes, entender su funcionamiento, definir los puertos necesarios (que el programa puede identificar) y escribir los procedimientos de lectura y escritura.
Cómo escribir datos en el chip, cómo leer datos y por qué puerto introducir o leer (lo más importante).
Al conectar chips a través de un bus, primero debe comprender el protocolo de dicho bus. El chip conectado al bus I2C controla principalmente a los demás chips a través de este bus.
1,One 74hc595 in the lattice is used for column selection, and the other two are used for color selection. The lattice is equivalent to a collection of diodes,
El diodo solo se enciende cuando un extremo recibe un nivel alto y el otro un nivel bajo. Simplemente, al seleccionar un extremo de forma diferente, se iluminan colores distintos.
Selección del modo de funcionamiento del temporizador: Los cuatro bits superiores configuran el temporizador T1, y los cuatro inferiores, T0. Los dos últimos dígitos de cada modo configuran el modo de funcionamiento. Al configurar dos temporizadores, tenga cuidado al usar el operador OR (|). Al usar interrupciones, preste atención a borrar las que deban borrarse después de que se produzca la interrupción.
2,Serial port transceiver: The baud rate is generally set in mode 2 (automatic reloading to initial value). Because different devices have different data processing capabilities, setting the baud rate is mainly to take care of low-speed devices and to communicate with each other. The interrupt flag bit must be cleared by software. When setting the serial port interrupt, no matter which one is generated by sending or receiving, it can enter the interrupt function, so pay attention to setting the interrupt function. (Self-feeling generally sets a function, as a host computer or a slave computer).
Si utilizas una interrupción para enviar datos, primero debes averiguar cómo acceder a ella. Para ello, primero debes enviar el mensaje una vez y luego podrás acceder a la interrupción. Solo se puede enviar un byte a la vez, y el siguiente bit solo se puede enviar después de que se active la interrupción (TI).
3,Pcf8591ad conversion has four channels of input. When reading pcf8591, which channel is selected, the voltage input by that channel is read. The converted data is stored in the chip and then read out. When reading, first write the address of the chip, then write the sub-address of the device (0x40|channel number), and then the read data.
4,Da conversion is to first write the device address into the chip, then write the sub-address (0x40), and then write the digital quantity to be converted. Device address chip information is introduced.
5,For the LCD display, after the data is written and displayed, it will always be displayed without continuous refresh. If you want to change it, you can only re-enter it.
6,For the ds1302 clock chip, when reading data, the first data is read at the falling edge of the eighth clock when writing data, and then prepares for the next output. Pay attention to the writing method of the program and the location of the return value.
7,In Ds1302, first specify the register and then write data to it. The register on the chip data indicates the address. (I still don’t quite understand the write protection program. Isn’t there always writing? Why is the write protection still turned on?)
(According to the previous hero, you can set a flag after the initialization time. If there is this flag, there is no need to initialize the time. However, if the power is turned off, the MCU's RAM cannot save this flag, so you can use the DS1302's RAM to save the flag, and read the flag after powering on. I am also a beginner, and I plan to use DS1302 recently. I don't know if this is correct, and I haven't implemented it yet. Please share more)
8,It is best to write down the initialization in case you forget it later. Sometimes pay attention to whether the lowest bit or the highest bit is operated first when reading or writing, which can be judged according to the timing diagram.
9,For infrared transceiver, when receiving, it determines whether it is a high level or a low level based on the time between two falling edges. When writing a program, first use a timer to determine the time, save it, and then convert it into binary (read more about how to write this program, it is very good).
10,Stepper motor: Mainly used for switching. The torque of the stepper motor decreases as the rotational speed increases. It is mainly used for automatic feeding of parts processed on machine tools. It can also be used in control places with higher precision.
Stepper motor is an open-loop control element stepper motor device that converts electrical pulse signals into angular displacement or linear displacement. Under non-overload conditions, the motor's speed and stop position only depend on the frequency and number of pulses of the pulse signal, and are not affected by load changes. When the stepper driver receives a pulse signal, it drives the stepper motor to rotate in the set direction at a fixed angle, called the "step angle". Its rotation runs step by step at a fixed angle. The angular displacement can be controlled by controlling the number of pulses to achieve accurate positioning; at the same time, the speed and acceleration of the motor rotation can be controlled by controlling the pulse frequency to achieve speed regulation.
11,Servo motor: (servo motor) refers to the engine that controls the operation of mechanical components in the servo system. It is an indirect transmission device that assists the motor. Servo motors can control speed and position accuracy very accurately, and can convert voltage signals into torque and rotational speed to drive control objects. The rotor speed of the servo motor is controlled by the input signal and can respond quickly. In the automatic control system, it is used as an actuator and has the characteristics of small electromechanical time constant, high linearity, starting voltage, etc. It can convert the received electrical signal into the angular displacement or angular velocity output on the motor shaft. They are divided into two categories: DC and AC servo motors. Their main feature is that there is no rotation when the signal voltage is zero, and the rotational speed decreases at a constant speed as the torque increases. DC motor: Large range, all on small cars.
Disclaimer: This article is reproduced from "International Electronic Business Information". This article only represents the author's personal views and does not represent the views of Sacco Micro and the industry. It is only for reprinting and sharing and supports the protection of intellectual property rights. Please indicate the original source and author for reprinting. If there is any infringement, please contact us to delete it.
Número de teléfono de la empresa: +86-0755-83044319
Fax/FAX: +86-0755-83975897
Correo electrónico: 1615456225@qq.com
Pregunta: 3518641314 Gerente Li
Pregunta: 332496225 Gerente Qiu
Dirección: Habitación 809, Edificio C, Edificio de Tecnología Zhantao, Avenida Minzhi n.° 1079, Nuevo Distrito de Longhua, Shenzhen




粤公网安备44030002007346号