void nmra_transmit(const Byte *nmra_packet, int length) {
Byte encoded[COMMAND_ENCODED_MAX], *encp;
- unsigned working;
+ unsigned working, newbits;
int working_qty;
+ assert(length > 0);
assert(length <= NMRA_PACKET_MAX);
encp= encoded;
working= 0xfffc; /* 16-bit temp register. Top working_qty bits */
- working_qty= 14; /* are some data bits to encode, rest are clear. */
+ working_qty= 15; /* are some data bits to encode, rest are clear. */
+ /* we start with the 14-bit preamble and the packet start bit */
for (;;) {
assert(working_qty >= 0);
if (working_qty < 7) {
if (length > 0) {
/* plonk new data bits just to right of old data bits */
- working |= (*nmra_packet++ << (8-working_qty));
length--;
- working_qty += 8;
+ newbits= *nmra_packet++;
+ newbits <<= 1;
+ newbits |= !length; /* 9 bits, bottom one is `end of packet' */
+ working |= (newbits << (7-working_qty));
+ working_qty += 9;
} else if (!working_qty) {
/* all done */
break;