SHIELD-Malb41k1/SPI/slave/slave.ino
2023-04-26 12:38:06 +03:00

144 lines
3.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <avr/io.h>
#include <util/delay.h>
// #include <GyverOLED.h>
#define DDR_SPI DDRB
#define DD_MOSI PB3
#define DD_MISO PB4
#define DD_SCK PB5
#define DD_SS PB2
// GyverOLED<SSD1306_128x64, OLED_NO_BUFFER> oled;
static int index = 0;
static int arIndex = 0;
static byte data[255];
void SPI_SlaveInit(void)
{
DDR_SPI = (1 << DD_MISO);
SPCR = (1 << SPE) | (1 << SPIE);
}
ISR(SPI_STC_vect)
{
char received = SPDR;
data[index] = received;
index++;
}
void setup()
{
Serial.begin(2000000);
SPI_SlaveInit();
// oled.init(); // инициализация
// oled.clear(); // очистка
Serial.println();
Serial.println("Initialization ");
}
void SetCommand(byte *data2){
byte command = data2[0];
// Отрезать 1 элемент от оставшихся
byte result[index];
byte *ptr = &data2[1];
strcpy(result, ptr);
Serial.print("\nReceived command: ");
Serial.println(command);
switch (command){
case 6:
AddSymbol(result);
break;
}
}
void AddSymbol(byte *symbols){
Serial.print("Received Add: ");
// oled.setScale(3); // масштаб текста (1..4)
// oled.home(); // курсор в 0,0
// oled.print("Привет!");
for(int i = 0; i < index - 1; i++) {
Serial.print(symbols[i], HEX);
Serial.print(" ");
}
}
// Функция для вычисления контрольной суммы XOR
byte calculateXORChecksum(byte *data, int length) {
byte crc = 0x00;
byte poly = 0x07; // полином для CRC8
for (int i = 0; i < length-2; i++) {
crc ^= data[i]; // XOR текущего байта с crc
for (int j = 0; j < length; j++) {
if (crc & 0x80) { // если старший бит crc равен 1
crc = (crc << 1) ^ poly; // сдвигаем crc на 1 бит влево и XOR с полиномом
} else {
crc <<= 1; // иначе просто сдвигаем на 1 бит влево
}
}
}
return crc;
}
// Вывод массива
void arrayOut(byte *arr,int size){
Serial.print("Array: ");
for(int i = 0; i < size;i++){
Serial.print(arr[i], HEX);
Serial.print(" ");
}
Serial.println(".");
}
// Проверка массива на ноль
bool checkArray(byte* arr, int size) {
for (int i = 0; i < size; i++) {
if (arr[i] != 0) {
return true;
}
}
return false;
}
void loop() {
if(PINB & (1 << 2)){
if(index > 0){
byte sum = 0;
sum = calculateXORChecksum(data, index-1);
bool checkNull = false;
byte last_1 = data[index - 1];
//arrayOut(data, index);
if (last_1 == sum){
Serial.println();
Serial.println("Старт вывода массивов");
Serial.println(sum, HEX);
checkNull = checkArray(data, index);
if(checkNull == true){
SetCommand(data);
}
Serial.println("Стоп вывода массивов");
index = 0;
return;
}
Serial.println("Nothing ...");
index = 0;
}
}
}