hi,everyone
I am working on a project that reads data through spi communication and prints it to a serial monitor.
When a specific byte is read, it tries to output to the serial monitor. Oddly, some bytes are read and some bytes are not read.
For example, if(buf[0] == 0x41) works fine, but if(buf[0] == 0x3F) does not.
Here is my code.
#include <stdio.h>
#include <SPI.h>
byte buf[50];
volatile byte pos;
volatile boolean process_it;
void setup (void)
{
//pinMode(MISO, OUTPUT); //12 mega50
pinMode(MOSI, INPUT); //11 mega51
pinMode(SCK, INPUT); //13 mega52
pinMode(SS, INPUT); //10 mega53
SPCR |= _BV(SPE);
SPCR &= ~_BV(MSTR);
SPCR |= _BV(SPIE);
pos=0;
process_it = false;
SPI.setBitOrder(LSBFIRST);
SPI.setDataMode(SPI_MODE0);
Serial.begin(57600);
Serial.println("Serial Start!");
}
ISR (SPI_STC_vect)
{
byte c = SPDR;
if (pos < sizeof(buf))
{
buf[pos++] = c;
if (c == 0x90)
{
process_it = true;
}
}
}
void loop (void)
{
if (process_it)
{
if(buf[0] == 0x3F) <--Here is the problem.
{
Serial.println("OK");
}
pos = 0;
process_it = false;
}
}
constexpr char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
void printHex(unsigned char * data, int len){
char tempByte[3] = {0,0,0};
for (int i = 0; i < len; i++) {
Serial.print((char*)hexChar(tempByte, data[i]));
if(data[i] == 0x90){
Serial.print('\n');
break;
}
}
//Serial.print('\n');
}
char *hexChar(char *destBuf, unsigned char srcData){
destBuf[0] = hexmap[(srcData & 0xF0) >> 4];
destBuf[1] = hexmap[srcData & 0x0F];
return destBuf;
}
Actually, the data received by spi is this format.
10:39:59.478 -> 41 50 3F 3F 3F 3F 90
10:39:59.478 -> 3F 50 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 90
However, ok is output only when buf[0] is 0x41, and ok is not output when 0x3f.