terminal/MASTER.ino

76 lines
1.8 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/interrupt.h>
#include <avr/io.h>
#define SPI_PORTX PORTB
#define SPI_DDRX DDRB
#define SPI_MISO 4
#define SPI_MOSI 3
#define SPI_SCK 5
#define SPI_SS 2
void SPI_MasterInit(void)
{
/* Настройка MOSI и SCK как выход,
все остальные сигналы как вход: */
SPI_DDRX = (1 << SPI_MOSI)|(1 << SPI_SCK)|(1<<SPI_SS)|(0<<SPI_MISO);
/* Разрешить работу SPI, режим Master,
установить скорость тактов fck/16: */
SPCR = (1 << SPE)|(1 << MSTR)|(0<<CPOL)|(0<<CPHA)|(1 << SPR0);
SPI_PORTX |= (1 << SPI_SS);
}
void SPI_MasterTransmit(char* buffer, size_t length)
{
SPI_PORTX &= ~(1 << SPI_SS);
for(int i=0; i<length; i++ ){
SPDR = buffer[i];
while(!(SPSR & (1 << SPIF)));
Serial.println("Transmitede");
delay(2000);
}
SPI_PORTX |= (1 << SPI_SS);
}
byte crc8(byte *data, int length) {
byte crc = 0x00;
byte poly = 0x07; //полином для CRC
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 setup() {
SPI_MasterInit();
Serial.begin(9600);
Serial.println("Arduino 1 starded");
}
void loop() {
char buffer[] = {'a', 't', 'g', '1', 0};
for(int y=5; y<21; y++) {
buffer[0]=0x06;
buffer[1]=3;
buffer[2]=y;
buffer[3]=0x01;
buffer[4]=crc8(&buffer[0], 4);
SPI_MasterTransmit(&buffer[0], 5);
}
}