Compare commits

..

1 Commits

Author SHA1 Message Date
af6dfe7a7d Master 2023-04-16 18:27:33 +00:00

100
SPI/master.ino Normal file
View File

@ -0,0 +1,100 @@
//master
#include <avr/io.h>
#include <util/delay.h>
#define DDR_SPI DDRB
#define DD_MOSI PB3
#define DD_MISO PB4
#define DD_SCK PB5
#define DD_SS PB2
void SPI_MasterInit(void)
{
DDR_SPI = (1 << DD_MOSI) | (1 << DD_SCK) | (1 << DD_SS);
DDRB |= (1<<DDB2); // set SS as output
SPCR = (1 << SPE) | (1 << MSTR);
}
void Print(byte *data2, int lenght){
for(int i = 0; i < lenght; i++) {
Serial.print(data2[i]);
Serial.print(" ");
}
}
void SPI_MasterTransmit(char *data, int length)
{
// Serial.println();
byte check = 0;
byte spdr[length];
for(int i = 0; i < length; i++) {
SPDR = data[i]; // отправляем байт массива
while (!(SPSR & (1 << SPIF))); // ждем, пока байт передастся
}
// Print(spdr, length);
// return check;
// //ждем, пока придет контрольная сумма
// while (!(SPSR & (1 << SPIF)));
// uint8_t received_checksum = SPDR;
// // вычисляем контрольную сумму XOR для принятых данных
// uint8_t calculated_checksum = calculateXORChecksum((byte*)data, length);
// Serial.println();
// Serial.println(received_checksum);
// // проверяем, совпадает ли принятая контрольная сумма с вычисленной
// if (received_checksum == calculated_checksum) {
// Serial.println("\nChecksum is correct");
// } else {
// Serial.println("\nChecksum is incorrect");
// }
}
void setup()
{
Serial.begin(9600);
SPI_MasterInit();
Serial.println("Master Initialization ");
}
// Функция для вычисления контрольной суммы XOR
byte calculateXORChecksum(byte *data, int length) {
byte checksum = 0;
for (int i = 0; i < length -1; i++) {
checksum ^= data[i];
}
return checksum;
}
void loop()
{
char data[5] = {6, 1, 2, 8, 0};
PORTB &= ~(1<<2);
int length = sizeof(data);
const int last = data [ (sizeof(data) / sizeof(data[0]))-1];
byte checking = calculateXORChecksum(data, length);
int size = sizeof(data) / sizeof(data[0]);
data[size - 1] = checking;
// Serial.println(last);
SPI_MasterTransmit(data, length);
_delay_ms(200);
PORTB |= (1<<2);
Serial.println("Sent");
// Serial.print(sum);
_delay_ms(2000);
// ожидаем ответа
// while (!(SPSR & (1 << SPIF)));
// byte response = SPDR;
// if (response == 0x55) { // 0x55 - успешный ответ
// Serial.println("Command executed successfully");
// } else if (response == 0xAA) { // 0xAA - ошибка контрольной суммы
// Serial.println("Error: Checksum does not match");
// } else { // другие значения - неизвестный ответ
// Serial.println("Error: Unknown response");
// }
}