I wrote a simple function to send a string of 8 bit characters on a digital pin using bit-banging. What I got was strange. If I send a message, its first character is often a duplicate of the second character. Say my message is "AXC!", then after repeatedly sending this message, I get this:
XXC!XXC!AXC!AXC!XXC!XXC!XXC!AXC!AXC!XXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!XXC!AXC!AXC!XXC!XXC!XXC!AXC!AXC!XXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!AXC!AXC!AXC!XXC!XXC!XXC!AXC!
So sometimes I get it right. Other times instead I get "XXC!".
[UPDATE]
OK, I replaced the noname TTL USB adapter with an arduino and the results are all correct now. So now my new question is: how can this happen with a TTL USB adapter?
My code is below:
I just pass "AXC!" to this function.
void send_to_SDI(char* buf)
{
int i=0;
pinMode(SDI_pin,OUTPUT);
digitalWrite(SDI_pin,marking_level);
/*
// Wake up all sensors
pinMode(SDI_pin,OUTPUT);
digitalWrite(SDI_pin,break_level);
delay(break_ms);
digitalWrite(SDI_pin,marking_level);
delay(marking_ms);
*/
noInterrupts();
while(buf[i]) // Send each byte
{
byte out_bit=0;
//Start bit
digitalWrite(SDI_pin,spacing_level);
delayMicroseconds(bit_length_us);
for (int j=0;j<8;j++) // Send each bit, LSB first.
{
out_bit=(buf[i]>>j)&1;
//Serial.print((int)out_bit);
if (out_bit)
{
digitalWrite(SDI_pin,marking_level);
}
else
{
digitalWrite(SDI_pin,spacing_level);
}
delayMicroseconds(bit_length_us);
}
//Stop bit
digitalWrite(SDI_pin,marking_level);
delayMicroseconds(bit_length_us);
//Serial.print(" ");
delayMicroseconds(delay_between_bytes_us);
i++;
}
// Relinquish the SDI pin
//digitalWrite(SDI_pin,marking_level);
//pinMode(SDI_pin,INPUT);
interrupts();
}
I checked a few times but can't find out what's gone wrong. I'll use a different TTL USB adapter and see if I get any better luck. Any help is appreciated.