Packet update

initialisation of secured data transmission with the implementation of
packets in the code to give them to the Python script safely.
This commit is contained in:
Martin Girard committed 2026-09-15 12:01:32 +02:00
1 parent 55f271f6ce
commit 93054253e6
1 file changed
+58 -6
+58 -6
View File
@@ -10,6 +10,54 @@ volatile bool new_rpm = false;
const unsigned long deltat_lambda = 100000; const unsigned long deltat_lambda = 100000;
unsigned long last_lambda = 0; unsigned long last_lambda = 0;
typedef uint8_t data_type;
enum{
SPEED = 0,
LAMBDA = 1,
};
#pragma pack(push,1)
typedef struct {
uint16_t sync;
data_type type;
uint32_t timestamp;
float data;
uint16_t crc;
} data_packet;
#pragma pack(pop)
uint16_t crc16_ccitt(const uint8_t *data, size_t length)
{
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; i++) {
crc ^= (uint16_t)data[i] << 8;
for (uint8_t bit = 0; bit < 8; bit++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ 0x1021;
} else {
crc <<= 1;
}
}
}
return crc;
}
data_packet pack(data_type type,uint32_t timestamp, float data){
data_packet output{};
output.sync = 0xBEEF;
output.type = type;
output.timestamp = timestamp;
output.data = data;
output.crc = crc16_ccitt(&output.type, sizeof(data_type)+sizeof(uint32_t)+sizeof(float));
return output;
}
void interrupt(){ void interrupt(){
unsigned long now = micros(); unsigned long now = micros();
timestamp2 = timestamp1; timestamp2 = timestamp1;
@@ -31,8 +79,10 @@ void loop() {
unsigned long deltat = timestamp1 - timestamp2; unsigned long deltat = timestamp1 - timestamp2;
float rpmhz = 500000.0 / deltat; float rpmhz = 500000.0 / deltat;
new_rpm = false; new_rpm = false;
Serial.print("Speed: "); data_packet speed_packet = pack(SPEED,timestamp1,rpmhz);
Serial.println(rpmhz); Serial.write((uint8_t*)&speed_packet, sizeof(data_packet));
//Serial.print("Speed: ");
//Serial.println(rpmhz);
} }
unsigned long now = micros(); unsigned long now = micros();
if (now > last_lambda + deltat_lambda){ if (now > last_lambda + deltat_lambda){
@@ -40,10 +90,12 @@ void loop() {
float voltage = output / 204.6; float voltage = output / 204.6;
float lambda = 0.56030161*voltage + 0.43969839; float lambda = 0.56030161*voltage + 0.43969839;
last_lambda = now; last_lambda = now;
Serial.print("Voltage: "); data_packet lambda_packet = pack(LAMBDA,now,lambda);
Serial.println(voltage); Serial.write((uint8_t*)&lambda_packet,sizeof(lambda_packet));
Serial.print("Lambda:"); //Serial.print("Voltage: ");
Serial.println(lambda); //Serial.println(voltage);
//Serial.print("Lambda:");
//Serial.println(lambda);
} }
} }