forked from raspberrypi/pico-examples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
picow_udp_beacon.c
79 lines (66 loc) · 2.15 KB
/
picow_udp_beacon.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Copyright (c) 2022 Andrew McDonnell
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <string.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
#define UDP_PORT 4444
#define BEACON_MSG_LEN_MAX 127
#define BEACON_TARGET "255.255.255.255"
#define BEACON_INTERVAL_MS 1000
void run_udp_beacon() {
struct udp_pcb* pcb = udp_new();
ip_addr_t addr;
ipaddr_aton(BEACON_TARGET, &addr);
int counter = 0;
while (true) {
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, BEACON_MSG_LEN_MAX+1, PBUF_RAM);
char *req = (char *)p->payload;
memset(req, 0, BEACON_MSG_LEN_MAX+1);
snprintf(req, BEACON_MSG_LEN_MAX, "%d\n", counter);
err_t er = udp_sendto(pcb, p, &addr, UDP_PORT);
pbuf_free(p);
if (er != ERR_OK) {
printf("Failed to send UDP packet! error=%d", er);
} else {
printf("Sent packet %d\n", counter);
counter++;
}
// Note in practice for this simple UDP transmitter,
// the end result for both background and poll is the same
#if PICO_CYW43_ARCH_POLL
// if you are using pico_cyw43_arch_poll, then you must poll periodically from your
// main loop (not from a timer) to check for Wi-Fi driver or lwIP work that needs to be done.
cyw43_arch_poll();
sleep_ms(BEACON_INTERVAL_MS);
#else
// if you are not using pico_cyw43_arch_poll, then WiFI driver and lwIP work
// is done via interrupt in the background. This sleep is just an example of some (blocking)
// work you might be doing.
sleep_ms(BEACON_INTERVAL_MS);
#endif
}
}
int main() {
stdio_init_all();
if (cyw43_arch_init()) {
printf("failed to initialise\n");
return 1;
}
cyw43_arch_enable_sta_mode();
printf("Connecting to Wi-Fi...\n");
if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000)) {
printf("failed to connect.\n");
return 1;
} else {
printf("Connected.\n");
}
run_udp_beacon();
cyw43_arch_deinit();
return 0;
}