Переход на C
Пока не работает
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
#include "SPIMaster.h"
|
||||
|
||||
|
||||
void Print(char *data2, int lenght){
|
||||
for(int i = 0; i < lenght; i++) {
|
||||
Serial.print(data2[i], HEX);
|
||||
Serial.print(" ");
|
||||
}
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(9600);
|
||||
SPI_MasterInit();
|
||||
Serial.println("Master Initialization ");
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
char data[] = {6, 1, 3, 5, 16, 17, 18, 0};
|
||||
int length = sizeof(data);
|
||||
|
||||
Serial.print("Start:");
|
||||
Print(data,length);
|
||||
Serial.println();
|
||||
|
||||
char checking = CRC8(data, length-1);
|
||||
int size = sizeof(data) / sizeof(data[0]);
|
||||
data[size - 1] = checking;
|
||||
|
||||
Serial.print("End:");
|
||||
Print(data,length);
|
||||
Serial.println();
|
||||
|
||||
SPI_MasterTransmit(data, length);
|
||||
_delay_ms(1000);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
|
||||
#include "SPIMaster.h"
|
||||
#include <avr/io.h>
|
||||
#include <util/delay.h>
|
||||
|
||||
void SPI_MasterInit(void)
|
||||
{
|
||||
DDR_SPI = (1 << DD_MOSI) | (1 << DD_SCK) | (1 << DD_SS);
|
||||
DDRB |= (1<<DDB2);
|
||||
SPCR = (1 << SPE) | (1 << MSTR);
|
||||
}
|
||||
|
||||
void SPI_MasterTransmit(char *data, int length)
|
||||
{
|
||||
PORTB &= ~(1<<2);
|
||||
|
||||
int size = sizeof(data) / sizeof(data[0]);
|
||||
|
||||
for(int i = 0; i < length; i++) {
|
||||
SPDR = data[i]; // отправляем байт массива
|
||||
while (!(SPSR & (1 << SPIF))); // ждем, пока байт передастся
|
||||
}
|
||||
|
||||
PORTB |= (1<<2);
|
||||
}
|
||||
|
||||
char CRC8(char *data, int length) {
|
||||
char crc = 0x00;
|
||||
char 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef SPIMaster_h
|
||||
#define SPIMaster_h
|
||||
|
||||
#define DDR_SPI DDRB
|
||||
#define DD_MOSI PB3
|
||||
#define DD_MISO PB4
|
||||
#define DD_SCK PB5
|
||||
#define DD_SS PB2
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
void SPI_MasterInit(void);
|
||||
void SPI_MasterTransmit(char *data, int length);
|
||||
char CRC8(char *data, int length);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user