#include #include void printAsBinary(unsigned short); void send(int); void receive(int); unsigned char simulatedInstructions[] = {0b0110, // 6 0b0000, // 0 0b0011, // 3 0b1111, // 15 0b0001}; // 1 unsigned char simulatedData[] = {0b00110011, // 51 0b11100000, // 228 0b10101010, // 170 0b00000000, // 0 0b11111111}; // 255 unsigned short simulatedResults[] = {0b0000101000010110, // 161 0b1010000000000000, // error code 2 0b1101001110010011, // error code 5 0b0000111111101111, // 254 0b0000000111110001}; // 31 int main() { unsigned short result; // Send 5 commands and get 5 results for (int i=0; i<5; i++) { send(i); receive(i) ; } return 0; } // Simulate the sending of an instruction with data to the device void send(int i) { unsigned short command = simulatedInstructions[i] + (simulatedData[i] << 4); printf("Sending Command: "); printAsBinary(command); } // Simulate the receiving of a one byte data reply from the device. An // error may have occurred, so this is checked for before the data is read. void receive(int i) { unsigned short result = simulatedResults[i]; if ((result & 0b1000000000000000) > 0) printf("An error has occurred with code: %d\n", (result & (0b111<<12)) >> 12); else printf("The result data from the device is: %d\n", (result & (255<<4)) >> 4); } // Convert an unsigned short to an integer that looks like binary void printAsBinary(unsigned short n) { for (int i=15; i>=0; i--) { if ((int)(n/pow(2,i)) > 0) { printf("1"); n = n - pow(2,i); } else printf("0"); } printf("\n"); }