2 ## This file is part of the sigrok project.
4 ## Copyright (C) 2011 Uwe Hermann <uwe@hermann-uwe.de>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 # UART protocol decoder
26 # Universal Asynchronous Receiver Transmitter (UART) is a simple serial
27 # communication protocol which allows two devices to talk to each other.
29 # It uses just two data signals and a ground (GND) signal:
30 # - RX/RXD: Receive signal
31 # - TX/TXD: Transmit signal
33 # The protocol is asynchronous, i.e., there is no dedicated clock signal.
34 # Rather, both devices have to agree on a baudrate (number of bits to be
35 # transmitted per second) beforehand. Baudrates can be arbitrary in theory,
36 # but usually the choice is limited by the hardware UARTs that are used.
37 # Common values are 9600 or 115200.
39 # The protocol allows full-duplex transmission, i.e. both devices can send
40 # data at the same time. However, unlike SPI (which is always full-duplex,
41 # i.e., each send operation is automatically also a receive operation), UART
42 # allows one-way communication, too. In such a case only one signal (and GND)
45 # The data is sent over the TX line in so-called 'frames', which consist of:
46 # - Exactly one start bit (always 0/low).
47 # - Between 5 and 9 data bits.
48 # - An (optional) parity bit.
49 # - One or more stop bit(s).
51 # The idle state of the RX/TX line is 1/high. As the start bit is 0/low, the
52 # receiver can continually monitor its RX line for a falling edge, in order
53 # to detect the start bit.
55 # Once detected, it can (due to the agreed-upon baudrate and thus the known
56 # width/duration of one UART bit) sample the state of the RX line "in the
57 # middle" of each (start/data/parity/stop) bit it wants to analyze.
59 # It is configurable whether there is a parity bit in a frame, and if yes,
60 # which type of parity is used:
61 # - None: No parity bit is included.
62 # - Odd: The number of 1 bits in the data (and parity bit itself) is odd.
63 # - Even: The number of 1 bits in the data (and parity bit itself) is even.
64 # - Mark/one: The parity bit is always 1/high (also called 'mark state').
65 # - Space/zero: The parity bit is always 0/low (also called 'space state').
67 # It is also configurable how many stop bits are to be used:
68 # - 1 stop bit (most common case)
70 # - 1.5 stop bits (i.e., one stop bit, but 1.5 times the UART bit width)
71 # - 0.5 stop bits (i.e., one stop bit, but 0.5 times the UART bit width)
73 # The bit order of the 5-9 data bits is LSB-first.
75 # Possible special cases:
76 # - One or both data lines could be inverted, which also means that the idle
77 # state of the signal line(s) is low instead of high.
78 # - Only the data bits on one or both data lines (and the parity bit) could
79 # be inverted (but the start/stop bits remain non-inverted).
80 # - The bit order could be MSB-first instead of LSB-first.
81 # - The baudrate could change in the middle of the communication. This only
82 # happens in very special cases, and can only work if both devices know
83 # to which baudrate they are to switch, and when.
84 # - Theoretically, the baudrate on RX and the one on TX could also be
85 # different, but that's a very obscure case and probably doesn't happen
86 # very often in practice.
89 # - If there is a parity bit, but it doesn't match the expected parity,
90 # this is called a 'parity error'.
91 # - If there are no stop bit(s), that's called a 'frame error'.
98 # Protocol output format:
101 # [<packet-type>, <rxtx>, <packet-data>]
103 # This is the list of <packet-types>s and their respective <packet-data>:
104 # - T_START: The data is the (integer) value of the start bit (0 or 1).
105 # - T_DATA: The data is the (integer) value of the UART data. Valid values
106 # range from 0 to 512 (as the data can be up to 9 bits in size).
107 # - T_PARITY: The data is the (integer) value of the parity bit (0 or 1).
108 # - T_STOP: The data is the (integer) value of the stop bit (0 or 1).
109 # - T_INVALID_START: The data is the (integer) value of the start bit (0 or 1).
110 # - T_INVALID_STOP: The data is the (integer) value of the stop bit (0 or 1).
111 # - T_PARITY_ERROR: The data is a tuple with two entries. The first one is
112 # the expected parity value, the second is the actual parity value.
114 # The <rxtx> field is 0 for RX packets, 1 for TX packets.
117 import sigrokdecode as srd
120 WAIT_FOR_START_BIT = 0
126 # Used for differentiating between the two data directions.
147 # Annotation feed formats
154 # Protocol output packet types
163 # Given a parity type to check (odd, even, zero, one), the value of the
164 # parity bit, the value of the data, and the length of the data (5-9 bits,
165 # usually 8 bits) return True if the parity is correct, False otherwise.
166 # PARITY_NONE is _not_ allowed as value for 'parity_type'.
167 def parity_ok(parity_type, parity_bit, data, num_data_bits):
169 # Handle easy cases first (parity bit is always 1 or 0).
170 if parity_type == PARITY_ZERO:
171 return parity_bit == 0
172 elif parity_type == PARITY_ONE:
173 return parity_bit == 1
175 # Count number of 1 (high) bits in the data (and the parity bit itself!).
176 parity = bin(data).count('1') + parity_bit
178 # Check for odd/even parity.
179 if parity_type == PARITY_ODD:
180 return (parity % 2) == 1
181 elif parity_type == PARITY_EVEN:
182 return (parity % 2) == 0
184 raise Exception('Invalid parity type: %d' % parity_type)
186 class Decoder(srd.Decoder):
189 longname = 'Universal Asynchronous Receiver/Transmitter'
190 desc = 'Universal Asynchronous Receiver/Transmitter (UART)'
196 # Allow specifying only one of the signals, e.g. if only one data
197 # direction exists (or is relevant).
198 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
199 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
202 'baudrate': ['Baud rate', 115200],
203 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
204 'parity': ['Parity', PARITY_NONE],
205 'parity_check': ['Check parity', True],
206 'num_stop_bits': ['Stop bit(s)', STOP_BITS_1],
207 'bit_order': ['Bit order', LSB_FIRST],
208 # TODO: Options to invert the signal(s).
211 ['ASCII', 'Data bytes as ASCII characters'],
212 ['Decimal', 'Databytes as decimal, integer values'],
213 ['Hex', 'Data bytes in hex format'],
214 ['Octal', 'Data bytes as octal numbers'],
215 ['Bits', 'Data bytes in bit notation (sequence of 0/1 digits)'],
218 def putx(self, rxtx, data):
219 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_ann, data)
221 def __init__(self, **kwargs):
223 self.frame_start = [-1, -1]
224 self.startbit = [-1, -1]
225 self.cur_data_bit = [0, 0]
226 self.databyte = [0, 0]
227 self.stopbit1 = [-1, -1]
228 self.startsample = [-1, -1]
231 self.state = [WAIT_FOR_START_BIT, WAIT_FOR_START_BIT]
233 self.oldbit = [None, None]
235 # Set protocol decoder option defaults.
236 self.baudrate = Decoder.options['baudrate'][1]
237 self.num_data_bits = Decoder.options['num_data_bits'][1]
238 self.parity = Decoder.options['parity'][1]
239 self.check_parity = Decoder.options['parity_check'][1]
240 self.num_stop_bits = Decoder.options['num_stop_bits'][1]
241 self.bit_order = Decoder.options['bit_order'][1]
243 def start(self, metadata):
244 self.samplerate = metadata['samplerate']
245 self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
246 self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
248 # TODO: Override PD options, if user wants that.
250 # The width of one UART bit in number of samples.
251 self.bit_width = float(self.samplerate) / float(self.baudrate)
256 # Return true if we reached the middle of the desired bit, false otherwise.
257 def reached_bit(self, rxtx, bitnum):
258 # bitpos is the samplenumber which is in the middle of the
259 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
260 # (if used) or the first stop bit, and so on).
261 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
262 bitpos += bitnum * self.bit_width
263 if self.samplenum >= bitpos:
267 def reached_bit_last(self, rxtx, bitnum):
268 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
269 if self.samplenum >= bitpos:
273 def wait_for_start_bit(self, rxtx, old_signal, signal):
274 # The start bit is always 0 (low). As the idle UART (and the stop bit)
275 # level is 1 (high), the beginning of a start bit is a falling edge.
276 if not (old_signal == 1 and signal == 0):
279 # Save the sample number where the start bit begins.
280 self.frame_start[rxtx] = self.samplenum
282 self.state[rxtx] = GET_START_BIT
284 def get_start_bit(self, rxtx, signal):
285 # Skip samples until we're in the middle of the start bit.
286 if not self.reached_bit(rxtx, 0):
289 self.startbit[rxtx] = signal
291 # The startbit must be 0. If not, we report an error.
292 if self.startbit[rxtx] != 0:
293 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
294 [T_INVALID_START, rxtx, self.startbit[rxtx]])
295 # TODO: Abort? Ignore rest of the frame?
297 self.cur_data_bit[rxtx] = 0
298 self.databyte[rxtx] = 0
299 self.startsample[rxtx] = -1
301 self.state[rxtx] = GET_DATA_BITS
303 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
304 [T_START, rxtx, self.startbit[rxtx]])
305 self.put(self.frame_start[rxtx], self.samplenum, self.out_ann,
306 [ANN_ASCII, ['Start bit', 'Start', 'S']])
308 def get_data_bits(self, rxtx, signal):
309 # Skip samples until we're in the middle of the desired data bit.
310 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
313 # Save the sample number where the data byte starts.
314 if self.startsample[rxtx] == -1:
315 self.startsample[rxtx] = self.samplenum
317 # Get the next data bit in LSB-first or MSB-first fashion.
318 if self.bit_order == LSB_FIRST:
319 self.databyte[rxtx] >>= 1
320 self.databyte[rxtx] |= (signal << (self.num_data_bits - 1))
321 elif self.bit_order == MSB_FIRST:
322 self.databyte[rxtx] <<= 1
323 self.databyte[rxtx] |= (signal << 0)
325 raise Exception('Invalid bit order value: %d', self.bit_order)
327 # Return here, unless we already received all data bits.
328 if self.cur_data_bit[rxtx] < self.num_data_bits - 1: # TODO? Off-by-one?
329 self.cur_data_bit[rxtx] += 1
332 self.state[rxtx] = GET_PARITY_BIT
334 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_proto,
335 [T_DATA, rxtx, self.databyte[rxtx]])
337 s = 'RX: ' if (rxtx == RX) else 'TX: '
338 self.putx(rxtx, [ANN_ASCII, [s + chr(self.databyte[rxtx])]])
339 self.putx(rxtx, [ANN_DEC, [s + str(self.databyte[rxtx])]])
340 self.putx(rxtx, [ANN_HEX, [s + hex(self.databyte[rxtx]),
341 s + hex(self.databyte[rxtx])[2:]]])
342 self.putx(rxtx, [ANN_OCT, [s + oct(self.databyte[rxtx]),
343 s + oct(self.databyte[rxtx])[2:]]])
344 self.putx(rxtx, [ANN_BITS, [s + bin(self.databyte[rxtx]),
345 s + bin(self.databyte[rxtx])[2:]]])
347 def get_parity_bit(self, rxtx, signal):
348 # If no parity is used/configured, skip to the next state immediately.
349 if self.parity == PARITY_NONE:
350 self.state[rxtx] = GET_STOP_BITS
353 # Skip samples until we're in the middle of the parity bit.
354 if not self.reached_bit(rxtx, self.num_data_bits + 1):
357 self.paritybit[rxtx] = signal
359 self.state[rxtx] = GET_STOP_BITS
361 if parity_ok(self.parity[rxtx], self.paritybit[rxtx],
362 self.databyte[rxtx], self.num_data_bits):
364 self.put(self.samplenum, self.samplenum, self.out_proto,
365 [T_PARITY_BIT, rxtx, self.paritybit[rxtx]])
366 self.put(self.samplenum, self.samplenum, self.out_ann,
367 [ANN_ASCII, ['Parity bit', 'Parity', 'P']])
370 # TODO: Return expected/actual parity values.
371 self.put(self.samplenum, self.samplenum, self.out_proto,
372 [T_PARITY_ERROR, rxtx, (0, 1)]) # FIXME: Dummy tuple...
373 self.put(self.samplenum, self.samplenum, self.out_ann,
374 [ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
376 # TODO: Currently only supports 1 stop bit.
377 def get_stop_bits(self, rxtx, signal):
378 # Skip samples until we're in the middle of the stop bit(s).
379 skip_parity = 0 if self.parity == PARITY_NONE else 1
380 if not self.reached_bit(rxtx, self.num_data_bits + 1 + skip_parity):
383 self.stopbit1[rxtx] = signal
385 # Stop bits must be 1. If not, we report an error.
386 if self.stopbit1[rxtx] != 1:
387 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
388 [T_INVALID_STOP, rxtx, self.stopbit1[rxtx]])
389 # TODO: Abort? Ignore the frame? Other?
391 self.state[rxtx] = WAIT_FOR_START_BIT
394 self.put(self.samplenum, self.samplenum, self.out_proto,
395 [T_STOP, rxtx, self.stopbit1[rxtx]])
396 self.put(self.samplenum, self.samplenum, self.out_ann,
397 [ANN_ASCII, ['Stop bit', 'Stop', 'P']])
399 def decode(self, ss, es, data): # TODO
400 for (samplenum, (rx, tx)) in data:
402 # TODO: Start counting at 0 or 1? Increase before or after?
405 # First sample: Save RX/TX value.
406 if self.oldbit[RX] == None:
409 if self.oldbit[TX] == None:
414 for rxtx in (RX, TX):
415 signal = rx if (rxtx == RX) else tx
417 if self.state[rxtx] == WAIT_FOR_START_BIT:
418 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
419 elif self.state[rxtx] == GET_START_BIT:
420 self.get_start_bit(rxtx, signal)
421 elif self.state[rxtx] == GET_DATA_BITS:
422 self.get_data_bits(rxtx, signal)
423 elif self.state[rxtx] == GET_PARITY_BIT:
424 self.get_parity_bit(rxtx, signal)
425 elif self.state[rxtx] == GET_STOP_BITS:
426 self.get_stop_bits(rxtx, signal)
428 raise Exception('Invalid state: %s' % self.state[rxtx])
430 # Save current RX/TX values for the next round.
431 self.oldbit[rxtx] = signal