SSP-based 1-Wire implementations
How to make steam from stone, our doctor Gaspar knows
When choosing a MK, it is often necessary to pay attention to the presence in its composition of a specific set of peripheral devices for a specific task. Meanwhile, a number of standard buses can be implemented on the basis of other interfaces available in the already used MK. In this post, I will show how to use the hardware 1-Wire interface based on the existing SSP interface that is absent in the 1986VIE1T MK, and this experience can be transferred to other MKs from other manufacturers of the same architecture.
First, a brief description of the microcontroller used. MK 1986BE1T manufactured by Milander is a very good device, the advantages of which are not limited to the fact that it is a domestic product (although this parameter was decisive for the author). Indeed, a MC with a Cortex-M1 core with a clock frequency of up to 140 MHz is an infrequent market participant, and given the presence of a large number of various interfaces, an expanded temperature range, and the availability of a version with VP, this MK becomes an almost unique offer. At the same time, it is necessary to note a number of properties that reduce the attractiveness of this MK for widespread use, namely: high price,
Here are the main characteristics of this MK:
CORTEX-M1 core (with slight restrictions);
clock frequency - up to 144 MHz (for frequencies above 25 MHz, delays are introduced when reading the program memory, which reduces the real speed to the equivalent of 100 MHz);
program memory - 128 Kb, data memory - 48 Kb;
both types of memory are easily expandable through the built-in 32-bit external system bus controller (which requires a significant number of external pins);
advanced clock system with two internal oscillators (not too precise), the ability to connect external quartz resonators and built-in PLL;
non-volatile memory (12 * 4 bytes) and a real-time clock (with external battery power);
8 * 12 bits ADC, 2 * 12 bits DAC, 8 timers with PWM mode;
32x channel RAP;
and a rich set of peripherals proper - 2 * CAN, GOST 18977, 2 * GOST R-52070, Ethernet 10/100 (with built-in PHY!), USB Host / Device, 2 * UART (with built-in IRDA), 3 * SSP;
up to 96 user configurable legs;
the ability to program and debug from under common programming environments (the author prefers IAR) through SWD and JTAG.
In general, the crystal is quite decent, see the manufacturer’s website for more information. Among the shortcomings of the equipment, the author would note the undeveloped interrupt apparatus for external events (external interrupts can only arrive at a small number of predefined conclusions), which limits the developer’s capabilities.
Another “hero” of this article is the 1-Wire interface. The interface is not standardized, it is the property of Dallas Semiconductor, it is widely known, it is used to interact with low-speed devices, among which i-Button identification keys and various temperature sensors are especially known, the bus topology is a star with individual addressing, the exchange speed is up to 15 Kbps, number of wires - 2, a more detailed specification is available on the company's website. Many microcontrollers have a hardware implementation of this interface, however, the MK in question does not apply to those. Therefore, we will consider the possibilities of implementing the interface using standard peripheral devices MK 986BE.
First of all, we need an implementation of layer 1 of the OSI model — the physical interface. From this point of view, the interface is completely uncomplicated - an earth wire and 1 wire are required, through which two-way interaction of devices is carried out and optionally power is transferred to the terminal device. To implement the information wire, an MK output with an open collector and a pull-up resistor with a nominal value of 5 Kom are required. All outputs of the used MK are configurable and can be equipped with built-in pull-up and down resistors (for more information, refer to the description of the MK). The values of the built-in resistors differ from the required ones (according to rumors, they are about 10 Kom - rumored, because NO documentation is given in the documentation), however, for the case with one source of information, it is possible to use built-in resistors, if necessary, it is easy to add an external resistor connected to the appropriate power supply. Among the acceptable configurations of MK terminals there is also an open drain output mode, which meets the interface requirements. Thus, the fundamental impossibility of the physical implementation of the interface was not found.
In the interaction of the master (and we implement it) with the slave, the active zero level is used, supplied in the form of pulses of various durations. 3 main pulse durations are used, namely:
a reset pulse with a duration of at least 480 μs, a transmission pulse of a unit of 1 to 15 μs duration (the same pulse is used to synchronize reading), a zero transmission pulse of 15 to 60 μs of duration. The protective interval between pulses should be at least 1 μs, the pulse duration with a protective interval should be from 60 to 120 μs. It should be noted here that if the requirements of the minimum duration are clear from the point of view of ignoring interference, then the limitation of bit intervals from above is not so obvious and is not dictated by the logic of the devices. Nevertheless, the restrictions are clearly spelled out and must be respected accordingly. When the slave interacts with the master, 2 types of pulses are used, namely: a presence pulse in the form of zero in response to a reset pulse with a delay relative to the termination of the latter from 15 to 60 μs and a duration of from 60 to 240 μs, and a zero transmission pulse issued in response to a read pulse with a delay relative to the beginning of the last not more than 1 μs and a duration from 15 to 60 microseconds (in the documentation for the interface, the requirement is set to EXACTLY 15 microseconds with a subsequent delay for the removal of a pulse from 0 to 45 microseconds - it is strange somehow written). The general conclusion from the above is that for the implementation of the 1-Wire interface, it is necessary to maintain time intervals with an accuracy of about 10 μs with restrictions from above and below. issued in response to a read impulse with a delay relative to the beginning of the last not more than 1 microsecond and duration from 15 to 60 microseconds (in the documentation for the interface, a requirement of exactly 15 microseconds with a subsequent delay to remove the pulse from 0 to 45 microseconds is established - it is strange somehow ) The general conclusion from the above is that for the implementation of the 1-Wire interface, it is necessary to maintain time intervals with an accuracy of about 10 μs with restrictions from above and below. issued in response to a read impulse with a delay relative to the beginning of the last not more than 1 microsecond and duration from 15 to 60 microseconds (in the documentation for the interface, a requirement of exactly 15 microseconds with a subsequent delay to remove the pulse from 0 to 45 microseconds is established - it is strange somehow ) The general conclusion from the above is that for the implementation of the 1-Wire interface, it is necessary to maintain time intervals with an accuracy of about 10 μs with restrictions from above and below.
An obvious implementation of this protocol can be based on direct control of the output port, configured in open source mode and connected by a pull-up resistor. For example, the implementation of a reset pulse with a presence pulse presence control can be represented by the following pseudo-code:
выдать на выход активный уровень (установить 0),
выполнить задержку 500 мксек,
снять активный уровень (установить 1),
на протяжении 15 мксек :
если есть 0 – завершение - ошибка протокола (неисправность),
на протяжении 45 мксек:
если есть 0 – перейти к ИМП::
завершение - ошибка протокола (отсутствие активных устройств),
ИМП:: на протяжении 60 мксек:
если есть 1- завершение - ошибка протокола (неисправность устройства),
на протяжении 180 мксек:
если есть 1- перейти к НОРМ::
завершение - ошибка протокола (неисправность устройства),
НОРМ:: завершение - устройство обнаружено.
In fact, even this procedure should be more difficult to exclude the influence of pulsed noise, but for the purposes of this article some simplifications are permissible.
Similar procedures can be implemented for the remaining pulses. Now consider the disadvantages of this option: the
lack of software implementation of the delays - the dependence of the received time interval on the clock frequency of the MK and the execution time of individual commands, and in the conditions of introducing delays in reading the program memory, the latter become almost indefinite)
and even if we overcame the first drawback by fine-tuning, then in the conditions of functioning together with other modules within the framework of RTOS or in the presence of interruptions (and they will almost always be, we are not writing a spherical program in a vacuum), the obtained time intervals can be much longer (but not shorter) than expected.
Since the interface is very time-dependent and the required accuracy is significant - 10 microseconds is not so much even on fast MKs, with a high probability we will receive chaotic failures when trying to communicate with devices on the 1-Wire bus. Although higher-level protocols can detect such failures due to coding redundancy, it is not possible to recommend such an implementation method. To deal with such errors, it is necessary within the critical sections (and in the above algorithm all operations) to prohibit interrupts and block the ability to switch tasks for a sufficiently long time, which is not a good programming style.
A variant of this implementation may be the use of one of the general purpose timers or the system timer to form the necessary time intervals. If you take into account delays in overhead costs, then you can pretty accurately maintain the timing chart and eliminate the first drawback of the above implementation. Nevertheless, the second drawback is fundamentally unrecoverable within the framework of the decision made, since in all RTOS (or in the presence of interruptions) it is possible to guarantee only that the ordered event will not occur before the specified time, but restrictions from above are impossible.
So, for the implementation of the 1-Wire interface, we need the ability to output time intervals that are strictly limited at the top and bottom and the ability to monitor the state of the MK terminals at precisely specified time intervals. MK has such an opportunity with developed timers (including hardware state machines), but the MK under consideration is not one of them. It is also possible to use hardware-implemented serial interfaces, which we will do. There are a lot of serial interfaces implemented in MK, however, not all of them can be used for our purposes. For example, the USB interface operates at a fixed frequency and its hardware is rigidly attached to the protocol, so it is hardly possible to substantially modify it for our purposes, which also applies to CAN and GOST. With UART, the situation is much better its speed can be changed over a wide range, and the presence of a start bit is not an obstacle, since any pulse starts from an active level, and the presence of a stop bit can be taken into account when calculating the time parameters. The only significant limitation is the mismatch of active levels, which can be eliminated by the introduction of a matching element. But, since all 2 UARTs were occupied for other tasks, such a solution was not worked out.
As a result, it was decided to implement a 1-Wire interface based on one of three universal modules of synchronous serial communication SSP. A detailed description of the capabilities of these modules can be found in the documentation of the manufacturer MK. In short, these modules allow you to synchronize with the clock frequency of the module generated inside the MK, to issue information to the output port with a serial code and simultaneously receive information on the input port of MK with reference to the above frequency. At the same time, to organize a two-way exchange, we will use the output and input of the module data connected together, but we will not use the signals on the clock and synchronization lines and can be used as general-purpose lines, which is allowed by the flexible MK pin configuration system. It is supposed to use the transmitted byte to encode time intervals associated with the transmission / reception of one bit, while the values of the byte bits will determine the duration of the active level (bit 0) and its absence (bit1). When determining the SSP settings, it should be taken into account that the minimum transmitted interval should be from 1 to 15 μs, and the maximum counted interval should be from 60 to 120 μs for information bits and not less than 480 for a reset signal. If you select 10 microseconds as the minimum interval, then the first condition is satisfied, and the duration of the bit interval is 6-12 minimum intervals, and the figure 8 fits well into this range. Then the duration of the reset signal will be at least 48 cycles, which exceeds the number of bits in a byte. To solve the last question, you should either change the duration of the minimum interval, or use more than 1 byte of information to transmit the pulse. The latter method could create a problem with the uncertainty of the intervals between transmissions of individual bytes of the packet and, accordingly, the duration of the resulting pulse could increase unpredictably. Fortunately, the SSP module is equipped with an 8 16-bit FIFO buffer, so the final buffer length of 16 * 8 = 128 bits overlaps the required minimum possible sequence length of 480 + 60 + 240 = 780/10 = 78 bits. the duration of the resulting pulse could increase unpredictably. Fortunately, the SSP module is equipped with an 8 16-bit FIFO buffer, so the final buffer length of 16 * 8 = 128 bits overlaps the required minimum possible sequence length of 480 + 60 + 240 = 780/10 = 78 bits. the duration of the resulting pulse could increase unpredictably. Fortunately, the SSP module is equipped with an 8 16-bit FIFO buffer, so the final buffer length of 16 * 8 = 128 bits overlaps the required minimum possible sequence length of 480 + 60 + 240 = 780/10 = 78 bits.
Thus, the following algorithm for working with SSP is built: configure the necessary mode and the desired transmission frequency, prohibit the operation of the transmitter, fill the transmitter buffer with information to provide the required time intervals, enable the transmitter. The module starts transmitting information with a serial code along the output data line, at the end of the transmission, the ready flag is raised, which serves as an MK signal that it is possible to form the next batch of data. In this case, the time diagram of the transmitted signal is rigidly tied to the module clock frequency, which depends only on the MK clock frequency and cannot be changed in any way, no matter what programs are executed at that moment. Moreover, between the transmission of individual bytes of the sequence there can only be intervals determined by the equipment, which can be taken into account when forming the sequence (studies have shown that such intervals can be eliminated). Consider the process of configuring the SSP module.
SSP module can operate in three modes -
Motorola's SPI interface;
Texas Instruments SSI
National Semiconductor Microwire interface.
Of these three modes, the latter is not suitable, since it imposes additional requirements on the signal format, the first two look equivalent, before we begin to examine them on an oscilloscope. Here it turns out that the SPI mode is characterized by 1-bit delays between the transmission of neighboring words, which serves to transmit a synchronization signal that we do not use. This would not be so important, since it would increase slightly the inter-bit intervals if at these moments 0 did not appear on the data line, which is completely unacceptable according to the requirements of 1-Wire.

Figure 1. False pulses in SPI mode
It is very fortunate that the SSI mode is devoid of such a drawback, otherwise it would have to significantly complicate the program. Studies have shown that in SSI mode, word intervals are simply absent (the synchronization pulse is transmitted during the last bit) and, accordingly, there are no "gaps" on the transmission line. It should be noted that at the time of configuration on the transmission and synchronization lines there is an undocumented change in signal levels, but they do not affect this implementation, since work with the device after setting up the SSP module still starts with a reset pulse that will suppress any consequences of these emissions.

Figure 2. False pulses at the time of SSI enable
Since the problem was solved in an easy way, they did not look for the cause of the emissions, although for applications that use the real SSI mode, I would have to understand it. In the above waveforms, the following reference signal corresponding to pattern 0xBF81 was applied.

Figure 3. Signal without false pulses.
In all figures, the upper signal (yellow) is the data line, the lower signal (blue) in Figures 1 and 3 is the clock frequency line, and in Figure 2 is the synchronization line. The lower signal in the implementation of the interface is not used and is given in the reference order to determine the time intervals.
Thus, the transmission of the reset pulse and the presence of the presence pulse can be represented by the following pseudo-code:
запретить работу передатчика;
загрузить буфер последовательностью 0хF800 0х0000 0х0000 0х01FF 0xFFFF 0xFFFF
// (50 мксек пауза, 500 мксек импульс, 410 мксек пауза для приема ответа);
разрешить работу передатчика;
ждать флага "устройство свободно";
прочитать содержимое буфера приема;
если прочитано не 6 слов – завершение – ошибка SSP;
сравнить принятую информацию с паттерном 0xF800 0x0000 0x0000 0b000X1XXXXX0XXXXX 0xXXXX 0xFFFF
если не совпало – завершение – ошибка устройства
завершение - устройство обнаружено.
I’ll explain some points - the transmission to SSP goes simultaneously with the reception, and the moment of gating the input data is shifted by half a clock cycle (at our clock frequency of 5 microseconds), therefore, when reading, you should get exactly as many words as transmitted, and when transmitting zeros it should be zero is accepted, with the exception of the latter (there should be 1, but the specific value depends on the line capacitance and the resistance of the pull-up resistor). The next feature is that the “buffer is empty” flag is set immediately after the last word of information is transferred to the shift register, but before the bits are transferred, therefore, the “device is free” flag should be used (see technical documentation), otherwise we will not see the last received word.
Similar procedures are easily created for transmitting zero and one pulses, and it is logical to transmit 2 bits of 1-Wire in a row in one 16-bit SSP word. A procedure is recommended that transfers immediately 1-Wire byte in 4 SSP words. At the end of the transmission, you should not forget to read the receive buffer in order to delete a copy of the transmitted data from there. For reading, you should create a sequence corresponding to record 1 and analyze the received information to extract the value of the received bit (send the pattern 0b01111111, accept 0b01111111 in case 1 or 0b00XXXX11 in case 0). For the transmission of long messages, you can (and it has been implemented) consider the option of organizing software using a developed apparatus for direct access to memory (again, insufficiently documented),
It should be noted that the proposed organization of the interface has a drawback - the received values are fixed along the front of the clock signal, that is, we can "catch" short pulses on the line that will distort the received information. This problem can be solved by a more detailed analysis of the received information, for example, in the adopted pattern 0b00100111, the third single bit from the left should be considered an interference. Of course, such a method cannot be considered optimal, although it must be understood that the likelihood of such an event is incommensurably less than the probability of failure in the case of a purely software implementation. Nevertheless, in the MK 1986BE1T used, it is possible to deal with interference at the hardware level, namely, each input port is equipped with a plug-in Schmidt trigger to increase noise immunity and, moreover, is equipped with a plug-in filter, which suppresses short pulses at the inputs. Unfortunately, like many other interesting solutions of the microcontroller developers, this part is very poorly documented.
Based on the above methods, a library of C subroutines is implemented for working with the 1-Wire interface through the SSP module of the 1986ВВ1Т microcontroller of the following composition:
1. The lower layer of working with hardware is made up of the MK register control routines included in the BSP MDR1986VE1T, available on the manufacturer’s website.
2. The next layer includes low-level write and read functions that are not public.
3. The interface implementation layer gives the developer full access to the 1-Wire interface and includes the following modules:
Init1Wire - initializes the hardware of the requested SSP module and returns a pointer to the control structure;
Reset1Wire - performs the initial installation of connected devices and reports on their availability;
Search1Wire - searches for devices connected to the interface and returns their addresses;
Adres1Wire - addresses a specific device on the interface;
WriteByte1Wire - writes an arbitrary byte to the selected device;
ReadByte1wire - Reads 1 byte from the selected device.
4. In the interface implementation layer, additional functions have been created to simplify interaction with the device:
WriteData1Wire - writes a data set to the selected device;
ReadData1Wire - reads a data set from the selected device.
5. The device implementation layer is built on the basis of layer 3 and is represented by an example of interaction with an electronic key of the DS1990 type.
The general conclusion is that the MK 1986VE1T is an interesting product of a domestic manufacturer with the possibility of creating various digital devices on its basis and presents a prepared specialist with rich opportunities for implementing various interfaces with minimal software costs, including non-standard ones for this microcontroller.
PS If the post is interesting to the public, then in the next I could describe the implementation of everything on the same I2C SSP interface.
Only registered users can participate in the survey. Please come in.
Material Lighting Level
- 20% Overly detailed coverage of obvious things 10
- 66% Adequate Level 33
- 14% There is a run up to the top, much remains unclear 7