Горячая линия обслуживания
6
Программирование микроконтроллеров
Между написанием программ для микроконтроллеров и программ для ПК существует большая разница. Хотя инструменты разработки для микроконтроллеров на языке C становятся все более популярными, для разработчиков, которым нужен эффективный программный код и которые предпочитают использовать ассемблер, язык ассемблера по-прежнему остается наиболее лаконичным и эффективным языком программирования.
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. Инициализация: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 programs are generally time-consuming, so we are firmly opposed to processing them in any interrupt, especially multiplication and division operations.
Обработка программ с низкими или нулевыми требованиями к реальному времени;
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. Для организации различных задач разные микроконтроллеры используют разные методы обработки:
Например, для приложений с низкоскоростными и маломощными микроконтроллерами (Fosc=32768 Гц), учитывая, что такие проекты представляют собой портативные устройства с обычными ЖК-дисплеями, требуется высокая производительность в реальном времени при обработке нажатий клавиш и отображении данных, поэтому для обработки нажатий клавиш, действий и отображения данных обычно используются прерывания по таймеру; для приложений с высокоскоростными микроконтроллерами, такими как приложения с Fosc>1 МГц, поскольку у микроконтроллера достаточно времени для выполнения основного цикла программы, он может только устанавливать различные флаги запуска в соответствующих прерываниях и передавать все задачи в основной цикл программы для выполнения.
5. При программировании микроконтроллеров особое внимание следует уделить следующим моментам:
Необходимо предотвратить одновременный доступ к одной и той же переменной или данным в теле прерывания и в основной программе. Эффективным методом предотвращения является организация обработки таких данных в отдельном модуле, определяя необходимость выполнения соответствующих операций с данными по флагу запуска; в других частях программы (в основном, в прерываниях) флаги запуска следует устанавливать только там, где данные необходимо обработать. — Это гарантирует предсказуемость и уникальность выполнения данных.
7
Краткое изложение программирования микроконтроллеров от инженера
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.
В разработке приложений на микроконтроллерах по-прежнему остаются актуальными такие проблемы, как эффективность использования кода, помехоустойчивость и надежность микроконтроллеров. В данной статье мы обобщим несколько основных навыков, которые необходимо освоить при разработке микроконтроллеров.
8
Навыки разработки микроконтроллеров
1.How to reduce bugs in programs
Что касается способов уменьшения количества программных ошибок, в первую очередь следует рассмотреть следующие параметры управления, выходящие за пределы допустимого диапазона, которые необходимо учитывать во время работы системы.
-
Физические параметры: Эти параметры в основном являются входными параметрами системы, которые включают параметры возбуждения, рабочие параметры в процессе сбора данных и параметры результата в конце обработки.
-
Параметры ресурсов: Эти параметры в основном представляют собой ресурсы схем, устройств и функциональных блоков в системе, такие как объем памяти, длина блока хранения и глубина стекирования.
-
Параметры приложения: Эти параметры приложения часто представляют собой условия работы некоторых микроконтроллеров и функциональных блоков. Параметры процесса: относятся к параметрам, которые упорядоченно изменяются в процессе работы системы.
2.How to improve the efficiency of C language programming code
Использование языка C для программирования микроконтроллеров — неизбежная тенденция в разработке и применении микроконтроллеров. Для достижения максимальной эффективности при программировании на C лучше всего ознакомиться с используемым компилятором C. Сначала протестируйте количество строк операторов ассемблера, соответствующих каждой компиляции на языке C, чтобы четко определить эффективность. В дальнейшем при программировании используйте оператор с наибольшей эффективностью компиляции. Каждый компилятор C имеет свои особенности, поэтому и эффективность компиляции будет разной. Длина кода и время выполнения отличного компилятора C для встроенных систем всего на 5-20% больше, чем у той же функции, написанной на языке ассемблера.
Для сложных проектов с ограниченными сроками разработки можно использовать язык C, но обязательным условием является хорошее знание языка C и компилятора C, используемого в системе микроконтроллера. Особое внимание следует уделить типам данных и алгоритмам, поддерживаемым системой компиляции C. Хотя язык C является наиболее распространенным языком высокого уровня, разные производители микроконтроллеров используют разные системы компиляции C, особенно в работе некоторых специализированных функциональных модулей. Поэтому, если вы не понимаете эти особенности, во время отладки возникнет множество проблем, что приведет к снижению эффективности выполнения по сравнению с языком ассемблера.
3.How to solve the anti-interference problem of microcontrollerНаиболее эффективный способ предотвращения помех — это устранение источника помех и блокирование пути их распространения, но зачастую это сложно сделать, поэтому мы можем лишь оценить, достаточно ли сильна помехоустойчивость микроконтроллера. При повышении помехоустойчивости аппаратных систем всё больше внимания уделяется программной защите от помех благодаря её гибкости, экономии аппаратных ресурсов и высокой надёжности.
Наиболее распространенным явлением помех в работе микроконтроллеров является сброс. Что касается выхода программы из-под контроля, то для возвращения программы в состояние сброса могут использоваться программные ловушки и сторожевые таймеры. Поэтому важнейшая задача программного обеспечения микроконтроллера для противодействия помехам — это обработка состояния сброса.
Как правило, микроконтроллеры имеют регистры флагов, которые можно использовать для определения причины сброса; кроме того, можно также самостоятельно разместить некоторые флаги в оперативной памяти. При каждом сбросе программы можно определить различные причины сброса, оценивая эти флаги; также можно перейти непосредственно к соответствующей программе на основе различных флагов. Это позволяет программе работать непрерывно, и пользователь не заметит, что программа была сброшена, во время её использования.
4.How to test the reliability of microcontroller systemПосле завершения проектирования микроконтроллерной системы для разных типов микроконтроллерных систем будут разработаны различные методы и инструменты тестирования, но некоторые из них обязательно должны быть протестированы:
- Проверьте полноту работы программного обеспечения микроконтроллера.
- Тест включения и выключения питания
- Тест на старение
- Тесты, такие как ESD и EFT.
Иногда мы можем также имитировать повреждения, которые могут возникнуть в процессе эксплуатации. Например, намеренно потереть контактный порт микроконтроллерной системы о тело человека или ткань одежды, чтобы проверить антистатические свойства. Или использовать мощную электродрель, работая вблизи микроконтроллерной системы, чтобы проверить ее устойчивость к электромагнитным помехам.
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.
Кроме того, в процессе разработки и применения необходимо совершенствовать навыки и повышать эффективность, чтобы продукт можно было использовать для более широкого круга целей.
9
Краткое описание работы микросхемы
Основные операции на микросхеме — это операции над регистрами. Регистры имеют свои уникальные адреса, отображаемые в памяти, и операция выполняется над соответствующим адресом. При изучении микросхемы сначала следует посмотреть на временную диаграмму, затем понять, как работают соответствующие регистры, определить необходимые порты (которые могут быть идентифицированы программой), а также процедуры записи и чтения.
Как записывать данные в микросхему, как считывать данные и через какой порт вводить или считывать (самое важное).
При подключении микросхем через шину необходимо сначала понять протокол этой шины. Микросхема, подключенная к шине I2C, в основном управляет другими микросхемами через эту шину.
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,
Диод загорается только тогда, когда на один конец подается высокий уровень сигнала, а на другой — низкий. Просто при изменении напряжения на одном конце загораются разные цвета.
Выбор режима работы таймера: старшие четыре бита устанавливают таймер T1, а младшие четыре бита — T0. Затем последние две цифры каждого режима определяют режим работы. При установке двух таймеров следует использовать оператор ИЛИ (|). При использовании прерываний необходимо следить за сбросом тех прерываний, которые должны быть сброшены после их срабатывания.
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).
Если вы используете прерывание для отправки данных, вам нужно выяснить, как впервые активировать прерывание, поэтому сначала необходимо отправить его один раз, а затем можно активировать прерывание. За один раз можно отправить только один байт, и следующий бит можно отправить только после установки 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.
Номер телефона компании: +86-0755-83044319
Факс: +86-0755-83975897
Почта: 1615456225@qq.com
QQ: 3518641314 Менеджер Ли
QQ: 332496225 Менеджер Цю
Адрес: Комната 809, корпус C, технологический корпус Чжаньтао, проспект Миньчжи, 1079, новый район Лунхуа, Шэньчжэнь.




粤公网安备44030002007346号