Hi,
I am experimenting around with a custom data bus, and have got sending bytes and bits down. However, I am a bit stuck on how to read the sent bits and assign them to a char array. I first send a starting bit, then a byte (8 bits of data) and then a closing bit. So in total, 10 bits. For each time a bit is sent (on digital 4) the clock wire (digital 3) goes high. The clock then goes low, and then high for the next bit. Since the clock wire goes high for more than one cycle of the code loop, when I try to receive one bit, I end up getting like 50 values of the same one.
So my question is: how can I make it so it only received one bit per clock cycle of the clock wire?
By using a global or static local, you can use a variable to keep track of the clock pin state, which you can then use to decide weather to act or ignore.
void loop(){
static bool clkLast = !digitalRead( clk );
if( !!digitalRead( clk ) != clkLast ){
//Start of new clock state
//Do something with bit
clkLast = !clkLast;
}
}
Of course this will need additional logic to count bits etc... It simply detects a change of state + the initial state.
Ah thank you. So basically if its a new clock state then that data is used. What happens if I want to assign that data to, say, data[n] where n starts at 0 for the starting bit and is 9 for the end bit? How can, each time, it be assign to the next place, until the 9th place?
Using the same method, use a variable to store the position, incrementing after reading a bit from the data line. The same variable will tell you when the data is complete so you can use it and then reset the counter.
Actually, I've one more question. I tried your method, it works great, but I would like to use true c coding rather than digitalwrite(), for speed reasons. How can I then compare the previous states with PINB as reading ports?
Actually, after a bit more testing, I believe your code does work, but not for what I wish. I need it to read data only on a new high clock state, not just a new clock state. Sorry if I wasn't clear on that at first.
just add an additional check that when the new clk state is found, it is high. that would imply that the previous state was low and you'll only be capturing data on the clock rising edge.