Packet Serial without library
Posted: Fri Aug 06, 2021 3:21 pm
I have tried to write the code for sending commands with an Arduino Uno over packet serial with the checksum without the library. The reason for that is, because I have tried to use the example and copied the same commands into my code to get it working. The example seems to work, but with the same commands in my code it does not. Also I would like to understand the code I make. With a library it is not really visible what the code really makes. Perhaps someone could help me to get my code working with the Roboclaw 2x60?
Here I will post the parts of the code how I send and make the checksum, but as I have said, somewhere is an issue and need some help to fix it:
const unsigned long Baudrate = 38400;
const byte SpeedFDLR = 100;
#define RoboclawRXpin 6
#define RoboclawTXpin 5
byte mapFDLR = 0;
byte data[5];
uint16_t crc = 0;
#include <SoftwareSerial.h>
#define address 0x80
SoftwareSerial serial2(RoboclawRXpin, RoboclawTXpin);
void setup() {
pinMode(RoboclawRXpin, INPUT);
pinMode(RoboclawTXpin, OUTPUT);
serial2.begin(Baudrate);
}
void loop() {
if(FDLR != lastFDLR && joybut == HIGH){
if(0 <= FDLR && FDLR < 87){
mapFDLR = map(FDLR, 90, 0, 0, SpeedFDLR);
Serial.println(mapFDLR);
data[0] = address;
data[1] = 10;
data[2] = mapFDLR;
for(byte index = 0; index <= 3; index++){
crc16(data[index]);
}
crc = getCRC();
data[3] = crc >> 8;
data[4] = crc;
serial2.write(data, sizeof(data));
}
lastFDLR = FDLR;
crc = 0;
}
}
//Calculates CRC16 of nBytes of data[index] in byte array
void crc16(uint8_t data) {
int i;
crc = crc ^ ((uint16_t)data << 8);
for (i=0; i<8; i++){
if (crc & 0x8000){
crc = (crc << 1) ^ 0x1021;
}
else{
crc <<= 1;
}
}
}
uint16_t getCRC() {
return crc;
}
Every help and ideas are appreciated!
Regards
Stef
Here I will post the parts of the code how I send and make the checksum, but as I have said, somewhere is an issue and need some help to fix it:
const unsigned long Baudrate = 38400;
const byte SpeedFDLR = 100;
#define RoboclawRXpin 6
#define RoboclawTXpin 5
byte mapFDLR = 0;
byte data[5];
uint16_t crc = 0;
#include <SoftwareSerial.h>
#define address 0x80
SoftwareSerial serial2(RoboclawRXpin, RoboclawTXpin);
void setup() {
pinMode(RoboclawRXpin, INPUT);
pinMode(RoboclawTXpin, OUTPUT);
serial2.begin(Baudrate);
}
void loop() {
if(FDLR != lastFDLR && joybut == HIGH){
if(0 <= FDLR && FDLR < 87){
mapFDLR = map(FDLR, 90, 0, 0, SpeedFDLR);
Serial.println(mapFDLR);
data[0] = address;
data[1] = 10;
data[2] = mapFDLR;
for(byte index = 0; index <= 3; index++){
crc16(data[index]);
}
crc = getCRC();
data[3] = crc >> 8;
data[4] = crc;
serial2.write(data, sizeof(data));
}
lastFDLR = FDLR;
crc = 0;
}
}
//Calculates CRC16 of nBytes of data[index] in byte array
void crc16(uint8_t data) {
int i;
crc = crc ^ ((uint16_t)data << 8);
for (i=0; i<8; i++){
if (crc & 0x8000){
crc = (crc << 1) ^ 0x1021;
}
else{
crc <<= 1;
}
}
}
uint16_t getCRC() {
return crc;
}
Every help and ideas are appreciated!
Regards
Stef