I am attempting to take in a UDP packet to my code and spit it out as a CAN message.
Pretty much a complete beginner and have now gotten stuck.
My code currently will receive a hex UDP packet and read it out in serial. It will also transmit a template CAN message to my PCAN.
Where I am stuck is how to turn these hex messages from UDP into a CAN message?
#include <SPI.h>
#include <PortentaEthernet.h>
#include <Arduino_CAN.h>
#include <Arduino_PortentaMachineControl.h>
// Ethernet settings
IPAddress ip(192, 168, 0, 2); //IP address of Arduino
unsigned int localPort = 8888; // Local port to listen on
//buffer for packet
//static uint32_t const UDP_TX_PACKET_MAX_SIZE = 7;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
// CAN settings
static uint32_t const canId = 0x20;
static uint32_t msg_cnt = 0;
// UDP instance
EthernetUDP Udp;
void setup()
{
Serial.begin(9600);
// Start Ethernet and UDP
Ethernet.begin(ip);
Udp.begin(localPort);
//CAN setup
if (!MachineControl_CANComm.begin(CanBitRate::BR_1000k)) {
Serial.println("CAN init failed.");
while(1) ;
}
}
void loop()
{
// If there's data available in the UDP buffer
int packetSize = Udp.parsePacket();
if (packetSize)
{
// Read the UDP packet
int len = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
if (len > 0)
{
packetBuffer[len] = 0; // Null-terminate the string
}
// Print the received UDP packet
Serial.println("UDP packet received");
Serial.println(packetBuffer);
// Assemble CAN message
uint8_t const msg_data[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
CanMsg msg(canId, sizeof(msg_data), msg_data);
//Transmit CAN msg
int const rc = MachineControl_CANComm.write(msg);
if (rc <= 0) {
Serial.print("CAN write failed with error code: ");
Serial.println(rc);
while(1) ;
}
Serial.println("CAN write message!");
/* Increase the message counter */
msg_cnt++;
/* Only send one message per second */
delay(1000);
}
}