This page describes a simple UDP (User Datagram Protocol) communication example designed for embedded systems, specifically targeting the Raspberry Pi Zero W. This example demonstrates how to send a UDP message from the Raspberry Pi to a specified IP address and port.
The C code, udpw.c, initializes a UDP socket and sends a JSON formatted message to a preconfigured IP address and port. The message contains information like the code ID, description, destination IP, and port. The program sends this message every 10 seconds in an infinite loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sockfd;
struct sockaddr_in receiver_addr;
char message[] = "{\"codeId\":\"RZGC130\",\"desc\":\"udpw\",\"dist\":\"192.168.147\",\"port\":3147}";
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("Error creating socket");
return 1;
}
memset(&receiver_addr, 0, sizeof(receiver_addr));
receiver_addr.sin_family = AF_INET;
receiver_addr.sin_port = htons(3147);
if (inet_pton(AF_INET, "192.168.1.147", &receiver_addr.sin_addr) <= 0) {
perror("Invalid address ");
close(sockfd);
return 1;
}
while(1){
sendto(sockfd, message, strlen(message), 0, (const struct sockaddr *)&receiver_addr, sizeof(receiver_addr));
printf("udpw: %s\n", message);
sleep(10);
}
close(sockfd);
return 0;
}
To compile and run the code on your Raspberry Pi Zero W, follow these steps:
cd ~/RZGC130gcc udpw.c -o udpw./udpw
udpw: {"codeId":"RZGC130","desc":"udpw","dist":"192.168.147","port":3147}
udpw: {"codeId":"RZGC130","desc":"udpw","dist":"192.168.147","port":3147}
The program will continuously send the UDP message every 10 seconds, printing the message to the console.