Compare commits

...

47 Commits

Author SHA1 Message Date
Kripesh Adhikari
bf9df10259
audio/hwopus-decoder: fix glitchy playback (#110)
* audio/hwopus-decoder: fix offset for pointer to wavebuf start
* audio/hwopus-decoder: change to 4 wavebufs and reduce size of wavebufs
2024-10-26 15:36:59 +01:00
Dave Murphy
5e36dc2902
time: display local time 2024-10-18 19:30:12 +01:00
Dave Murphy
399aa26c6e
templates/sysmodule: add force_debug_prod. Closes #109 2024-10-18 18:46:00 +01:00
Vicki Pfau
b41c4957e7
vibration: Improve vibration example usability (#107)
This update moves the frequency controls to D-Pad and lets you turn the values
down, as well as displaying the current values on screen.
2024-10-16 19:57:56 +01:00
Vicki Pfau
d1b2175d58
power: Update charger enum (#108) 2024-10-16 19:57:38 +01:00
Dave Murphy
4f6e700642
sdl2-demo: use acceleration 2024-01-20 02:21:36 +00:00
Narr the Reg
455ad6732c nfc: Update example 2023-07-04 23:17:34 +02:00
yellows8
fbbe90507d
app-playstats: Updated for latest libnx, etc. 2023-03-08 16:36:36 -05:00
yellows8
454610b266
Updated hdls example for passing workmem. 2023-02-23 10:09:09 -05:00
TurtleP
713404797b
Delete various copy constructors and assignment operators (#102)
Prevents common C++ programming mistakes
2023-01-04 21:30:48 +01:00
yellows8
73960d720c
app-playstats: Updated for 15.0.0. 2022-10-16 12:56:12 -04:00
scturtle
0947425fc5 graphics/deko3d: fix and simplify rbtree code 2022-09-14 19:16:35 +02:00
Jeremy S. Postelnek
b55cb17676
account: add code to satisfy multiple accounts (#97)
* add code to satisfy multiple accounts
2022-04-09 16:17:54 -04:00
yellows8
950e99a1ab
Updated hdls example for 13.0.0. 2021-09-17 12:42:06 -04:00
yellows8
f03b9864ce
Improved IMAGE_DISPLAY handling in simplegfx. 2021-09-13 13:25:26 -04:00
Ben Kallus
5980937bdf ChargerType -> PsmChargerType 2021-07-08 23:01:23 +02:00
yellows8
e423a0ab0e
audio/playtone: KEY -> HidNpadButton, which were missed previously. 2021-02-15 12:29:32 -05:00
yellows8
78b1ed515e
Updated for libnx applet changes. 2020-12-15 19:17:30 -05:00
yellows8
ce7c9a99ea
network/ldn: Updated button text. 2020-12-10 23:57:35 -05:00
yellows8
84be02950a
Added network/lp2p. 2020-12-10 23:52:53 -05:00
yellows8
a5f53afed0
hid/hdls: Use HiddbgNpadButton. 2020-12-08 15:39:02 -05:00
yellows8
b924d358ec
hid/read-controls: Updated comment. 2020-12-08 14:59:11 -05:00
yellows8
62885bbbff
hid/hdls: Updated for hid-refactor. 2020-12-08 13:54:25 -05:00
yellows8
ac702280bc
hid/read-controls: Updated for hid-refactor. 2020-12-08 13:52:19 -05:00
yellows8
40ec713452
hid/abstracted-pad: Updated for hid-refactor. 2020-12-08 12:56:11 -05:00
yellows8
07863f0585
hid/touch-screen: Updated for hid-refactor. 2020-12-08 10:36:50 -05:00
yellows8
a6ea828801
hid/irsensor: Updated for hid-refactor. 2020-12-08 01:03:19 -05:00
yellows8
00a0bb3899
hid/vibration: Minor adjustments. 2020-12-08 00:33:18 -05:00
yellows8
29484f5c06
hid/sevensixaxis: Updated for hid-refactor. 2020-12-08 00:23:52 -05:00
yellows8
5a42b4766b
hid/ring-con: Updated for hid-refactor. 2020-12-08 00:00:16 -05:00
yellows8
2b0d5062a5
colors/notification-led: Updated for hid-refactor. 2020-12-07 23:44:31 -05:00
fincs
1e59bd0699
Update all non-HID examples for hid-refactor 2020-12-02 14:39:00 +01:00
fincs
4272e286cc
hid/vibration: update for hid-refactor 2020-12-01 21:51:39 +01:00
fincs
8487e07653
hid/sixaxis: update for hid-refactor 2020-12-01 21:46:58 +01:00
fincs
11fa984774
templates/application: Update for hid-refactor API 2020-12-01 21:36:02 +01:00
fincs
f252e65ebd
Update & clean up the sysmodule template 2020-10-31 19:25:14 +01:00
fincs
847bb129e9
Use diagAbortWithResult instead of fatalThrow 2020-10-31 19:13:24 +01:00
Dave Murphy
fc98393d50 Add targets per Makefile, allowing make -j to work 2020-10-03 16:00:22 +01:00
Vicki Pfau
9db0cfd567 Add power example 2020-09-28 13:08:31 +02:00
Dave Murphy
c21700136e
remove stray printf 2020-07-07 02:54:53 +01:00
Dave Murphy
179e9a847b sdl2-audio: include path is set to SDL2 by pkg-config. Closes #79 2020-06-26 09:58:25 +01:00
Dave Murphy
a6de2da842 sdl2-audio: rely on pkg-config for includes & libs 2020-06-26 09:58:25 +01:00
Nichole Mattera
cb01bf3c37
Fixed SDL2 demo to not render text on every frame. (#81) 2020-06-26 09:41:59 +01:00
AdaLovegirls
ea27fe123d
Added sdl2-ttf example to sdl2-demo (#80) 2020-06-25 12:31:06 +01:00
yellows8
73b50688ab
Added -lm to the swkbd example Makefile. 2020-06-14 00:08:11 -04:00
yellows8
4437fb814f
Added a comment for the swkbd example. 2020-06-11 22:56:04 -04:00
yellows8
1392e6cad0
Added hid/sevensixaxis example. 2020-06-01 12:16:15 -04:00
92 changed files with 2428 additions and 731 deletions

View File

@ -1,13 +1,19 @@
MAKEFILES := $(shell find . -mindepth 2 -name Makefile)
MAKEFILES := $(subst ./,,$(shell find . -mindepth 2 -name Makefile))
TARGETS := $(dir $(MAKEFILES))
DATESTRING := $(shell date +%Y)$(shell date +%m)$(shell date +%d)
all:
@for i in $(MAKEFILES); do $(MAKE) -C `dirname $$i` || exit 1; done;
all: $(TARGETS)
.PHONY: $(TARGETS)
$(TARGETS):
@$(MAKE) -C $@
clean:
@rm -f *.bz2
@for i in $(MAKEFILES); do $(MAKE) -C `dirname $$i` clean || exit 1; done;
@for i in $(TARGETS); do $(MAKE) -C $$i clean || exit 1; done;
dist: clean
@tar -cvjf switch-examples-$(DATESTRING).tar.bz2 *

View File

@ -18,6 +18,13 @@ int main(int argc, char **argv)
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
memset(&userdata, 0, sizeof(userdata));
memset(&profilebase, 0, sizeof(profilebase));
@ -30,7 +37,17 @@ int main(int argc, char **argv)
rc = accountGetPreselectedUser(&userID);
if (R_FAILED(rc)) {
printf("accountGetPreselectedUser() failed: 0x%x\n", rc);
printf("accountGetPreselectedUser() failed: 0x%x, using pselShowUserSelector..\n", rc);
/* Create player selection UI settings */
PselUserSelectionSettings settings;
memset(&settings, 0, sizeof(settings));
rc = pselShowUserSelector(&userID, &settings);
if (R_FAILED(rc)) {
printf("pselShowUserSelector() failed: 0x%x\n", rc);
}
}
if (R_SUCCEEDED(rc)) {
@ -68,13 +85,13 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -37,6 +37,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("alarm-notifications example\n");
Result rc=0, rc2=0;
@ -75,14 +82,14 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (R_SUCCEEDED(rc) && R_SUCCEEDED(eventWait(&alarmevent, 0))) { // Some official apps don't use this. See libnx notif.h for this.
@ -96,7 +103,7 @@ int main(int argc, char* argv[])
}
if (R_SUCCEEDED(rc)) {
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
// Setup an alarm with {current local-time} + {2 minutes}. You can use any weekday/time you want.
// See libnx notif.h for more notifAlarmSetting*() funcs.
@ -121,7 +128,7 @@ int main(int argc, char* argv[])
if (R_SUCCEEDED(rc)) printf("alarm_setting_id = 0x%x\n", alarm_setting_id);
}
}
else if (kDown & KEY_B) {
else if (kDown & HidNpadButton_B) {
// List the Alarms.
total_out=0;
@ -160,8 +167,8 @@ int main(int argc, char* argv[])
}
}
}
else if ((kDown & KEY_X) && alarm_setting_id) {
// Delete the AlarmSetting which was registered with the KEY_A block.
else if ((kDown & HidNpadButton_X) && alarm_setting_id) {
// Delete the AlarmSetting which was registered with the HidNpadButton_A block.
// If wanted, you can also use this with alarm_settings[alarmi].alarm_setting_id with the output from notifListAlarmSettings.
rc = notifDeleteAlarmSetting(alarm_setting_id);
printf("notifDeleteAlarmSetting(): 0x%x\n", rc);

View File

@ -19,6 +19,13 @@ int main(int argc, char **argv)
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
buf = (NsApplicationControlData*)malloc(sizeof(NsApplicationControlData));
if (buf==NULL) {
rc = MAKERESULT(Module_Libnx, LibnxError_OutOfMemory);
@ -69,13 +76,13 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -20,6 +20,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("application play-stats example\n");
Result rc=0;
@ -53,17 +60,17 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
// Use appletQueryApplicationPlayStatisticsByUid if you want playstats for a specific userID.
memset(stats, 0, sizeof(stats));
@ -79,12 +86,12 @@ int main(int argc, char* argv[])
printf("total_out: %d\n", total_out);
for (i=0; i<total_out; i++) {
printf("%d: ", i);
printf("application_id = 0x%08lX, totalPlayTime = %lu (%llu seconds), totalLaunches = %lu\n", stats[i].application_id, stats[i].totalPlayTime, stats[i].totalPlayTime / 1000000000ULL, stats[i].totalLaunches);
printf("application_id = 0x%08lX, playtime = %lu (%lu seconds), total_launches = %lu\n", stats[i].application_id, stats[i].playtime, stats[i].playtime / 1000000000UL, stats[i].total_launches);
}
}
}
if (initflag && (kDown & KEY_X)) {
if (initflag && (kDown & HidNpadButton_X)) {
memset(events, 0, sizeof(events));
total_out = 0;
@ -94,10 +101,10 @@ int main(int argc, char* argv[])
if (R_SUCCEEDED(rc)) {
printf("total_out: %d\n", total_out);
for (i=0; i<total_out; i++) {
time_t tmptime = pdmPlayTimestampToPosix(events[i].timestampUser);
time_t tmptime = events[i].timestamp_user;
printf("%d: ", i);
printf("program_id = 0x%08lX, entry_index = 0x%x, timestampUser = %u, timestampNetwork = %u, eventType = %u, timestampUser = %s\n", events[i].program_id, events[i].entry_index, events[i].timestampUser, events[i].timestampNetwork, events[i].eventType, ctime(&tmptime));
printf("program_id = 0x%08lX, entry_index = 0x%x, timestamp_user = %lu, timestamp_network = %lu, event_type = %u, timestamp_user = %s\n", events[i].program_id, events[i].entry_index, events[i].timestamp_user, events[i].timestamp_network, events[i].event_type, ctime(&tmptime));
}
}
@ -105,12 +112,12 @@ int main(int argc, char* argv[])
PdmPlayStatistics playstats[1]={0};
rc = pdmqryQueryPlayStatisticsByApplicationId(application_ids[0], false, &playstats[0]);
printf("pdmqryQueryPlayStatisticsByApplicationId(): 0x%x\n", rc);
if (R_SUCCEEDED(rc)) printf("application_id = 0x%08lX, playtimeMinutes = %u, totalLaunches = %u\n", playstats[0].application_id, playstats[0].playtimeMinutes, playstats[0].totalLaunches);
if (R_SUCCEEDED(rc)) printf("program_id = 0x%016lX, playtime = %lu (%lu seconds), total_launches = %u\n", playstats[0].program_id, playstats[0].playtime, playstats[0].playtime / 1000000000UL, playstats[0].total_launches);
// Get PdmPlayStatistics for the specified ApplicationId and user.
rc = pdmqryQueryPlayStatisticsByApplicationIdAndUserAccountId(application_ids[0], preselected_uid, false, &playstats[0]);
printf("pdmqryQueryPlayStatisticsByApplicationIdAndUserAccountId(): 0x%x\n", rc);
if (R_SUCCEEDED(rc)) printf("application_id = 0x%08lX, playtimeMinutes = %u, totalLaunches = %u\n", playstats[0].application_id, playstats[0].playtimeMinutes, playstats[0].totalLaunches);
if (R_SUCCEEDED(rc)) printf("program_id = 0x%016lX, playtime = %lu (%lu seconds), total_launches = %u\n", playstats[0].program_id, playstats[0].playtime, playstats[0].playtime / 1000000000UL, playstats[0].total_launches);
// Get a listing of PdmLastPlayTime for the specified applications.
PdmLastPlayTime playtimes[1]={0};
@ -118,7 +125,7 @@ int main(int argc, char* argv[])
printf("pdmqryQueryLastPlayTime(): 0x%x, %d\n", rc, total_out);
if (R_SUCCEEDED(rc)) {
for (i=0; i<total_out; i++)
printf("%d: timestampUser = %lu\n", i, pdmPlayTimestampToPosix(playtimes[i].timestampUser));
printf("%d: timestamp_user = %lu\n", i, pdmPlayTimestampToPosix(playtimes[i].timestamp_user));
}
// Get the available range for reading events, see pdm.h.
@ -126,12 +133,17 @@ int main(int argc, char* argv[])
rc = pdmqryGetAvailablePlayEventRange(&total_entries, &start_entryindex, &end_entryindex);
printf("pdmqryGetAvailablePlayEventRange(): 0x%x, 0x%x, 0x%x, 0x%x\n", rc, total_entries, start_entryindex, end_entryindex);
// Get a listing of applications recently played by the specified user.
rc = pdmqryQueryRecentlyPlayedApplication(preselected_uid, false, application_ids, 1, &total_out);
printf("pdmqryQueryRecentlyPlayedApplication(): 0x%x, %d\n", rc, total_out);
// Get account events.
PdmAccountEvent accevents[5]={};
rc = pdmqryQueryAccountEvent(0, accevents, 5, &total_out);
printf("pdmqryQueryAccountEvent(): 0x%x\n", rc);
if (R_SUCCEEDED(rc)) {
for (i=0; i<total_out; i++)
printf("%d: application_id = 0x%08lX\n", i, application_ids[i]);
printf("total_out: %d\n", total_out);
for (i=0; i<total_out; i++) {
time_t tmptime = accevents[i].timestamp_user;
printf("%d: ", i);
printf("uid = 0x%lx 0x%lx, program_id = 0x%016lX, entry_index = 0x%x, timestamp_user = %lu, timestamp_network = %lu, event_type = %u, timestamp_user = %s\n", accevents[i].uid.uid[0], accevents[i].uid.uid[1], accevents[i].program_id, accevents[i].entry_index, accevents[i].timestamp_user, accevents[i].timestamp_network, accevents[i].type, ctime(&tmptime));
}
}
// For more cmds, see pdm.h.

View File

@ -24,6 +24,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("error example\n");
consoleUpdate(NULL);
@ -34,17 +41,17 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
printf("Running errorResultRecordShow()...\n");
consoleUpdate(NULL);
rc = errorResultRecordShow(MAKERESULT(16, 250), time(NULL));

View File

@ -23,6 +23,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("pctlauth example\n");
consoleUpdate(NULL);
@ -47,17 +54,17 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (pctlflag && (kDown & KEY_A)) {
if (pctlflag && (kDown & HidNpadButton_A)) {
printf("Running pctlauthShow()...\n");
consoleUpdate(NULL);
rc = pctlauthShow(true); // Launch the applet for validating the PIN.

View File

@ -59,7 +59,7 @@ CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
LIBS := -lnx -lm
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing

View File

@ -57,6 +57,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("swkbd example\n");
consoleUpdate(NULL);
@ -107,6 +114,7 @@ int main(int argc, char* argv[])
swkbdInlineSetFinishedInitializeCallback(&kbdinline, finishinit_cb);
// Launch the applet.
// If you want to display the image manually, you can also use swkbdInlineLaunch and swkbdInlineGetImageMemoryRequirement/swkbdInlineGetImage.
if (R_SUCCEEDED(rc)) {
rc = swkbdInlineLaunchForLibraryApplet(&kbdinline, SwkbdInlineMode_AppletDisplay, 0);
printf("swkbdInlineLaunch(): 0x%x\n", rc);
@ -141,21 +149,21 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Your code goes here
if (R_SUCCEEDED(rc)) {
if (kDown & KEY_ZR) swkbdInlineDisappear(&kbdinline); //Optional, you can have swkbd (dis)appear whenever.
if (kDown & KEY_Y) swkbdInlineAppear(&kbdinline, &appearArg); // If you use swkbdInlineAppear again after text was submitted, you may want to use swkbdInlineSetInputText since the current-text will be the same as when it was submitted otherwise.
if (kDown & HidNpadButton_ZR) swkbdInlineDisappear(&kbdinline); //Optional, you can have swkbd (dis)appear whenever.
if (kDown & HidNpadButton_Y) swkbdInlineAppear(&kbdinline, &appearArg); // If you use swkbdInlineAppear again after text was submitted, you may want to use swkbdInlineSetInputText since the current-text will be the same as when it was submitted otherwise.
rc = swkbdInlineUpdate(&kbdinline, NULL); // Handles updating SwkbdInline state, this should be called periodically.
if (R_FAILED(rc)) printf("swkbdInlineUpdate(): 0x%x\n", rc);

View File

@ -23,6 +23,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("web example\n");
consoleUpdate(NULL);
@ -33,17 +40,17 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
WebCommonConfig config;
WebCommonReply reply;
WebExitReason exitReason=0;

View File

@ -18,6 +18,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("light-sensor example\n");
printf("Press A to check light-sensor.\n");
printf("Press + to exit.\n");
@ -25,17 +32,17 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
Result rc = 0;
float fLux=0;
bool availableflag=0;

View File

@ -22,19 +22,26 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("applet exit-locking example.\n");
// Main loop
while (appletMainLoop())//This loop will automatically exit when applet requests exit.
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Your code goes here

View File

@ -28,22 +28,29 @@ int main(int argc, char **argv)
appletInitializeGamePlayRecording();//Normally this is only recording func you need to call.
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
u32 cnt = 0;
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
if (kDown & KEY_Y) {
if (kDown & HidNpadButton_Y) {
appletSetGamePlayRecordingState(0);//Disable recording.
}
else if (kDown & KEY_X) {
else if (kDown & HidNpadButton_X) {
appletSetGamePlayRecordingState(1);//Enable recording.
}

View File

@ -18,6 +18,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("screenshot-overlay example\n");
// Setup the RGBA8 image.
@ -56,14 +63,14 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Update the console, sending a new frame to the display

View File

@ -24,6 +24,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("VrMode example\n");
// Using pctl is optional.
@ -43,18 +50,18 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (pctlinit) {
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
// Not sure what this is.
/*rc = pctlConfirmStereoVisionPermission();
if (R_FAILED(rc)) printf("pctlConfirmStereoVisionPermission(): 0x%x\n", rc);*/
@ -70,7 +77,7 @@ int main(int argc, char* argv[])
printf("appletSetVrModeEnabled(true): 0x%x\n", rc);
}
}
else if (kDown & KEY_B) {
else if (kDown & HidNpadButton_B) {
rc = appletSetVrModeEnabled(false);
printf("appletSetVrModeEnabled(false): 0x%x\n", rc);
@ -78,7 +85,7 @@ int main(int argc, char* argv[])
/*rc = pctlResetConfirmedStereoVisionPermission();
printf("pctlResetConfirmedStereoVisionPermission(): 0x%x\n", rc);*/
}
else if (kDown & KEY_X) {
else if (kDown & HidNpadButton_X) {
bool flag=0;
rc = appletIsVrModeEnabled(&flag);
printf("appletIsVrModeEnabled(): 0x%x", rc);

View File

@ -13,6 +13,13 @@ int main(void)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("Simple audren demonstration program\n");
static const AudioRendererConfig arConfig =
@ -57,7 +64,7 @@ int main(void)
audrvMemPoolAttach(&drv, mpid);
static const u8 sink_channels[] = { 0, 1 };
int sink = audrvDeviceSinkAdd(&drv, AUDREN_DEFAULT_DEVICE_NAME, 2, sink_channels);
/*int sink =*/ audrvDeviceSinkAdd(&drv, AUDREN_DEFAULT_DEVICE_NAME, 2, sink_channels);
res = audrvUpdate(&drv);
printf("audrvUpdate: %" PRIx32 "\n", res);
@ -77,16 +84,16 @@ int main(void)
// Main loop
while (appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break;
if (initedDriver)
{
if (kDown & KEY_A)
if (kDown & HidNpadButton_A)
{
audrvVoiceStop(&drv, 0);
audrvVoiceAddWaveBuf(&drv, 0, &wavebuf);

View File

@ -22,6 +22,13 @@ int main(int argc, char **argv)
// Initialize console. Using NULL as the second argument tells the console library to use the internal console structure as current one.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
AudioInBuffer audin_buf;
AudioOutBuffer audout_buf;
AudioInBuffer *released_in_buffer;
@ -108,13 +115,13 @@ int main(int argc, char **argv)
while (appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
// Wait for audio capture and playback to finish.
audinWaitCaptureFinish(&released_in_buffer, &released_in_count, UINT64_MAX);

View File

@ -53,6 +53,13 @@ int main(void)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("Simple hwopus-decoder example with audren\n");
static const AudioRendererConfig arConfig =
@ -67,15 +74,15 @@ int main(void)
size_t num_channels = 1;
size_t samplerate = 48000;
size_t max_samples = samplerate;
size_t max_samples = samplerate/20;//each wavebuf can hold upto 1sec/20 = 50ms of audio data
size_t max_samples_datasize = max_samples*num_channels*sizeof(opus_int16);
size_t mempool_size = (max_samples_datasize*2 + 0xFFF) &~ 0xFFF;//*2 for 2 wavebufs.
size_t mempool_size = (max_samples_datasize*4 + 0xFFF) &~ 0xFFF;//*4 for 4 wavebufs.
void* mempool_ptr = memalign(0x1000, mempool_size);
void* tmpdata_ptr = malloc(max_samples_datasize);
opuspkt_tmpbuf = (u8*)malloc(opuspkt_tmpbuf_size);
opus_int16* curbuf = NULL;
AudioDriverWaveBuf wavebuf[2] = {0};
AudioDriverWaveBuf wavebuf[4] = {0};
int i, wavei;
HwopusDecoder hwdecoder = {0};
@ -122,7 +129,7 @@ int main(void)
audrvMemPoolAttach(&drv, mpid);
static const u8 sink_channels[] = { 0, 1 };
int sink = audrvDeviceSinkAdd(&drv, AUDREN_DEFAULT_DEVICE_NAME, 2, sink_channels);
/*int sink =*/ audrvDeviceSinkAdd(&drv, AUDREN_DEFAULT_DEVICE_NAME, 2, sink_channels);
res = audrvUpdate(&drv);
printf("audrvUpdate: %" PRIx32 "\n", res);
@ -144,9 +151,9 @@ int main(void)
}
audrvVoiceStart(&drv, 0);
for(i=0; i<2; i++) {
for(i=0; i<4; i++) {
wavebuf[i].data_raw = mempool_ptr;
wavebuf[i].size = max_samples_datasize*2;//*2 for 2 wavebufs.
wavebuf[i].size = max_samples_datasize*4;//*4 for 4 wavebufs.
wavebuf[i].start_sample_offset = i * max_samples;
wavebuf[i].end_sample_offset = wavebuf[i].start_sample_offset + max_samples;
}
@ -163,16 +170,16 @@ int main(void)
// Main loop
while (appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break;
if (initedDriver)
{
if (kDown & KEY_A)
if (kDown & HidNpadButton_A)
{
//Close the opus-file if needed and (re)open it, since libopusfile doesn't support seek-to-beginning.
if (of)
@ -191,7 +198,7 @@ int main(void)
if (audio_playing) {
wavei = -1;
for(i=0; i<2; i++) {
for(i=0; i<4; i++) {
if (wavebuf[i].state == AudioDriverWaveBufState_Free || wavebuf[i].state == AudioDriverWaveBufState_Done) {
wavei = i;
break;
@ -199,7 +206,7 @@ int main(void)
}
if (wavei >= 0) {
curbuf = (opus_int16*)(mempool_ptr + wavebuf[wavei].start_sample_offset);
curbuf = (opus_int16*)(mempool_ptr + wavebuf[wavei].start_sample_offset * sizeof(opus_int16));
opret = op_read(of, tmpdata_ptr, max_samples * num_channels, NULL);//The buffer used here has to be seperate from mempool_ptr.
if (opret < 0)

View File

@ -38,6 +38,13 @@ int main(int argc, char **argv)
// Initialize console. Using NULL as the second argument tells the console library to use the internal console structure as current one.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
AudioOutBuffer audout_buf;
AudioOutBuffer *audout_released_buf;
@ -82,81 +89,81 @@ int main(int argc, char **argv)
while (appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
if (kDown & KEY_A)
if (kDown & HidNpadButton_A)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[0]);
play_tone = true;
}
if (kDown & KEY_B)
if (kDown & HidNpadButton_B)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[1]);
play_tone = true;
}
if (kDown & KEY_Y)
if (kDown & HidNpadButton_Y)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[2]);
play_tone = true;
}
if (kDown & KEY_X)
if (kDown & HidNpadButton_X)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[3]);
play_tone = true;
}
if (kDown & KEY_DLEFT)
if (kDown & HidNpadButton_Left)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[4]);
play_tone = true;
}
if (kDown & KEY_DUP)
if (kDown & HidNpadButton_Up)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[5]);
play_tone = true;
}
if (kDown & KEY_DRIGHT)
if (kDown & HidNpadButton_Right)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[6]);
play_tone = true;
}
if (kDown & KEY_DDOWN)
if (kDown & HidNpadButton_Down)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[7]);
play_tone = true;
}
if (kDown & KEY_L)
if (kDown & HidNpadButton_L)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[8]);
play_tone = true;
}
if (kDown & KEY_R)
if (kDown & HidNpadButton_R)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[9]);
play_tone = true;
}
if (kDown & KEY_ZL)
if (kDown & HidNpadButton_ZL)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[10]);
play_tone = true;
}
if (kDown & KEY_ZR)
if (kDown & HidNpadButton_ZR)
{
fill_audio_buffer(out_buf_data, 0, data_size, notefreq[11]);
play_tone = true;

View File

@ -52,20 +52,20 @@ ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += -D__SWITCH__ $(INCLUDE) `aarch64-none-elf-pkg-config --cflags SDL2_mixer`
CFLAGS += -D__SWITCH__ $(INCLUDE) `$(PREFIX)pkg-config --cflags SDL2_mixer`
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := `aarch64-none-elf-pkg-config --libs SDL2_mixer`
LIBS := `$(PREFIX)pkg-config --libs SDL2_mixer`
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
LIBDIRS := $(LIBNX)
#---------------------------------------------------------------------------------

View File

@ -7,8 +7,8 @@
#include <switch.h>
// Include sdl2 headers
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <SDL.h>
#include <SDL_mixer.h>
// Main program entrypoint
int main(int argc, char *argv[])
@ -17,6 +17,13 @@ int main(int argc, char *argv[])
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc = romfsInit();
if (R_FAILED(rc))
printf("romfsInit: %08X\n", rc);
@ -41,17 +48,17 @@ int main(int argc, char *argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & KEY_A)
if (kDown & HidNpadButton_A)
Mix_PlayMusic(audio, 1); //Play the audio file
// Update the console, sending a new frame to the display

View File

@ -47,6 +47,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("Triggering crash...\n");
consoleUpdate(NULL);
@ -56,14 +63,14 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Your code goes here

View File

@ -32,6 +32,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc = romfsInit();
if (R_FAILED(rc))
printf("romfsInit: %08X\n", rc);
@ -46,13 +53,13 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -51,6 +51,13 @@ int main(int argc, char **argv)
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
//Get the userID for save mounting. To mount common savedata, use an all-zero userID.
//Try to find savedata to use with get_save() first, otherwise fallback to the above hard-coded TID + the userID from accountGetPreselectedUser(). Note that you can use either method.
@ -113,13 +120,13 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -11,6 +11,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
DIR* dir;
struct dirent* ent;
@ -33,13 +40,13 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -209,12 +209,19 @@ int main(int argc, char* argv[])
romfsInit();
graphicsInitialize();
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
while (appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
graphicsUpdate();

View File

@ -7,6 +7,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// clear screen and home cursor
printf( CONSOLE_ESC(2J) );
@ -61,15 +68,15 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -4,7 +4,7 @@ void userAppInit(void)
{
Result res = romfsInit();
if (R_FAILED(res))
fatalThrow(res);
diagAbortWithResult(res);
}
void userAppExit(void)

View File

@ -24,6 +24,8 @@ class CExample01 final : public CApplication
static constexpr uint32_t FramebufferHeight = 720;
static constexpr unsigned StaticCmdSize = 0x1000;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -59,6 +61,10 @@ public:
// Create the framebuffer resources
createFramebufferResources();
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample01()
@ -159,9 +165,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
render();

View File

@ -51,6 +51,8 @@ class CExample02 final : public CApplication
static constexpr uint32_t FramebufferHeight = 720;
static constexpr unsigned StaticCmdSize = 0x10000;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -101,6 +103,10 @@ public:
// Create the framebuffer resources
createFramebufferResources();
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample02()
@ -214,9 +220,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
render();

View File

@ -104,6 +104,8 @@ class CExample03 final : public CApplication
static constexpr unsigned StaticCmdSize = 0x10000;
static constexpr unsigned DynamicCmdSize = 0x10000;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -169,6 +171,10 @@ public:
// Load the vertex buffer
vertexBuffer = pool_data->allocate(sizeof(CubeVertexData), alignof(Vertex));
memcpy(vertexBuffer.getCpuAddr(), CubeVertexData.data(), vertexBuffer.getSize());
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample03()
@ -339,9 +345,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -109,6 +109,8 @@ class CExample04 final : public CApplication
static constexpr unsigned MaxImages = 1;
static constexpr unsigned MaxSamplers = 1;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -210,6 +212,10 @@ public:
queue.waitIdle();
cmdbuf.clear();
}
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample04()
@ -381,9 +387,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -52,6 +52,8 @@ class CExample05 final : public CApplication
static constexpr uint32_t FramebufferHeight = 720;
static constexpr unsigned StaticCmdSize = 0x10000;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -106,6 +108,10 @@ public:
// Create the framebuffer resources
createFramebufferResources();
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample05()
@ -236,9 +242,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
render();

View File

@ -104,6 +104,8 @@ class CExample06 final : public CApplication
static constexpr unsigned DynamicCmdSize = 0x10000;
static constexpr DkMsMode MultisampleMode = DkMsMode_4x;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -171,6 +173,10 @@ public:
// Load the vertex buffer
vertexBuffer = pool_data->allocate(sizeof(CubeVertexData), alignof(Vertex));
memcpy(vertexBuffer.getCpuAddr(), CubeVertexData.data(), vertexBuffer.getSize());
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample06()
@ -375,9 +381,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -74,6 +74,8 @@ class CExample07 final : public CApplication
static constexpr unsigned DynamicCmdSize = 0x10000;
static constexpr DkMsMode MultisampleMode = DkMsMode_4x;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -154,6 +156,10 @@ public:
// Load the teapot mesh
vertexBuffer = LoadFile(*pool_data, "romfs:/teapot-vtx.bin", alignof(Vertex));
indexBuffer = LoadFile(*pool_data, "romfs:/teapot-idx.bin", alignof(u16));
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample07()
@ -368,9 +374,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -76,6 +76,8 @@ class CExample08 final : public CApplication
static constexpr unsigned MaxImages = 3;
static constexpr unsigned MaxSamplers = 1;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -188,6 +190,10 @@ public:
queue.waitIdle();
cmdbuf.clear();
}
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
void createFramebufferResources()
@ -449,9 +455,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -69,6 +69,8 @@ class CExample09 final : public CApplication
static constexpr unsigned DynamicCmdSize = 0x10000;
static constexpr unsigned NumVertices = 256;
PadState pad;
dk::UniqueDevice device;
dk::UniqueQueue queue;
@ -138,6 +140,10 @@ public:
// Create the framebuffer resources
createFramebufferResources();
// Initialize gamepad
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
}
~CExample09()
@ -291,9 +297,9 @@ public:
bool onFrame(u64 ns) override
{
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
return false;
float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision

View File

@ -20,7 +20,7 @@ void CApplication::run()
{
u64 tick_ref = armGetSystemTick();
u64 tick_saved = tick_ref;
bool focused = appletGetFocusState() == AppletFocusState_Focused;
bool focused = appletGetFocusState() == AppletFocusState_InFocus;
onOperationMode(appletGetOperationMode());
@ -40,7 +40,7 @@ void CApplication::run()
{
bool old_focused = focused;
AppletFocusState state = appletGetFocusState();
focused = state == AppletFocusState_Focused;
focused = state == AppletFocusState_InFocus;
onFocusState(state);
if (focused == old_focused)

View File

@ -30,7 +30,7 @@ constexpr void CApplication::chooseFramebufferSize(uint32_t& width, uint32_t& he
width = 1280;
height = 720;
break;
case AppletOperationMode_Docked:
case AppletOperationMode_Console:
width = 1920;
height = 1080;
break;

View File

@ -15,6 +15,11 @@ class CCmdMemRing
dk::Fence m_fences[NumSlices];
public:
CCmdMemRing() : m_mem{}, m_curSlice{}, m_fences{} { }
CCmdMemRing(const CCmdMemRing&) = delete;
CCmdMemRing& operator=(const CCmdMemRing&) = delete;
~CCmdMemRing()
{
m_mem.destroy();

View File

@ -18,6 +18,11 @@ class CDescriptorSet
CMemPool::Handle m_mem;
public:
CDescriptorSet() : m_mem{} { }
CDescriptorSet(const CDescriptorSet&) = delete;
CDescriptorSet& operator=(const CDescriptorSet&) = delete;
~CDescriptorSet()
{
m_mem.destroy();

View File

@ -13,6 +13,11 @@ class CExternalImage
CMemPool::Handle m_mem;
public:
CExternalImage() : m_image{}, m_descriptor{}, m_mem{} { }
CExternalImage(const CExternalImage&) = delete;
CExternalImage& operator=(const CExternalImage&) = delete;
~CExternalImage()
{
m_mem.destroy();

View File

@ -192,7 +192,7 @@ void CIntrusiveTreeBase::remove(N* node)
}
else
{
child = node->left() ? node->right() : node->left();
child = node->left() ? node->left() : node->right();
parent = node->getParent();
color = node->getColor();

View File

@ -173,7 +173,7 @@ public:
T* first() const { return toType(minmax(N::Left)); }
T* last() const { return toType(minmax(N::Right)); }
bool empty() const { return m_root != nullptr; }
bool empty() const { return m_root == nullptr; }
void clear() { m_root = nullptr; }
T* prev(T* node) const { return toType(walk(toNode(node), N::Left)); }
@ -194,31 +194,11 @@ public:
mode != UpperBound ? N::Left : N::Right,
[&lambda](N* curnode) { return lambda(toType(curnode)); });
switch (mode)
{
default:
case Exact:
break;
case LowerBound:
if (!node && parent)
{
if (&parent->left() == &point)
node = parent;
else
node = walk(parent, N::Right);
}
break;
case UpperBound:
if (node)
if (mode != Exact) {
if (mode == UpperBound && node)
node = walk(node, N::Right);
else if (parent)
{
if (&parent->right() == &point)
node = walk(parent, N::Right);
else
node = parent;
}
break;
else if (!node && parent)
node = &parent->left() == &point ? parent : walk(parent, N::Right);
}
return toType(node);
}

View File

@ -20,6 +20,10 @@ class CMemPool
void* m_cpuAddr;
DkGpuAddr m_gpuAddr;
Block(const Block&) = delete;
Block& operator=(const Block&) = delete;
constexpr void* cpuOffset(uint32_t offset) const
{
return m_cpuAddr ? ((u8*)m_cpuAddr + offset) : nullptr;
@ -42,6 +46,10 @@ class CMemPool
uint32_t m_start;
uint32_t m_end;
Slice(const Slice&) = delete;
Slice& operator=(const Slice&) = delete;
constexpr uint32_t getSize() const { return m_end - m_start; }
constexpr bool canCoalesce(Slice const& rhs) const { return m_pool == rhs.m_pool && m_block == rhs.m_block && m_end == rhs.m_start; }
@ -109,9 +117,14 @@ public:
CMemPool(dk::Device dev, uint32_t flags = DkMemBlockFlags_CpuUncached | DkMemBlockFlags_GpuCached, uint32_t blockSize = DefaultBlockSize) :
m_dev{dev}, m_flags{flags}, m_blockSize{blockSize}, m_blocks{}, m_memMap{}, m_sliceHeap{}, m_freeList{} { }
~CMemPool();
Handle allocate(uint32_t size, uint32_t alignment = DK_CMDMEM_ALIGNMENT);
CMemPool(const CMemPool&) = delete;
CMemPool& operator=(const CMemPool&) = delete;
};
constexpr bool operator<(uint32_t lhs, CMemPool::Slice const& rhs)

View File

@ -12,6 +12,11 @@ class CShader
CMemPool::Handle m_codemem;
public:
CShader() : m_shader{}, m_codemem{} { }
CShader(const CShader&) = delete;
CShader& operator=(const CShader&) = delete;
~CShader()
{
m_codemem.destroy();

View File

@ -15,7 +15,7 @@ extern "C" void userAppInit(void)
{
Result res = romfsInit();
if (R_FAILED(res))
fatalThrow(res);
diagAbortWithResult(res);
#ifdef DEBUG_NXLINK
socketInitializeDefault();

View File

@ -46,6 +46,8 @@ class CMainMenu final : public CApplication
static constexpr unsigned EntriesPerScreen = 39;
static constexpr unsigned EntryPageLength = 10;
PadState pad;
int screenPos;
int selectPos;
@ -69,6 +71,10 @@ class CMainMenu final : public CApplication
{
consoleInit(NULL);
renderMenu();
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
padInitializeDefault(&pad);
padUpdate(&pad);
}
~CMainMenu()
@ -79,23 +85,23 @@ class CMainMenu final : public CApplication
bool onFrame(u64 ns) override
{
int oldPos = selectPos;
hidScanInput();
padUpdate(&pad);
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
{
selectPos = -1;
return false;
}
if (kDown & KEY_A)
if (kDown & HidNpadButton_A)
return false;
if (kDown & KEY_UP)
if (kDown & HidNpadButton_AnyUp)
selectPos -= 1;
if (kDown & KEY_DOWN)
if (kDown & HidNpadButton_AnyDown)
selectPos += 1;
if (kDown & KEY_LEFT)
if (kDown & HidNpadButton_AnyLeft)
selectPos -= EntryPageLength;
if (kDown & KEY_RIGHT)
if (kDown & HidNpadButton_AnyRight)
selectPos += EntryPageLength;
if (selectPos < 0)

View File

@ -1,4 +1,4 @@
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <switch.h>
@ -430,16 +430,16 @@ static void sceneUpdate(u32 kHeld)
float deltaTime = curTime - s_updTime;
s_updTime = curTime;
if (kHeld & KEY_LEFT)
if (kHeld & HidNpadButton_AnyLeft)
s_cameraAngle = fract(s_cameraAngle - deltaTime/4);
else if (kHeld & KEY_RIGHT)
else if (kHeld & HidNpadButton_AnyRight)
s_cameraAngle = fract(s_cameraAngle + deltaTime/4);
if (kHeld & (KEY_UP|KEY_DOWN))
if (kHeld & (HidNpadButton_AnyUp|HidNpadButton_AnyDown))
{
glm::vec3 front = deltaTime * glm::rotate(glm::vec3{0.0f, 0.0f, -1.0f}, s_cameraAngle * TAU, glm::vec3{0.0f, -1.0f, 0.0f});
if (kHeld & KEY_UP)
if (kHeld & HidNpadButton_AnyUp)
s_cameraPos += front;
else if (kHeld & KEY_DOWN)
else if (kHeld & HidNpadButton_AnyDown)
s_cameraPos -= front;
}
@ -464,7 +464,7 @@ static void configureResolution(NWindow* win, bool halved)
width = 1280;
height = 720;
break;
case AppletOperationMode_Docked:
case AppletOperationMode_Console:
width = 1920;
height = 1080;
break;
@ -525,17 +525,24 @@ int main(int argc, char* argv[])
// Initialize our scene
sceneInit();
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Main graphics loop
while (appletMainLoop())
{
// Get and process input
hidScanInput();
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u32 kHeld = hidKeysHeld(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u32 kDown = padGetButtonsDown(&pad);
u32 kHeld = padGetButtons(&pad);
if (kDown & HidNpadButton_Plus)
break;
bool shouldHalveResolution = !!(kHeld & KEY_A);
bool shouldHalveResolution = !!(kHeld & HidNpadButton_A);
// Configure the resolution used to render the scene, which
// will be different in handheld mode/docked mode.

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (C) 1999-2001 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
@ -855,13 +855,20 @@ int main(int argc, char* argv[])
gears_init();
gears_reshape(1280, 720);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Main graphics loop
while (appletMainLoop())
{
// Get and process input
hidScanInput();
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break;
// Render stuff!

View File

@ -7,6 +7,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// clear screen and home cursor
printf( CONSOLE_ESC(2J) );
@ -46,15 +53,15 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -1,4 +1,4 @@
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <switch.h>
@ -414,13 +414,20 @@ int main(int argc, char* argv[])
// Initialize our scene
sceneInit();
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Main graphics loop
while (appletMainLoop())
{
// Get and process input
hidScanInput();
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break;
// Update our scene

View File

@ -325,13 +325,20 @@ int main(int argc, char* argv[])
// Initialize our scene
sceneInit();
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Main graphics loop
while (appletMainLoop())
{
// Get and process input
hidScanInput();
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break;
// Render stuff!

View File

@ -514,13 +514,20 @@ int main(int argc, char* argv[])
// Initialize our scene
sceneInit();
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Main graphics loop
while (appletMainLoop())
{
// Get and process input
hidScanInput();
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
padUpdate(&pad);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break;
// Update our scene

View File

@ -8,6 +8,13 @@ int main(int argc, char **argv)
//Initialize console. Using NULL as the second argument tells the console library to use the internal console structure as current one.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
//Move the cursor to row 16 and column 20 and then prints "Hello World!"
//To move the cursor you have to print "\x1b[r;cH", where r and c are respectively
//the row and column where you want your cursor to move
@ -15,13 +22,13 @@ int main(int argc, char **argv)
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -7,6 +7,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// clear screen and home cursor
printf( CONSOLE_ESC(2J) );
@ -61,15 +68,15 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -62,7 +62,7 @@ CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := `$(PREFIX)pkg-config --libs sdl2 SDL2_mixer SDL2_image` \
LIBS := `$(PREFIX)pkg-config --libs sdl2 SDL2_mixer SDL2_image SDL2_ttf` \
-lnx
#---------------------------------------------------------------------------------

View File

@ -1,5 +1,5 @@
/* Mini SDL Demo
* featuring SDL2 + SDL2_mixer + SDL2_image
* featuring SDL2 + SDL2_mixer + SDL2_image + SDL2_ttf
* on Nintendo Switch using libnx
*
* Copyright 2018 carsten1ns
@ -25,6 +25,7 @@
#include <SDL.h>
#include <SDL_mixer.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <switch.h>
// some switch buttons
@ -42,6 +43,21 @@
#define SCREEN_W 1280
#define SCREEN_H 720
SDL_Texture * render_text(SDL_Renderer *renderer, const char* text, TTF_Font *font, SDL_Color color, SDL_Rect *rect)
{
SDL_Surface *surface;
SDL_Texture *texture;
surface = TTF_RenderText_Solid(font, text, color);
texture = SDL_CreateTextureFromSurface(renderer, surface);
rect->w = surface->w;
rect->h = surface->h;
SDL_FreeSurface(surface);
return texture;
}
int rand_range(int min, int max){
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
@ -56,7 +72,7 @@ int main(int argc, char** argv) {
int trail = 0;
int wait = 25;
SDL_Texture *switchlogo_tex = NULL, *sdllogo_tex = NULL;
SDL_Texture *switchlogo_tex = NULL, *sdllogo_tex = NULL, *helloworld_tex = NULL;
SDL_Rect pos = { 0, 0, 0, 0 }, sdl_pos = { 0, 0, 0, 0 };
Mix_Music *music = NULL;
Mix_Chunk *sound[4] = { NULL };
@ -81,9 +97,10 @@ int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER);
Mix_Init(MIX_INIT_OGG);
IMG_Init(IMG_INIT_PNG);
TTF_Init();
SDL_Window* window = SDL_CreateWindow("sdl2+mixer+image demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_W, SCREEN_H, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
SDL_Window* window = SDL_CreateWindow("sdl2+mixer+image+ttf demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_W, SCREEN_H, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
// load logos from file
SDL_Surface *sdllogo = IMG_Load("data/sdl.png");
@ -110,6 +127,16 @@ int main(int argc, char** argv) {
SDL_JoystickEventState(SDL_ENABLE);
SDL_JoystickOpen(0);
// load font from romfs
TTF_Font* font = TTF_OpenFont("data/LeroyLetteringLightBeta01.ttf", 36);
// render text as texture
SDL_Rect helloworld_rect = { 0, SCREEN_H - 36, 0, 0 };
helloworld_tex = render_text(renderer, "Hello, world!", font, colors[1], &helloworld_rect);
// no need to keep the font loaded
TTF_CloseFont(font);
SDL_InitSubSystem(SDL_INIT_AUDIO);
Mix_AllocateChannels(5);
Mix_OpenAudio(48000, AUDIO_S16, 2, 4096);
@ -132,7 +159,6 @@ int main(int argc, char** argv) {
// use joystick
if (event.type == SDL_JOYBUTTONDOWN) {
printf("%d\n",event.jbutton.button);
if (event.jbutton.button == JOY_UP)
if (wait > 0)
wait--;
@ -197,11 +223,25 @@ int main(int argc, char** argv) {
SDL_RenderCopy(renderer, switchlogo_tex, NULL, &pos);
}
// put text on screen
if (helloworld_tex)
SDL_RenderCopy(renderer, helloworld_tex, NULL, &helloworld_rect);
SDL_RenderPresent(renderer);
SDL_Delay(wait);
}
// clean up your textures when you are done with them
if (sdllogo_tex)
SDL_DestroyTexture(sdllogo_tex);
if (switchlogo_tex)
SDL_DestroyTexture(switchlogo_tex);
if (helloworld_tex)
SDL_DestroyTexture(helloworld_tex);
// stop sounds and free loaded data
Mix_HaltChannel(-1);
Mix_FreeMusic(music);
@ -211,6 +251,7 @@ int main(int argc, char** argv) {
IMG_Quit();
Mix_CloseAudio();
TTF_Quit();
Mix_Quit();
SDL_Quit();
romfsExit();

View File

@ -18,6 +18,8 @@
static u32 framebuf_width=0;
static PadState pad;
//Note that this doesn't handle any blending.
void draw_glyph(FT_Bitmap* bitmap, u32* framebuf, u32 x, u32 y)
{
@ -102,8 +104,8 @@ static int error_screen(const char* fmt, ...)
printf("Press PLUS to exit\n");
while (appletMainLoop())
{
hidScanInput();
if (hidKeysDown(CONTROLLER_P1_AUTO) & KEY_PLUS)
padUpdate(&pad);
if (padGetButtonsDown(&pad) & HidNpadButton_Plus)
break;
consoleUpdate(NULL);
}
@ -134,7 +136,7 @@ void userAppInit(void)
rc = plInitialize(PlServiceType_User);
if (R_FAILED(rc))
fatalThrow(rc);
diagAbortWithResult(rc);
LanguageCode = getSystemLanguage();
}
@ -149,6 +151,12 @@ int main(int argc, char **argv)
Result rc=0;
FT_Error ret=0;
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
padInitializeDefault(&pad);
//Use this when using multiple shared-fonts.
/*
PlFontData fonts[PlSharedFontType_Total];
@ -198,13 +206,13 @@ int main(int argc, char **argv)
while (appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
u32 stride;
u32* framebuf = (u32*)framebufferBegin(&fb, &stride);

View File

@ -33,21 +33,30 @@ int main(int argc, char* argv[])
#ifdef DISPLAY_IMAGE
u8* imageptr = (u8*)image_bin;
const u32 image_width = 1280;
const u32 image_height = 720;
#endif
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
u32 cnt = 0;
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Retrieve the framebuffer
@ -66,7 +75,9 @@ int main(int argc, char* argv[])
{
u32 pos = y * stride / sizeof(u32) + x;
#ifdef DISPLAY_IMAGE
framebuf[pos] = RGBA8_MAXALPHA(imageptr[pos*3+0]+(cnt*4), imageptr[pos*3+1], imageptr[pos*3+2]);
if (y >= image_height || x >= image_width) continue;
u32 imagepos = y * image_width + x;
framebuf[pos] = RGBA8_MAXALPHA(imageptr[imagepos*3+0]+(cnt*4), imageptr[imagepos*3+1], imageptr[imagepos*3+2]);
#else
framebuf[pos] = 0x01010101 * cnt * 4;//Set framebuf to different shades of grey.
#endif

View File

@ -104,19 +104,26 @@ int main(int argc, char* argv[])
u8* imageptr = (u8*)image_bin;
#endif
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
u32 cnt = 0;
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Retrieve the framebuffer.

View File

@ -19,23 +19,18 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: all players with standard controller styles
padConfigureInput(8, HidNpadStyleSet_NpadStandard);
// Initialize the gamepad for reading all controllers
PadState pad;
padInitializeAny(&pad);
Result rc=0;
bool initflag=0;
u32 i;
printf("abstracted-pad example\n");
hidScanInput();
// When hiddbgSetAutoPilotVirtualPadState runs a new controller may become available, depending on the specified npadInterfaceType field. If CONTROLLER_HANDHELD is being internally, CONTROLLER_P1_AUTO would use the new controller. Check which controller we're currently using and don't use CONTROLLER_P1_AUTO, so it doesn't switch to using the new controller later.
HidControllerID conID = hidGetHandheldMode() ? CONTROLLER_HANDHELD : CONTROLLER_PLAYER_1;
printf("Connected controllers: ");
for(i=0; i<10; i++) {
if (hidIsControllerConnected(i)) printf("%d ", i);
}
printf("\n");
rc = hiddbgInitialize();
if (R_FAILED(rc)) {
printf("hiddbgInitialize(): 0x%x\n", rc);
@ -44,7 +39,7 @@ int main(int argc, char* argv[])
initflag = 1;
}
u64 pads[8]={0};
HiddbgAbstractedPadHandle pads[8]={0};
HiddbgAbstractedPadState states[8]={0};
s32 tmpout=0;
@ -57,26 +52,24 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(conID);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (R_SUCCEEDED(rc) && (kDown & (KEY_A | KEY_X))) {
printf("Connected controllers:\n");
for(i=0; i<10; i++) {
if (hidIsControllerConnected(i)) {
JoystickPosition tmpjoy[2];
hidJoystickRead(&tmpjoy[0], i, JOYSTICK_LEFT);
hidJoystickRead(&tmpjoy[1], i, JOYSTICK_RIGHT);
printf("%d: type = 0x%x, devicetype = 0x%x, buttons = 0x%lx, stickL.dx = 0x%x, stickL.dy = 0x%x, stickR.dx = 0x%x, stickR.dy = 0x%x\n", i, hidGetControllerType(i), hidGetControllerDeviceType(i), hidKeysHeld(i), tmpjoy[0].dx, tmpjoy[0].dy, tmpjoy[1].dx, tmpjoy[1].dy);
}
}
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (R_SUCCEEDED(rc) && (kDown & (HidNpadButton_A | HidNpadButton_X))) {
printf("Controllers state:\n");
HidAnalogStickState analog_stick_l = padGetStickPos(&pad, 0);
HidAnalogStickState analog_stick_r = padGetStickPos(&pad, 1);
printf("buttons = 0x%lx, analog_stick_l.x = 0x%x, analog_stick_l.y = 0x%x, analog_stick_r.x = 0x%x, analog_stick_r.y = 0x%x\n", padGetButtons(&pad), analog_stick_l.x, analog_stick_l.y, analog_stick_r.x, analog_stick_r.y);
}
if (R_SUCCEEDED(rc) && (kDown & KEY_A)) {
if (R_SUCCEEDED(rc) && (kDown & HidNpadButton_A)) {
tmpout = 0;
rc = hiddbgGetAbstractedPadsState(pads, states, sizeof(pads)/sizeof(u64), &tmpout);
printf("hiddbgGetAbstractedPadsState(): 0x%x, 0x%x\n", rc, tmpout);
@ -86,7 +79,7 @@ int main(int argc, char* argv[])
if (R_SUCCEEDED(rc) && tmpout>=1) {
for (u32 i=0; i<tmpout; i++) {
printf("0x%x: \n", i);
printf("type = 0x%x, flags = 0x%x, colors = 0x%x 0x%x, npadInterfaceType = 0x%x, buttons = 0x%x, stickL.dx = 0x%x, stickL.dy = 0x%x, stickR.dx = 0x%x, stickR.dy = 0x%x\n", states[i].type, states[i].flags, states[i].singleColorBody, states[i].singleColorButtons, states[i].npadInterfaceType, states[i].state.buttons, states[i].state.joysticks[0].dx, states[i].state.joysticks[0].dy, states[i].state.joysticks[1].dx, states[i].state.joysticks[1].dy);
printf("type = 0x%x, flags = 0x%x, colors = 0x%x 0x%x, npadInterfaceType = 0x%x, buttons = 0x%x, analog_stick_l.x = 0x%x, analog_stick_l.y = 0x%x, analog_stick_r.x = 0x%x, analog_stick_r.y = 0x%x\n", states[i].type, states[i].flags, states[i].singleColorBody, states[i].singleColorButtons, states[i].npadInterfaceType, states[i].state.buttons, states[i].state.analog_stick_l.x, states[i].state.analog_stick_l.y, states[i].state.analog_stick_r.x, states[i].state.analog_stick_r.y);
}
}
@ -99,9 +92,9 @@ int main(int argc, char* argv[])
states[0].type = BIT(1);
// Use state-merge for the above controller, the state will be merged with an existing controller.
// For a plain virtual controller, use NpadInterfaceType_Bluetooth, and update the above type value.
states[0].npadInterfaceType = NpadInterfaceType_Rail;
states[0].npadInterfaceType = HidNpadInterfaceType_Rail;
states[0].state.buttons |= KEY_ZL;
states[0].state.buttons |= HidNpadButton_ZL;
rc = hiddbgSetAutoPilotVirtualPadState(AbstractedVirtualPadId, &states[0]);
printf("hiddbgSetAutoPilotVirtualPadState(): 0x%x\n", rc);
@ -110,9 +103,6 @@ int main(int argc, char* argv[])
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
if (kDown & KEY_PLUS)
break; // break in order to return to hbmenu
}
if (initflag) {

View File

@ -1,53 +1,64 @@
#include <string.h>
// Include the most common headers from the C standard library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
//See also libnx hid.h.
int main(int argc, char **argv)
// Main program entrypoint
int main(int argc, char* argv[])
{
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
// If on the other hand you want to write an OpenGL based application,
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc=0;
printf(CONSOLE_ESC(1;1H) "Press PLUS to exit.");
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
HidControllerColors colors;
HidNpadControllerColor colors={0};
hidGetControllerColors(CONTROLLER_P1_AUTO, &colors);
printf(CONSOLE_ESC(2;1H) "singleSet = %d, splitSet = %d.\n", colors.singleSet, colors.splitSet);
//Note that if a color field is zero that indicates that the color field isn't set, regardless of the *Set fields.
if (colors.singleSet) {
printf(CONSOLE_ESC(3;1H) "singleColorBody = 0x%08x, singleColorButtons = 0x%08x.\n", colors.singleColorBody, colors.singleColorButtons);
// Note that if a color field is zero that indicates that the color field isn't set.
// You might want to also use hidGetNpadControllerColorSplit.
rc = hidGetNpadControllerColorSingle(padIsHandheld(&pad) ? HidNpadIdType_Handheld : HidNpadIdType_No1, &colors);
if (R_SUCCEEDED(rc)) {
printf(CONSOLE_ESC(3;1H) "main = 0x%08x, sub = 0x%08x.\n", colors.main, colors.sub);
}
else {
printf(CONSOLE_ESC(3;1H) CONSOLE_ESC(2K));
}
if (colors.splitSet) {
printf(CONSOLE_ESC(4;1H) "leftColorBody = 0x%08x, leftColorButtons = 0x%08x.\n", colors.leftColorBody, colors.leftColorButtons);
printf(CONSOLE_ESC(5;1H) "rightColorBody = 0x%08x, rightColorButtons = 0x%08x.\n", colors.rightColorBody, colors.rightColorButtons);
}
else {
printf(CONSOLE_ESC(4;1H) CONSOLE_ESC(2K));
printf(CONSOLE_ESC(5;1H) CONSOLE_ESC(2K));
}
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
}
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);
return 0;
}

View File

@ -19,38 +19,38 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: all players with standard controller styles
padConfigureInput(8, HidNpadStyleSet_NpadStandard);
// Initialize the gamepad for reading all controllers
PadState pad;
padInitializeAny(&pad);
Result rc=0, rc2=0;
bool initflag=0;
u32 i;
u8 *workmem = NULL;
size_t workmem_size = 0x1000;
printf("hdls example\n");
hidScanInput();
// When hiddbgAttachHdlsVirtualDevice runs a new controller will become available. If CONTROLLER_HANDHELD is being internally, CONTROLLER_P1_AUTO would use the new virtual controller. Check which controller we're currently using and don't use CONTROLLER_P1_AUTO, so it doesn't switch to using the new controller later.
HidControllerID conID = hidGetHandheldMode() ? CONTROLLER_HANDHELD : CONTROLLER_PLAYER_1;
printf("Connected controllers: ");
for(i=0; i<10; i++) {
if (hidIsControllerConnected(i)) printf("%d ", i);
}
printf("\n");
rc = hiddbgInitialize();
if (R_FAILED(rc)) {
printf("hiddbgInitialize(): 0x%x\n", rc);
}
else {
initflag = 1;
workmem = aligned_alloc(0x1000, workmem_size);
if (workmem) initflag = 1;
else printf("workmem alloc failed\n");
}
u64 HdlsHandle=0;
HiddbgHdlsSessionId session_id={0};
HiddbgHdlsHandle HdlsHandle={0};
HiddbgHdlsDeviceInfo device = {0};
HiddbgHdlsState state={0};
// Set the controller type to Pro-Controller, and set the npadInterfaceType.
device.deviceType = HidDeviceType_FullKey3;
device.npadInterfaceType = NpadInterfaceType_Bluetooth;
device.npadInterfaceType = HidNpadInterfaceType_Bluetooth;
// Set the controller colors. The grip colors are for Pro-Controller on [9.0.0+].
device.singleColorBody = RGBA8_MAXALPHA(255,255,255);
device.singleColorButtons = RGBA8_MAXALPHA(0,0,0);
@ -58,14 +58,14 @@ int main(int argc, char* argv[])
device.colorRightGrip = RGBA8_MAXALPHA(0,40,20);
// Setup example controller state.
state.batteryCharge = 4; // Set battery charge to full.
state.joysticks[JOYSTICK_LEFT].dx = 0x1234;
state.joysticks[JOYSTICK_LEFT].dy = -0x1234;
state.joysticks[JOYSTICK_RIGHT].dx = 0x5678;
state.joysticks[JOYSTICK_RIGHT].dy = -0x5678;
state.battery_level = 4; // Set BatteryLevel to full.
state.analog_stick_l.x = 0x1234;
state.analog_stick_l.y = -0x1234;
state.analog_stick_r.x = 0x5678;
state.analog_stick_r.y = -0x5678;
if (initflag) {
rc = hiddbgAttachHdlsWorkBuffer();
rc = hiddbgAttachHdlsWorkBuffer(&session_id, workmem, workmem_size);
printf("hiddbgAttachHdlsWorkBuffer(): 0x%x\n", rc);
if (R_SUCCEEDED(rc)) {
@ -81,12 +81,15 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(conID);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Set state for the controller. You can also use hiddbgApplyHdlsStateList for this.
if (R_SUCCEEDED(rc)) {
@ -95,51 +98,31 @@ int main(int argc, char* argv[])
state.buttons = 0;
if (hidKeysHeld(conID) & KEY_R)
state.buttons |= KEY_HOME;
if (padGetButtons(&pad) & HidNpadButton_R)
state.buttons |= HiddbgNpadButton_Home;
if (hidKeysHeld(conID) & KEY_L)
state.buttons |= KEY_CAPTURE;
if (padGetButtons(&pad) & HidNpadButton_L)
state.buttons |= HiddbgNpadButton_Capture;
if (hidKeysHeld(conID) & KEY_DUP)
state.buttons |= KEY_ZR;
if (padGetButtons(&pad) & HidNpadButton_Up)
state.buttons |= HidNpadButton_ZR;
state.joysticks[JOYSTICK_LEFT].dx += 0x10;
if (state.joysticks[JOYSTICK_LEFT].dx > JOYSTICK_MAX) state.joysticks[JOYSTICK_LEFT].dx = JOYSTICK_MIN;
state.joysticks[JOYSTICK_RIGHT].dy -= 0x10;
if (state.joysticks[JOYSTICK_LEFT].dy < JOYSTICK_MIN) state.joysticks[JOYSTICK_LEFT].dy = JOYSTICK_MAX;
state.analog_stick_l.x += 0x10;
if (state.analog_stick_l.x > JOYSTICK_MAX) state.analog_stick_l.x = JOYSTICK_MIN;
state.analog_stick_r.y -= 0x10;
if (state.analog_stick_r.y < JOYSTICK_MIN) state.analog_stick_r.y = JOYSTICK_MAX;
}
if (R_SUCCEEDED(rc) && (kDown & (KEY_A | KEY_X))) {
printf("Connected controllers:\n");
for(i=0; i<10; i++) {
if (hidIsControllerConnected(i)) {
JoystickPosition tmpjoy[2];
hidJoystickRead(&tmpjoy[0], i, JOYSTICK_LEFT);
hidJoystickRead(&tmpjoy[1], i, JOYSTICK_RIGHT);
u8 interfacetype=0;
rc2 = hidGetNpadInterfaceType(i, &interfacetype);
if (R_FAILED(rc2)) printf("hidGetNpadInterfaceType(): 0x%x\n", rc2);
HidPowerInfo powerinfo[3]={0};
hidGetControllerPowerInfo(i, &powerinfo[0], 1);
hidGetControllerPowerInfo(i, &powerinfo[1], 2);
printf("%d: type = 0x%x, devicetype = 0x%x, buttons = 0x%lx, stickL.dx = 0x%x, stickL.dy = 0x%x, stickR.dx = 0x%x, stickR.dy = 0x%x, interface = %d\n", i, hidGetControllerType(i), hidGetControllerDeviceType(i), hidKeysHeld(i), tmpjoy[0].dx, tmpjoy[0].dy, tmpjoy[1].dx, tmpjoy[1].dy, interfacetype);
for (u32 poweri=0; poweri<3; poweri++)
printf("%d powerinfo[%d]: powerConnected = %d, isCharging = %d, batteryCharge = %d\n", i, poweri, powerinfo[poweri].powerConnected, powerinfo[poweri].isCharging, powerinfo[poweri].batteryCharge);
}
}
if (R_SUCCEEDED(rc) && (kDown & (HidNpadButton_A | HidNpadButton_X))) {
printf("Controllers state:\n");
HidAnalogStickState analog_stick_l = padGetStickPos(&pad, 0);
HidAnalogStickState analog_stick_r = padGetStickPos(&pad, 1);
printf("buttons = 0x%lx, analog_stick_l.x = 0x%x, analog_stick_l.y = 0x%x, analog_stick_r.x = 0x%x, analog_stick_r.y = 0x%x\n", padGetButtons(&pad), analog_stick_l.x, analog_stick_l.y, analog_stick_r.x, analog_stick_r.y);
printf("\n");
}
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
if (kDown & KEY_PLUS)
break; // break in order to return to hbmenu
}
if (initflag) {
@ -150,10 +133,11 @@ int main(int argc, char* argv[])
printf("hiddbgDetachHdlsVirtualDevice(): 0x%x\n", rc);
}
rc = hiddbgReleaseHdlsWorkBuffer();
rc = hiddbgReleaseHdlsWorkBuffer(session_id);
printf("hiddbgReleaseHdlsWorkBuffer(): 0x%x\n", rc);
hiddbgExit();
free(workmem);
}
// Deinitialize and clean up resources used by the console (important!)

View File

@ -1,8 +1,9 @@
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
// Joy-Con IR-sensor example, displays the image from the IR camera. See also libnx irs.h.
@ -17,7 +18,7 @@ void userAppInit(void)
rc = irsInitialize();
if (R_FAILED(rc))
fatalThrow(rc);
diagAbortWithResult(rc);
}
void userAppExit(void)
@ -25,8 +26,8 @@ void userAppExit(void)
irsExit();
}
__attribute__((format(printf, 1, 2)))
static int error_screen(const char* fmt, ...)
__attribute__((format(printf, 2, 3)))
static int error_screen(PadState *pad, const char* fmt, ...)
{
consoleInit(NULL);
va_list va;
@ -36,8 +37,8 @@ static int error_screen(const char* fmt, ...)
printf("Press PLUS to exit\n");
while (appletMainLoop())
{
hidScanInput();
if (hidKeysDown(CONTROLLER_P1_AUTO) & KEY_PLUS)
padUpdate(pad);
if (padGetButtonsDown(pad) & HidNpadButton_Plus)
break;
consoleUpdate(NULL);
}
@ -45,26 +46,34 @@ static int error_screen(const char* fmt, ...)
return EXIT_FAILURE;
}
int main(int argc, char **argv)
// Main program entrypoint
int main(int argc, char* argv[])
{
Result rc=0;
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
const size_t ir_buffer_size = 0x12c00; // Size for the max IrsImageTransferProcessorFormat.
u8 *ir_buffer = NULL;
ir_buffer = (u8*)malloc(ir_buffer_size);
if (!ir_buffer) {
rc = MAKERESULT(Module_Libnx, LibnxError_OutOfMemory);
return error_screen("Failed to allocate memory for ir_buffer.\n");
return error_screen(&pad, "Failed to allocate memory for ir_buffer.\n");
}
memset(ir_buffer, 0, ir_buffer_size);
// Get the handle for the specified controller.
padUpdate(&pad); // Only needed because this wasn't used yet, and we're using padIsHandheld.
IrsIrCameraHandle irhandle;
hidScanInput(); // Only needed because hidScanInput() was not used yet since this is before the main-loop, and we're using hidGetHandheldMode().
rc = irsGetIrCameraHandle(&irhandle, hidGetHandheldMode() ? CONTROLLER_HANDHELD : CONTROLLER_PLAYER_1);
rc = irsGetIrCameraHandle(&irhandle, padIsHandheld(&pad) ? HidNpadIdType_Handheld : HidNpadIdType_No1);
if (R_FAILED(rc))
return error_screen("irsGetIrCameraHandle() returned 0x%x\n", rc);
return error_screen(&pad, "irsGetIrCameraHandle() returned 0x%x\n", rc);
// If a controller update is needed, force an update.
bool updateflag=0;
@ -81,7 +90,7 @@ int main(int argc, char **argv)
irsGetDefaultImageTransferProcessorConfig(&config);
rc = irsRunImageTransferProcessor(irhandle, &config, 0x100000);
if (R_FAILED(rc))
return error_screen("irsRunImageTransferProcessor() returned 0x%x\n", rc);
return error_screen(&pad, "irsRunImageTransferProcessor() returned 0x%x\n", rc);
Framebuffer fb;
framebufferCreate(&fb, nwindowGetDefault(), FB_WIDTH, FB_HEIGHT, PIXEL_FORMAT_RGBA_8888, 2);
@ -91,13 +100,15 @@ int main(int argc, char **argv)
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// With the default config the image is updated every few seconds (see above). Likewise, it takes a few seconds for the initial image to become available.
// This will return an error when no image is available yet.

View File

@ -18,11 +18,17 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc=0;
bool initflag=0;
s32 i;
s32 total_entries;
u64 UniquePadIds[2];
HidsysUniquePadId unique_pad_ids[2]={0};
HidsysNotificationLedPattern pattern;
printf("notification-led example\n");
@ -33,7 +39,6 @@ int main(int argc, char* argv[])
printf("Init failed, press + to exit.\n");
}
else {
initflag = 1;
printf("Press A to set a Breathing effect notification-LED pattern.\n");
printf("Press B to set a Heartbeat effect notification-LED pattern.\n");
printf("Press + to disable notification-LED and exit.\n");
@ -42,18 +47,18 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) {
if (kDown & HidNpadButton_Plus) {
// Disable notification led. Only needed with hidsysSetNotificationLedPattern, with hidsysSetNotificationLedPatternWithTimeout the LED will be automatically disabled via the timeout.
memset(&pattern, 0, sizeof(pattern));
}
else if (kDown & KEY_A) {
else if (kDown & HidNpadButton_A) {
memset(&pattern, 0, sizeof(pattern));
// Setup Breathing effect pattern data.
@ -69,7 +74,7 @@ int main(int argc, char* argv[])
pattern.miniCycles[1].transitionSteps = 0xF; // 15 steps. Transition time 1.5s.
pattern.miniCycles[1].finalStepDuration = 0x0; // Forced 12.5ms.
}
else if (kDown & KEY_B) {
else if (kDown & HidNpadButton_B) {
memset(&pattern, 0, sizeof(pattern));
// Setup Heartbeat effect pattern data.
@ -102,40 +107,40 @@ int main(int argc, char* argv[])
}
}
if (kDown & (KEY_A | KEY_B | KEY_PLUS)) {
if (kDown & (HidNpadButton_A | HidNpadButton_B | HidNpadButton_Plus)) {
total_entries = 0;
memset(UniquePadIds, 0, sizeof(UniquePadIds));
memset(unique_pad_ids, 0, sizeof(unique_pad_ids));
// Get the UniquePadIds for the specified controller, which will then be used with hidsysSetNotificationLedPattern*.
// If you want to get the UniquePadIds for all controllers, you can use hidsysGetUniquePadIds instead.
rc = hidsysGetUniquePadsFromNpad(hidGetHandheldMode() ? CONTROLLER_HANDHELD : CONTROLLER_PLAYER_1, UniquePadIds, 2, &total_entries);
rc = hidsysGetUniquePadsFromNpad(padIsHandheld(&pad) ? HidNpadIdType_Handheld : HidNpadIdType_No1, unique_pad_ids, 2, &total_entries);
printf("hidsysGetUniquePadsFromNpad(): 0x%x", rc);
if (R_SUCCEEDED(rc)) printf(", %d", total_entries);
printf("\n");
if (R_SUCCEEDED(rc)) {
for(i=0; i<total_entries; i++) { // System will skip sending the subcommand to controllers where this isn't available.
printf("[%d] = 0x%lx ", i, UniquePadIds[i]);
printf("[%d] = 0x%lx ", i, unique_pad_ids[i].id);
// Attempt to use hidsysSetNotificationLedPatternWithTimeout first with a 2 second timeout, then fallback to hidsysSetNotificationLedPattern on failure. See hidsys.h for the requirements for using these.
rc = hidsysSetNotificationLedPatternWithTimeout(&pattern, UniquePadIds[i], 2000000000ULL);
rc = hidsysSetNotificationLedPatternWithTimeout(&pattern, unique_pad_ids[i], 2000000000ULL);
printf("hidsysSetNotificationLedPatternWithTimeout(): 0x%x\n", rc);
if (R_FAILED(rc)) {
rc = hidsysSetNotificationLedPattern(&pattern, UniquePadIds[i]);
rc = hidsysSetNotificationLedPattern(&pattern, unique_pad_ids[i]);
printf("hidsysSetNotificationLedPattern(): 0x%x\n", rc);
}
}
}
}
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
if (kDown & KEY_PLUS)
break; // break in order to return to hbmenu
}
if (initflag) hidsysExit();
hidsysExit();
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);

View File

@ -1,26 +1,41 @@
#include <string.h>
// Include the most common headers from the C standard library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
//See also libnx hid.h.
// See also libnx pad.h / hid.h.
int main(int argc, char **argv)
// Main program entrypoint
int main(int argc, char* argv[])
{
//Matrix containing the name of each key. Useful for printing when a key is pressed
char keysNames[32][32] = {
"KEY_A", "KEY_B", "KEY_X", "KEY_Y",
"KEY_LSTICK", "KEY_RSTICK", "KEY_L", "KEY_R",
"KEY_ZL", "KEY_ZR", "KEY_PLUS", "KEY_MINUS",
"KEY_DLEFT", "KEY_DUP", "KEY_DRIGHT", "KEY_DDOWN",
"KEY_LSTICK_LEFT", "KEY_LSTICK_UP", "KEY_LSTICK_RIGHT", "KEY_LSTICK_DOWN",
"KEY_RSTICK_LEFT", "KEY_RSTICK_UP", "KEY_RSTICK_RIGHT", "KEY_RSTICK_DOWN",
"KEY_SL_LEFT", "KEY_SR_LEFT", "KEY_SL_RIGHT", "KEY_SR_RIGHT",
"KEY_TOUCH", "", "", ""
};
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
// If on the other hand you want to write an OpenGL based application,
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
//Matrix containing the name of each key. Useful for printing when a key is pressed
char keysNames[28][32] = {
"A", "B", "X", "Y",
"StickL", "StickR", "L", "R",
"ZL", "ZR", "Plus", "Minus",
"Left", "Up", "Right", "Down",
"StickLLeft", "StickLUp", "StickLRight", "StickLDown",
"StickRLeft", "StickRUp", "StickRRight", "StickRDown",
"LeftSL", "LeftSR", "RightSL", "RightSR",
};
u32 kDownOld = 0, kHeldOld = 0, kUpOld = 0; //In these variables there will be information about keys detected in the previous frame
printf("\x1b[1;1HPress PLUS to exit.");
@ -30,34 +45,39 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
//hidKeysHeld returns information about which buttons have are held down in this frame
u64 kHeld = hidKeysHeld(CONTROLLER_P1_AUTO);
//hidKeysUp returns information about which buttons have been just released
u64 kUp = hidKeysUp(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
// padGetButtons returns the set of buttons that are currently pressed
u64 kHeld = padGetButtons(&pad);
//Do the keys printing only if keys have changed
// padGetButtonsUp returns the set of buttons that have been
// newly released in this frame compared to the previous one
u64 kUp = padGetButtonsUp(&pad);
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Do the keys printing only if keys have changed
if (kDown != kDownOld || kHeld != kHeldOld || kUp != kUpOld)
{
//Clear console
// Clear console
consoleClear();
//These two lines must be rewritten because we cleared the whole console
// These two lines must be rewritten because we cleared the whole console
printf("\x1b[1;1HPress PLUS to exit.");
printf("\x1b[2;1HLeft joystick position:");
printf("\x1b[4;1HRight joystick position:");
printf("\x1b[2;1HLeft stick position:");
printf("\x1b[4;1HRight stick position:");
printf("\x1b[6;1H"); //Move the cursor to the sixth row because on the previous ones we'll write the joysticks' position
//Check if some of the keys are down, held or up
// Check if some of the keys are down, held or up
int i;
for (i = 0; i < 32; i++)
for (i = 0; i < 28; i++)
{
if (kDown & BIT(i)) printf("%s down\n", keysNames[i]);
if (kHeld & BIT(i)) printf("%s held\n", keysNames[i]);
@ -65,24 +85,24 @@ int main(int argc, char **argv)
}
}
//Set keys old values for the next frame
// Set keys old values for the next frame
kDownOld = kDown;
kHeldOld = kHeld;
kUpOld = kUp;
JoystickPosition pos_left, pos_right;
// Read the sticks' position
HidAnalogStickState analog_stick_l = padGetStickPos(&pad, 0);
HidAnalogStickState analog_stick_r = padGetStickPos(&pad, 1);
//Read the joysticks' position
hidJoystickRead(&pos_left, CONTROLLER_P1_AUTO, JOYSTICK_LEFT);
hidJoystickRead(&pos_right, CONTROLLER_P1_AUTO, JOYSTICK_RIGHT);
//Print the joysticks' position
printf("\x1b[3;1H%04d; %04d", pos_left.dx, pos_left.dy);
printf("\x1b[5;1H%04d; %04d", pos_right.dx, pos_right.dy);
// Print the sticks' position
printf("\x1b[3;1H%04d; %04d", analog_stick_l.x, analog_stick_l.y);
printf("\x1b[5;1H%04d; %04d", analog_stick_r.x, analog_stick_r.y);
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
}
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);
return 0;
}

View File

@ -19,14 +19,19 @@ int main(int argc, char **argv)
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
printf(CONSOLE_ESC(1;1H)"Press PLUS to exit.");
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
hidScanInput(); // This needs to be used at least once before ringconCreate() since it uses hidGetControllerType() internally. This is only called here since ringconCreate() is called before the main-loop in this example.
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf(CONSOLE_ESC(1;1H)"Press PLUS to exit.");
Result rc=0;
RingCon ring={0};
bool ready=0;
rc = ringconCreate(&ring, CONTROLLER_PLAYER_1); // Setup Ring-Con usage for the specified controller, if you want to use multiple controllers you can do so by calling this multiple times with multiple RingCon objects/controllers. The Ring-Con must be connected to the specified controller.
rc = ringconCreate(&ring, HidNpadIdType_No1); // Setup Ring-Con usage for the specified controller, if you want to use multiple controllers you can do so by calling this multiple times with multiple RingCon objects/controllers. The Ring-Con must be connected to the specified controller.
printf(CONSOLE_ESC(2;1H)"ringconCreate(): 0x%x, 0x%x", rc, ringconGetErrorFlags(&ring)); // You can also use ringconGetErrorFlag().
ready = R_SUCCEEDED(rc);
@ -35,14 +40,14 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Get the sensor state data.

222
hid/sevensixaxis/Makefile Normal file
View File

@ -0,0 +1,222 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional)
#
# NO_ICON: if set to anything, do not use icon.
# NO_NACP: if set to anything, no .nacp file is generated.
# APP_TITLE is the name of the app stored in the .nacp file (Optional)
# APP_AUTHOR is the author of the app stored in the .nacp file (Optional)
# APP_VERSION is the version of the app stored in the .nacp file (Optional)
# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional)
# ICON is the filename of the icon (.jpg), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.jpg
# - icon.jpg
# - <libnx folder>/default_icon.jpg
#
# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.json
# - config.json
# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead
# of a homebrew executable (.nro). This is intended to be used for sysmodules.
# NACP building is skipped as well.
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA := data
INCLUDES := include
#ROMFS := romfs
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
ifeq ($(strip $(CONFIG_JSON)),)
jsons := $(wildcard *.json)
ifneq (,$(findstring $(TARGET).json,$(jsons)))
export APP_JSON := $(TOPDIR)/$(TARGET).json
else
ifneq (,$(findstring config.json,$(jsons)))
export APP_JSON := $(TOPDIR)/config.json
endif
endif
else
export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
endif
ifeq ($(strip $(ICON)),)
icons := $(wildcard *.jpg)
ifneq (,$(findstring $(TARGET).jpg,$(icons)))
export APP_ICON := $(TOPDIR)/$(TARGET).jpg
else
ifneq (,$(findstring icon.jpg,$(icons)))
export APP_ICON := $(TOPDIR)/icon.jpg
endif
endif
else
export APP_ICON := $(TOPDIR)/$(ICON)
endif
ifeq ($(strip $(NO_ICON)),)
export NROFLAGS += --icon=$(APP_ICON)
endif
ifeq ($(strip $(NO_NACP)),)
export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp
endif
ifneq ($(APP_TITLEID),)
export NACPFLAGS += --titleid=$(APP_TITLEID)
endif
ifneq ($(ROMFS),)
export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS)
endif
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
ifeq ($(strip $(APP_JSON)),)
@rm -fr $(BUILD) $(TARGET).nro $(TARGET).nacp $(TARGET).elf
else
@rm -fr $(BUILD) $(TARGET).nsp $(TARGET).nso $(TARGET).npdm $(TARGET).elf
endif
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
ifeq ($(strip $(APP_JSON)),)
all : $(OUTPUT).nro
ifeq ($(strip $(NO_NACP)),)
$(OUTPUT).nro : $(OUTPUT).elf $(OUTPUT).nacp
else
$(OUTPUT).nro : $(OUTPUT).elf
endif
else
all : $(OUTPUT).nsp
$(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm
$(OUTPUT).nso : $(OUTPUT).elf
endif
$(OUTPUT).elf : $(OFILES)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@ -0,0 +1,90 @@
// Include the most common headers from the C standard library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
// This example shows how to use the SevenSixAxisSensor. Official sw usually only uses this while VrMode is active. See also the vrmode example.
// See also libnx hid.h.
// SevenSixAxisSensor combines the SixAxisSensor for the Console and Joy-Cons together.
// Main program entrypoint
int main(int argc, char* argv[])
{
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
// If on the other hand you want to write an OpenGL based application,
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc=0;
printf("Press A to get state.\n");
printf("Press + to exit.\n");
rc = hidInitializeSevenSixAxisSensor();
printf("hidInitializeSevenSixAxisSensor(): 0x%x\n", rc);
rc = appletSetVrModeEnabled(true);
printf("appletSetVrModeEnabled(true): 0x%x\n", rc);
rc = hidResetSevenSixAxisSensorTimestamp(); // Official sw uses this right before hidStartSevenSixAxisSensor, each time.
printf("hidResetSevenSixAxisSensorTimestamp(): 0x%x\n", rc);
rc = hidStartSevenSixAxisSensor();
printf("hidStartSevenSixAxisSensor(): 0x%x\n", rc);
// Main loop
while(appletMainLoop())
{
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (kDown & HidNpadButton_A) {
HidSevenSixAxisSensorState states[1]={0};
size_t total_out=0;
rc = hidGetSevenSixAxisSensorStates(states, 1, &total_out);
printf("hidGetSevenSixAxisSensorStates(): 0x%x, %lx\n", rc, total_out);
if (R_SUCCEEDED(rc) && total_out) {
printf("unk_x18: ");
for (u32 i=0; i<sizeof(states[0].unk_x18)/sizeof(float); i++) printf("%f ", states[0].unk_x18[i]);
printf("\n");
}
}
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
}
rc = appletSetVrModeEnabled(false);
printf("appletSetVrModeEnabled(false): 0x%x\n", rc);
rc = hidStopSevenSixAxisSensor();
printf("hidStopSevenSixAxisSensor(): 0x%x\n", rc);
rc = hidFinalizeSevenSixAxisSensor();
printf("hidFinalizeSevenSixAxisSensor(): 0x%x\n", rc);
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);
return 0;
}

View File

@ -9,11 +9,18 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// It's necessary to initialize these separately as they all have different handle values
u32 handles[4];
hidGetSixAxisSensorHandles(&handles[0], 2, CONTROLLER_PLAYER_1, TYPE_JOYCON_PAIR);
hidGetSixAxisSensorHandles(&handles[2], 1, CONTROLLER_PLAYER_1, TYPE_PROCONTROLLER);
hidGetSixAxisSensorHandles(&handles[3], 1, CONTROLLER_HANDHELD, TYPE_HANDHELD);
HidSixAxisSensorHandle handles[4];
hidGetSixAxisSensorHandles(&handles[0], 1, HidNpadIdType_Handheld, HidNpadStyleTag_NpadHandheld);
hidGetSixAxisSensorHandles(&handles[1], 1, HidNpadIdType_No1, HidNpadStyleTag_NpadFullKey);
hidGetSixAxisSensorHandles(&handles[2], 2, HidNpadIdType_No1, HidNpadStyleTag_NpadJoyDual);
hidStartSixAxisSensor(handles[0]);
hidStartSixAxisSensor(handles[1]);
hidStartSixAxisSensor(handles[2]);
@ -25,31 +32,43 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
SixAxisSensorValues sixaxis;
// You can read back up to 17 successive values at once
hidSixAxisSensorValuesRead(&sixaxis, CONTROLLER_P1_AUTO, 1);
// Read from the correct sixaxis handle depending on the current input style
HidSixAxisSensorState sixaxis = {0};
u64 style_set = padGetStyleSet(&pad);
if (style_set & HidNpadStyleTag_NpadHandheld)
hidGetSixAxisSensorStates(handles[0], &sixaxis, 1);
else if (style_set & HidNpadStyleTag_NpadFullKey)
hidGetSixAxisSensorStates(handles[1], &sixaxis, 1);
else if (style_set & HidNpadStyleTag_NpadJoyDual) {
// For JoyDual, read from either the Left or Right Joy-Con depending on which is/are connected
u64 attrib = padGetAttributes(&pad);
if (attrib & HidNpadAttribute_IsLeftConnected)
hidGetSixAxisSensorStates(handles[2], &sixaxis, 1);
else if (attrib & HidNpadAttribute_IsRightConnected)
hidGetSixAxisSensorStates(handles[3], &sixaxis, 1);
}
printf("\x1b[3;1H");
printf("Accelerometer: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.accelerometer.x, sixaxis.accelerometer.y, sixaxis.accelerometer.z);
printf("Gyroscope: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.gyroscope.x, sixaxis.gyroscope.y, sixaxis.gyroscope.z);
// It's currently unknown what this corresponds to other than some rotational value
printf("Unknown rotation: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.unk.x, sixaxis.unk.y, sixaxis.unk.z);
printf("Orientation matrix:\n"
printf("Acceleration: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.acceleration.x, sixaxis.acceleration.y, sixaxis.acceleration.z);
printf("Angular velocity: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.angular_velocity.x, sixaxis.angular_velocity.y, sixaxis.angular_velocity.z);
printf("Angle: x=% .4f, y=% .4f, z=% .4f\n", sixaxis.angle.x, sixaxis.angle.y, sixaxis.angle.z);
printf("Direction matrix:\n"
" [ % .4f, % .4f, % .4f ]\n"
" [ % .4f, % .4f, % .4f ]\n"
" [ % .4f, % .4f, % .4f ]\n",
sixaxis.orientation[0].x, sixaxis.orientation[0].y, sixaxis.orientation[0].z,
sixaxis.orientation[1].x, sixaxis.orientation[1].y, sixaxis.orientation[1].z,
sixaxis.orientation[2].x, sixaxis.orientation[2].y, sixaxis.orientation[2].z);
sixaxis.direction.direction[0][0], sixaxis.direction.direction[1][0], sixaxis.direction.direction[2][0],
sixaxis.direction.direction[0][1], sixaxis.direction.direction[1][1], sixaxis.direction.direction[2][1],
sixaxis.direction.direction[0][2], sixaxis.direction.direction[1][2], sixaxis.direction.direction[2][2]);
consoleUpdate(NULL);
}
@ -62,4 +81,3 @@ int main(int argc, char **argv)
consoleExit(NULL);
return 0;
}

View File

@ -1,38 +1,55 @@
#include <string.h>
// Include the most common headers from the C standard library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
//See also libnx hid.h.
// This example shows how to use the touch-screen. See also libnx hid.h.
int main(int argc, char **argv)
// Main program entrypoint
int main(int argc, char* argv[])
{
u32 prev_touchcount=0;
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
// If on the other hand you want to write an OpenGL based application,
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
hidInitializeTouchScreen();
s32 prev_touchcount=0;
printf("\x1b[1;1HPress PLUS to exit.");
printf("\x1b[2;1HTouch Screen position:");
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
touchPosition touch;
u32 i;
u32 touch_count = hidTouchCount();
if (touch_count != prev_touchcount)
HidTouchScreenState state={0};
if (hidGetTouchScreenStates(&state, 1)) {
if (state.count != prev_touchcount)
{
prev_touchcount = touch_count;
prev_touchcount = state.count;
consoleClear();
@ -42,18 +59,18 @@ int main(int argc, char **argv)
printf("\x1b[3;1H");
for(i=0; i<touch_count; i++)
for(s32 i=0; i<state.count; i++)
{
//Read the touch screen coordinates
hidTouchRead(&touch, i);
//Print the touch screen coordinates
printf("[point_id=%d] px=%03d, py=%03d, dx=%03d, dy=%03d, angle=%03d\n", i, touch.px, touch.py, touch.dx, touch.dy, touch.angle);
// Print the touch screen coordinates
printf("[%d] x=%03d, y=%03d, diameter_x=%03d, diameter_y=%03d, rotation_angle=%03d\n", i, state.touches[i].x, state.touches[i].y, state.touches[i].diameter_x, state.touches[i].diameter_y, state.touches[i].rotation_angle);
}
}
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
}
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);
return 0;
}

View File

@ -1,13 +1,17 @@
#include <string.h>
// Include the most common headers from the C standard library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
//Example for HID vibration/rumble.
// Example for HID vibration/rumble.
int main(int argc, char **argv)
// Main program entrypoint
int main(int argc, char* argv[])
{
u32 VibrationDeviceHandles[2][2];
HidVibrationDeviceHandle VibrationDeviceHandles[2][2];
Result rc = 0, rc2 = 0;
u32 target_device=0;
@ -17,17 +21,19 @@ int main(int argc, char **argv)
consoleInit(NULL);
printf("Press PLUS to exit.\n");
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
//Two VibrationDeviceHandles are returned: first one for left-joycon, second one for right-joycon.
//Change the total_handles param to 1, and update the hidSendVibrationValues calls, if you only want 1 VibrationDeviceHandle.
rc = hidInitializeVibrationDevices(VibrationDeviceHandles[0], 2, CONTROLLER_HANDHELD, TYPE_HANDHELD);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
//Setup VibrationDeviceHandles for CONTROLLER_PLAYER_1 too, since we want to support both CONTROLLER_HANDHELD and CONTROLLER_PLAYER_1.
if (R_SUCCEEDED(rc)) rc = hidInitializeVibrationDevices(VibrationDeviceHandles[1], 2, CONTROLLER_PLAYER_1, TYPE_JOYCON_PAIR);
printf("hidInitializeVibrationDevices() returned: 0x%x\n", rc);
// Two VibrationDeviceHandles are returned: first one for left-joycon, second one for right-joycon.
// Change the total_handles param to 1, and update the hidSendVibrationValues calls, if you only want 1 VibrationDeviceHandle.
rc = hidInitializeVibrationDevices(VibrationDeviceHandles[0], 2, HidNpadIdType_Handheld, HidNpadStyleTag_NpadHandheld);
if (R_SUCCEEDED(rc)) printf("Hold R to vibrate, and press A/B/X/Y while holding R to adjust values.\n");
// Setup VibrationDeviceHandles for HidNpadIdType_No1 too, since we want to support both HidNpadIdType_Handheld and HidNpadIdType_No1.
if (R_SUCCEEDED(rc)) rc = hidInitializeVibrationDevices(VibrationDeviceHandles[1], 2, HidNpadIdType_No1, HidNpadStyleTag_NpadJoyDual);
VibrationValue.amp_low = 0.2f;
VibrationValue.freq_low = 10.0f;
@ -44,22 +50,39 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
consoleClear();
printf("Press PLUS to exit.\n");
printf("Hold R to vibrate.\n");
printf("Press D-Pad (frequency) and face buttons (amplitude) to adjust values.\n");
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u64 kHeld = hidKeysHeld(CONTROLLER_P1_AUTO);
u64 kUp = hidKeysUp(CONTROLLER_P1_AUTO);
printf("High frequency %.0f, amplitude %.1f\n", VibrationValue.freq_high, VibrationValue.amp_high);
printf("Low frequency %.0f, amplitude %.1f\n", VibrationValue.freq_low, VibrationValue.amp_low);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
u64 kDown = padGetButtonsDown(&pad);
u64 kHeld = padGetButtons(&pad);
u64 kUp = padGetButtonsUp(&pad);
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
//Select which devices to vibrate.
target_device = 0;
if (!hidGetHandheldMode())
target_device = 1;
target_device = padIsHandheld(&pad) ? 0 : 1;
if (R_SUCCEEDED(rc) && (kHeld & KEY_R))
if (kDown & HidNpadButton_A) VibrationValue.amp_low += 0.1f;
if (kDown & HidNpadButton_Y) VibrationValue.amp_low -= 0.1f;
if (kDown & HidNpadButton_X) VibrationValue.amp_high += 0.1f;
if (kDown & HidNpadButton_B) VibrationValue.amp_high -= 0.1f;
if (kDown & HidNpadButton_Right) VibrationValue.freq_low += 5.0f;
if (kDown & HidNpadButton_Left) VibrationValue.freq_low -= 5.0f;
if (kDown & HidNpadButton_Up) VibrationValue.freq_high += 12.0f;
if (kDown & HidNpadButton_Down) VibrationValue.freq_high -= 12.0f;
if (R_SUCCEEDED(rc) && (kHeld & HidNpadButton_R))
{
//Calling hidSendVibrationValue/hidSendVibrationValues is really only needed when sending new VibrationValue(s).
//If you just want to vibrate 1 device, you can also use hidSendVibrationValue.
@ -69,13 +92,8 @@ int main(int argc, char **argv)
rc2 = hidSendVibrationValues(VibrationDeviceHandles[target_device], VibrationValues, 2);
if (R_FAILED(rc2)) printf("hidSendVibrationValues() returned: 0x%x\n", rc2);
if (kDown & KEY_A) VibrationValue.amp_low += 0.1f;
if (kDown & KEY_B) VibrationValue.freq_low += 5.0f;
if (kDown & KEY_X) VibrationValue.amp_high += 0.1f;
if (kDown & KEY_Y) VibrationValue.freq_high += 12.0f;
}
else if(kUp & KEY_R)//Stop vibration for all devices.
else if(kUp & HidNpadButton_R)//Stop vibration for all devices.
{
memcpy(&VibrationValues[0], &VibrationValue_stop, sizeof(HidVibrationValue));
memcpy(&VibrationValues[1], &VibrationValue_stop, sizeof(HidVibrationValue));
@ -88,9 +106,11 @@ int main(int argc, char **argv)
if (R_FAILED(rc2)) printf("hidSendVibrationValues() for stop other device returned: 0x%x\n", rc2);
}
// Update the console, sending a new frame to the display
consoleUpdate(NULL);
}
// Deinitialize and clean up resources used by the console (important!)
consoleExit(NULL);
return 0;
}

View File

@ -15,13 +15,23 @@ int main(int argc, char **argv)
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
rc = jitCreate(&j, 0x100000);//Adjust size as needed.
printf("jitCreate() returned: 0x%x\n", rc);
printf("jit type: %d\n", j.type);
if (R_SUCCEEDED(rc))
{
jit_rwaddr = jitGetRwAddr(&j);
jit_rxaddr = jitGetRxAddr(&j);
printf("jitGetRwAddr(): %p\n", jit_rwaddr);
printf("jitGetRxAddr(): %p\n", jit_rxaddr);
rc = jitTransitionToWritable(&j);
printf("jitTransitionToWritable() returned: 0x%x\n", rc);
@ -47,15 +57,15 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -35,6 +35,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
mutexInit(&g_PrintMutex);
barrierInit(&g_Barrier, 4);
@ -61,11 +68,11 @@ int main(int argc, char **argv)
while(appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break;
mutexLock(&g_PrintMutex);

View File

@ -54,6 +54,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
mutexInit(&g_PrintMutex);
ueventCreate(&g_Event, false);
ueventCreate(&g_ExitEvent, false);
@ -88,11 +95,11 @@ int main(int argc, char **argv)
while (appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break;
consoleUpdate(NULL);

View File

@ -50,6 +50,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
mutexInit(&g_PrintMutex);
utimerCreate(&g_Timer, 2000000000, TimerType_Repeating); // 2s
utimerCreate(&g_FastTimer, 1000000000, TimerType_Repeating); // 1s
@ -93,11 +100,11 @@ int main(int argc, char **argv)
while(appletMainLoop())
{
hidScanInput();
padUpdate(&pad);
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break;
consoleUpdate(NULL);

View File

@ -48,6 +48,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
socketInitializeDefault();
printf("curl example\n");
@ -57,14 +64,14 @@ int main(int argc, char* argv[])
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Your code goes here

View File

@ -112,6 +112,13 @@ int main(int argc, char **argv)
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Initialise sockets
socketInitializeDefault();
@ -208,23 +215,23 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
if (R_SUCCEEDED(rc) && (kDown & (KEY_A|KEY_B))) {
if (R_SUCCEEDED(rc) && (kDown & (HidNpadButton_A|HidNpadButton_B))) {
Result rc2 = ldnGetState(&state);
printf("ldnGetState(): 0x%x, %d\n", rc, state);
if (R_SUCCEEDED(rc2) && state==LdnState_Initialized) {
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
rc2 = create_network(&sec_config, &user_config, &netconfig, advert, sizeof(advert));
printf("create_network(): 0x%x\n", rc2);
}
if (kDown & KEY_B) {
if (kDown & HidNpadButton_B) {
rc2 = connect_network(&filter, &sec_config, &user_config, advert, sizeof(advert));
printf("connect_network(): 0x%x\n", rc2);
}
@ -274,7 +281,7 @@ int main(int argc, char **argv)
}
}
if (R_SUCCEEDED(rc) && (kDown & KEY_X)) {
if (R_SUCCEEDED(rc) && (kDown & HidNpadButton_X)) {
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
@ -282,14 +289,14 @@ int main(int argc, char **argv)
leave_network();
}
if (R_SUCCEEDED(rc) && sockfd>=0 && (kDown & (KEY_DLEFT|KEY_DRIGHT|KEY_DUP|KEY_DDOWN))) {
if (R_SUCCEEDED(rc) && sockfd>=0 && (kDown & (HidNpadButton_Left|HidNpadButton_Right|HidNpadButton_Up|HidNpadButton_Down))) {
char tmpstr[32];
memset(tmpstr, 0, sizeof(tmpstr));
if (kDown & KEY_DLEFT) strncpy(tmpstr, "Button DLEFT pressed.", sizeof(tmpstr)-1);
else if (kDown & KEY_DRIGHT) strncpy(tmpstr, "Button DRIGHT pressed.", sizeof(tmpstr)-1);
else if (kDown & KEY_DUP) strncpy(tmpstr, "Button DUP pressed.", sizeof(tmpstr)-1);
else if (kDown & KEY_DDOWN) strncpy(tmpstr, "Button DDOWN pressed.", sizeof(tmpstr)-1);
if (kDown & HidNpadButton_Left) strncpy(tmpstr, "Button Left pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Right) strncpy(tmpstr, "Button Right pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Up) strncpy(tmpstr, "Button Up pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Down) strncpy(tmpstr, "Button Down pressed.", sizeof(tmpstr)-1);
ssize_t ret = sendto(sockfd, tmpstr, sizeof(tmpstr), 0, (struct sockaddr*) &serv_addr, sizeof(struct sockaddr_in));
int tmp = errno;

222
network/lp2p/Makefile Normal file
View File

@ -0,0 +1,222 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional)
#
# NO_ICON: if set to anything, do not use icon.
# NO_NACP: if set to anything, no .nacp file is generated.
# APP_TITLE is the name of the app stored in the .nacp file (Optional)
# APP_AUTHOR is the author of the app stored in the .nacp file (Optional)
# APP_VERSION is the version of the app stored in the .nacp file (Optional)
# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional)
# ICON is the filename of the icon (.jpg), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.jpg
# - icon.jpg
# - <libnx folder>/default_icon.jpg
#
# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.json
# - config.json
# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead
# of a homebrew executable (.nro). This is intended to be used for sysmodules.
# NACP building is skipped as well.
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA := data
INCLUDES := include
#ROMFS := romfs
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
ifeq ($(strip $(CONFIG_JSON)),)
jsons := $(wildcard *.json)
ifneq (,$(findstring $(TARGET).json,$(jsons)))
export APP_JSON := $(TOPDIR)/$(TARGET).json
else
ifneq (,$(findstring config.json,$(jsons)))
export APP_JSON := $(TOPDIR)/config.json
endif
endif
else
export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
endif
ifeq ($(strip $(ICON)),)
icons := $(wildcard *.jpg)
ifneq (,$(findstring $(TARGET).jpg,$(icons)))
export APP_ICON := $(TOPDIR)/$(TARGET).jpg
else
ifneq (,$(findstring icon.jpg,$(icons)))
export APP_ICON := $(TOPDIR)/icon.jpg
endif
endif
else
export APP_ICON := $(TOPDIR)/$(ICON)
endif
ifeq ($(strip $(NO_ICON)),)
export NROFLAGS += --icon=$(APP_ICON)
endif
ifeq ($(strip $(NO_NACP)),)
export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp
endif
ifneq ($(APP_TITLEID),)
export NACPFLAGS += --titleid=$(APP_TITLEID)
endif
ifneq ($(ROMFS),)
export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS)
endif
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
ifeq ($(strip $(APP_JSON)),)
@rm -fr $(BUILD) $(TARGET).nro $(TARGET).nacp $(TARGET).elf
else
@rm -fr $(BUILD) $(TARGET).nsp $(TARGET).nso $(TARGET).npdm $(TARGET).elf
endif
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
ifeq ($(strip $(APP_JSON)),)
all : $(OUTPUT).nro
ifeq ($(strip $(NO_NACP)),)
$(OUTPUT).nro : $(OUTPUT).elf $(OUTPUT).nacp
else
$(OUTPUT).nro : $(OUTPUT).elf
endif
else
all : $(OUTPUT).nsp
$(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm
$(OUTPUT).nso : $(OUTPUT).elf
endif
$(OUTPUT).elf : $(OFILES)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

216
network/lp2p/source/main.c Normal file
View File

@ -0,0 +1,216 @@
// Include the most common headers from the C standard library
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/errno.h>
#include <unistd.h>
// Include the main libnx system header, for Switch development
#include <switch.h>
// This example shows how to use lp2p, for Switch-hosted local-network communications with mainly non-Switch devices. See also libnx lp2p.h.
// Note that in an actual app you may want to use lp2p/sockets from another thread.
Result create_network(const Lp2pGroupInfo *in_group_info) {
Result rc=0;
rc = lp2pCreateGroup(in_group_info);
printf("lp2pCreateGroup(): 0x%x\n", rc);
return rc;
}
void leave_network(void) {
Result rc=0;
u32 tmp32=0;
rc = lp2pLeave(&tmp32);
printf("lp2pLeave(): 0x%x, 0x%x\n", rc, tmp32);
rc = lp2pDestroyGroup();
printf("lp2pDestroyGroup(): 0x%x\n", rc);
}
void generate_random_str(char *str, size_t string_len) {
if (string_len & 1) string_len--;
for (size_t i=0; i<string_len; i+=2) {
u8 tmp=0;
randomGet(&tmp, sizeof(tmp));
snprintf(&str[i], 3, "%02X", tmp);
}
}
int main(int argc, char **argv)
{
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
// If on the other hand you want to write an OpenGL based application,
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Initialise sockets
socketInitializeDefault();
printf("lp2p example\n");
int sockfd=-1;
struct sockaddr_in serv_addr;
Result rc=0;
Lp2pIpConfig ip_config={0};
Lp2pGroupInfo in_group_info={0};
Lp2pGroupInfo group_info={0};
lp2pCreateGroupInfo(&in_group_info);
// This example uses [11.0.0+] WPA2-PSK. If you want to use Nintendo-encryption for the network (for communicating with accessories such as mklive), use flags=1 (which is also the default), and replace the lp2pGroupInfoSetPassphrase call with lp2pGroupInfoSetPresharedKey.
// If you want to use plaintext (open network), set in_group_info.security_type manually, and call lp2pGroupInfoSetPresharedKey (where the used keydata doesn't matter).
s8 flags=0;
lp2pGroupInfoSetFlags(&in_group_info, &flags, 1);
// See lp2p.h Lp2pGroupInfo::service_name.
char ssid[0x20] = {"libnxlp2p-"};
char passphrase[0x40] = {0};
generate_random_str(&ssid[strlen(ssid)], 8);
generate_random_str(passphrase, 16);
lp2pGroupInfoSetServiceName(&in_group_info, ssid);
lp2pGroupInfoSetPassphrase(&in_group_info, passphrase);
rc = lp2pInitialize(Lp2pServiceType_App);
printf("lp2pInitialize(): 0x%x\n", rc);
if (R_SUCCEEDED(rc)) {
printf("Press A to create a network.\n");
printf("Press X to leave a network.\n");
printf("Press the D-Pad buttons while on a network to send messages.\n");
}
printf("Press + to exit.\n");
// Main loop
while(appletMainLoop())
{
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u32 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
if (R_SUCCEEDED(rc) && (kDown & HidNpadButton_A)) {
Result rc2 = create_network(&in_group_info);
printf("create_network(): 0x%x\n", rc2);
// We didn't set the full ServiceName, so the sysmodule will generate the rest of it. Use lp2pGetGroupInfo to get the actual ServiceName.
if (R_SUCCEEDED(rc2)) {
rc2 = lp2pGetGroupInfo(&group_info);
printf("lp2pGetGroupInfo(): 0x%x\n", rc2);
}
if (R_SUCCEEDED(rc2)) {
rc2 = lp2pGetIpConfig(&ip_config);
printf("lp2pGetIpConfig(): 0x%x\n", rc2);
}
if (R_SUCCEEDED(rc2)) {
printf("Network created.\nSSID: %s\nPassphrase: %s\n", group_info.service_name, passphrase);
}
// Once on a network, you can use whatever sockets you want. In this example, we'll send/recv data with UDP-broadcast.
if (R_SUCCEEDED(rc2)) {
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("socket() failed\n");
}
else {
int ret=0;
int optval = 1;
ret = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval));
if (ret==-1) {
printf("setsockopt() failed\n");
close(sockfd);
sockfd = -1;
}
// Setup a broadcast addr. If you want to use IP addrs for members on the network, see lp2pGetMembers().
if (sockfd >= 0) {
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(ntohl(((struct sockaddr_in*)ip_config.ip_addr)->sin_addr.s_addr) | ~ntohl(((struct sockaddr_in*)ip_config.subnet_mask)->sin_addr.s_addr));
serv_addr.sin_port = htons(7777);
if (bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) {
printf("bind failed\n");
close(sockfd);
sockfd = -1;
}
}
}
}
}
if (R_SUCCEEDED(rc) && (kDown & HidNpadButton_X)) {
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
leave_network();
}
if (R_SUCCEEDED(rc) && sockfd>=0 && (kDown & (HidNpadButton_Left|HidNpadButton_Right|HidNpadButton_Up|HidNpadButton_Down))) {
char tmpstr[32];
memset(tmpstr, 0, sizeof(tmpstr));
if (kDown & HidNpadButton_Left) strncpy(tmpstr, "Button Left pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Right) strncpy(tmpstr, "Button Right pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Up) strncpy(tmpstr, "Button Up pressed.", sizeof(tmpstr)-1);
else if (kDown & HidNpadButton_Down) strncpy(tmpstr, "Button Down pressed.", sizeof(tmpstr)-1);
ssize_t ret = sendto(sockfd, tmpstr, sizeof(tmpstr), 0, (struct sockaddr*) &serv_addr, sizeof(struct sockaddr_in));
int tmp = errno;
printf("sendto(): %ld", ret);
if (ret < 0) printf(", %s", strerror(tmp));
printf("\n");
}
if (R_SUCCEEDED(rc) && sockfd>=0) {
char tmpstr[32];
memset(tmpstr, 0, sizeof(tmpstr));
struct sockaddr_in src_addr={0};
socklen_t fromlen = sizeof(struct sockaddr_in);
ssize_t ret = recvfrom(sockfd, tmpstr, sizeof(tmpstr), MSG_DONTWAIT, (struct sockaddr*) &src_addr, &fromlen);
tmpstr[sizeof(tmpstr)-1] = 0;
if (ret>0) printf("Received data: %s\n", tmpstr);
}
consoleUpdate(NULL);
}
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
leave_network();
lp2pExit();
socketExit();
consoleExit(NULL);
return 0;
}

View File

@ -20,6 +20,13 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Initialise sockets
socketInitializeDefault();
@ -44,20 +51,20 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u32 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u32 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
if (kDown & KEY_A) {
if (kDown & HidNpadButton_A) {
printf("A Pressed\n");
}
if (kDown & KEY_B) {
if (kDown & HidNpadButton_B) {
printf("B Pressed\n");
}

View File

@ -9,14 +9,16 @@
// See also libnx nfc.h.
static PadState pad;
// Indefinitely wait for an event to be signaled
// Break when + is pressed, or if the application should quit (in this case, return value will be non-zero)
Result eventWaitLoop(Event *event) {
Result rc = 1;
while (appletMainLoop()) {
rc = eventWait(event, 0);
hidScanInput();
if (R_SUCCEEDED(rc) || (hidKeysDown(CONTROLLER_P1_AUTO) & KEY_PLUS))
padUpdate(&pad);
if (R_SUCCEEDED(rc) || (padGetButtonsDown(&pad) & HidNpadButton_Plus))
break;
consoleUpdate(NULL);
}
@ -31,7 +33,7 @@ void print_hex(void *buf, size_t size) {
consoleUpdate(NULL);
}
Result process_amiibo(u32 app_id) {
Result process_amiibo() {
Result rc = 0;
// Get the handle of the first controller with NFC capabilities.
@ -92,15 +94,34 @@ Result process_amiibo(u32 app_id) {
rc = eventWaitLoop(&activate_event);
if (R_SUCCEEDED(rc)) {
printf("A tag was detected, please do not remove it from the NFC spot.\n");
printf("A tag was detected, please do not remove it from the NFC spot.\n\n");
consoleUpdate(NULL);
}
}
// Retrieve the tag info data, which contains the protocol, type and uuid.
if (R_SUCCEEDED(rc)) {
NfpTagInfo tag_info = {0};
rc = nfpGetTagInfo(&handle, &tag_info);
if (R_SUCCEEDED(rc)) {
printf("Tag protocol: 0x%02x, type: 0x%02x, UUID: ", tag_info.protocol, tag_info.tag_type);
print_hex(tag_info.uuid, tag_info.uuid_length);
printf("\n");
}
}
// If a tag was successfully detected, load it into memory.
if (R_SUCCEEDED(rc))
if (R_SUCCEEDED(rc)) {
rc = nfpMount(&handle, NfpDeviceType_Amiibo, NfpMountTarget_All);
if (rc == 0x11073) // 2115-0136
printf("This tag is corrupted and has a backup in system.\n");
if (rc == 0x12073) // 2115-0144
printf("This tag is corrupted.\n");
}
// Retrieve the model info data, which contains the amiibo id.
if (R_SUCCEEDED(rc)) {
NfpModelInfo model_info = {0};
@ -109,6 +130,7 @@ Result process_amiibo(u32 app_id) {
if (R_SUCCEEDED(rc)) {
printf("Amiibo ID: ");
print_hex(model_info.amiibo_id, 8);
printf("\n");
}
}
@ -118,8 +140,43 @@ Result process_amiibo(u32 app_id) {
NfpCommonInfo common_info = {0};
rc = nfpGetCommonInfo(&handle, &common_info);
if (R_SUCCEEDED(rc))
if (R_SUCCEEDED(rc)) {
app_area_size = common_info.application_area_size;
printf("Write counter: %d, last write date %d/%d/%d\n\n", common_info.write_counter, common_info.last_write_day, common_info.last_write_month, common_info.last_write_year);
}
}
u32 app_id=0;
// Retrieve the admin info data, which contains the app id.
if (R_SUCCEEDED(rc)) {
NfpAdminInfo admin_info = {0};
rc = nfpGetAdminInfo(&handle, &admin_info);
if (R_SUCCEEDED(rc)) {
app_id = admin_info.application_area_id;
printf("App area: 0x%x, game ID: 0x%lx, console: ", app_id, admin_info.application_id);
switch (admin_info.application_area_version) {
case NfpApplicationAreaVersion_3DS:
printf("Old 3ds");
break;
case NfpApplicationAreaVersion_WiiU:
printf("Wii U");
break;
case NfpApplicationAreaVersion_3DSv2:
printf("New 3ds");
break;
case NfpApplicationAreaVersion_Switch:
printf("Switch");
break;
case NfpApplicationAreaVersion_NotSet:
printf("Not set");
break;
default:
printf("0x%x", admin_info.application_area_version);
break;
}
printf("\n");
}
}
if (R_SUCCEEDED(rc)) {
@ -132,13 +189,15 @@ Result process_amiibo(u32 app_id) {
}
u8 app_area[0xd8] = {0}; // Maximum size of the application area.
u32 app_area_read_size = 0; // Actual number of bytes set by nfpGetApplicationArea.
if (app_area_size > sizeof(app_area)) app_area_size = sizeof(app_area);
if (R_SUCCEEDED(rc)) {
rc = nfpGetApplicationArea(&handle, app_area, app_area_size);
rc = nfpGetApplicationArea(&handle, app_area, app_area_size, &app_area_read_size);
if (R_SUCCEEDED(rc)) {
printf("App area:\n");
print_hex(app_area, app_area_size);
printf("App data:\n");
print_hex(app_area, app_area_read_size);
printf("\n");
}
}
@ -170,10 +229,6 @@ int main(int argc, char* argv[])
{
Result rc = 0;
// Hardcoded for Super Smash Bros. Ultimate.
// See also: https://switchbrew.org/wiki/NFC_services#Application_IDs
u32 app_id = 0x34f80200;
// This example uses a text console, as a simple way to output text to the screen.
// If you want to write a software-rendered graphics application,
// take a look at the graphics/simplegfx example, which uses the libnx Framebuffer API instead.
@ -181,12 +236,20 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
padInitializeDefault(&pad);
printf("NFC example program.\n");
printf("Scan an amiibo tag to display information about it.\n\n");
consoleUpdate(NULL);
// Initialize the nfp:* service.
rc = nfpInitialize(NfpServiceType_User);
// Use the NfpServiceType as required by your app, only use Debug if actually needed.
// This example uses nfpGetAdminInfo which is only available on the debug interface.
rc = nfpInitialize(NfpServiceType_Debug);
// Check if NFC is enabled. If not, wait until it is.
// Note that various official games don't use nfc*().
@ -223,13 +286,13 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop()) {
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
if (hidKeysDown(CONTROLLER_P1_AUTO) & KEY_A) {
rc = process_amiibo(app_id);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
if (padGetButtonsDown(&pad) & HidNpadButton_A) {
rc = process_amiibo();
// If an error happened, print it.
if (R_FAILED(rc))
@ -239,7 +302,7 @@ int main(int argc, char* argv[])
}
// If + was pressed to exit an eventWaitLoop(), we also catch it here.
if (hidKeysDown(CONTROLLER_P1_AUTO) & KEY_PLUS)
if (padGetButtonsDown(&pad) & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Update the console, sending a new frame to the display

222
power/Makefile Normal file
View File

@ -0,0 +1,222 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional)
#
# NO_ICON: if set to anything, do not use icon.
# NO_NACP: if set to anything, no .nacp file is generated.
# APP_TITLE is the name of the app stored in the .nacp file (Optional)
# APP_AUTHOR is the author of the app stored in the .nacp file (Optional)
# APP_VERSION is the version of the app stored in the .nacp file (Optional)
# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional)
# ICON is the filename of the icon (.jpg), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.jpg
# - icon.jpg
# - <libnx folder>/default_icon.jpg
#
# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.json
# - config.json
# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead
# of a homebrew executable (.nro). This is intended to be used for sysmodules.
# NACP building is skipped as well.
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA := data
INCLUDES := include
#ROMFS := romfs
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
ifeq ($(strip $(CONFIG_JSON)),)
jsons := $(wildcard *.json)
ifneq (,$(findstring $(TARGET).json,$(jsons)))
export APP_JSON := $(TOPDIR)/$(TARGET).json
else
ifneq (,$(findstring config.json,$(jsons)))
export APP_JSON := $(TOPDIR)/config.json
endif
endif
else
export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
endif
ifeq ($(strip $(ICON)),)
icons := $(wildcard *.jpg)
ifneq (,$(findstring $(TARGET).jpg,$(icons)))
export APP_ICON := $(TOPDIR)/$(TARGET).jpg
else
ifneq (,$(findstring icon.jpg,$(icons)))
export APP_ICON := $(TOPDIR)/icon.jpg
endif
endif
else
export APP_ICON := $(TOPDIR)/$(ICON)
endif
ifeq ($(strip $(NO_ICON)),)
export NROFLAGS += --icon=$(APP_ICON)
endif
ifeq ($(strip $(NO_NACP)),)
export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp
endif
ifneq ($(APP_TITLEID),)
export NACPFLAGS += --titleid=$(APP_TITLEID)
endif
ifneq ($(ROMFS),)
export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS)
endif
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
ifeq ($(strip $(APP_JSON)),)
@rm -fr $(BUILD) $(TARGET).nro $(TARGET).nacp $(TARGET).elf
else
@rm -fr $(BUILD) $(TARGET).nsp $(TARGET).nso $(TARGET).npdm $(TARGET).elf
endif
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
ifeq ($(strip $(APP_JSON)),)
all : $(OUTPUT).nro
ifeq ($(strip $(NO_NACP)),)
$(OUTPUT).nro : $(OUTPUT).elf $(OUTPUT).nacp
else
$(OUTPUT).nro : $(OUTPUT).elf
endif
else
all : $(OUTPUT).nsp
$(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm
$(OUTPUT).nso : $(OUTPUT).elf
endif
$(OUTPUT).elf : $(OFILES)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

91
power/source/main.c Normal file
View File

@ -0,0 +1,91 @@
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <switch.h>
const char* const chargers[4] = {"None", "Full Power", "Low Power", "Unsupported"};
int main(int argc, char **argv)
{
consoleInit(NULL);
Result rc = psmInitialize();
if (R_FAILED(rc))
goto cleanup;
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("\x1b[16;16HPress PLUS to exit.");
// Main loop
while(appletMainLoop())
{
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
u32 charge;
double rawCharge;
double age;
bool isEnoughPower;
PsmChargerType type;
printf("\x1b[1;1H\x1b[K");
rc = psmGetBatteryChargePercentage(&charge);
if (R_FAILED(rc))
{
printf("psmGetBatteryChargePercentage: %08X", rc);
continue;
}
rc = psmGetRawBatteryChargePercentage(&rawCharge);
if (R_FAILED(rc))
{
printf("psmGetRawBatteryChargePercentage: %08X", rc);
continue;
}
rc = psmGetBatteryAgePercentage(&age);
if (R_FAILED(rc))
{
printf("psmGetBatteryAgePercentage: %08X", rc);
continue;
}
rc = psmIsEnoughPowerSupplied(&isEnoughPower);
if (R_FAILED(rc))
{
printf("psmIsEnoughPower: %08X", rc);
continue;
}
rc = psmGetChargerType(&type);
if (R_FAILED(rc))
{
printf("psmGetChargerType: %08X", rc);
continue;
}
printf("Battery charge: %u%% (%1.2f%%)", charge, rawCharge);
printf("\n\x1b[KBattery age: %1.2f%%", age);
printf("\n\x1b[KHas enough power: %s", isEnoughPower ? "Yes" : "No");
printf("\n\x1b[KCharger type: %s", chargers[type]);
consoleUpdate(NULL);
}
cleanup:
psmExit();
consoleExit(NULL);
return 0;
}

View File

@ -12,6 +12,13 @@ int main(int argc, char **argv)
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
Result rc = setInitialize();
if (R_FAILED(rc)) printf("setInitialize() failed: 0x%x.\n", rc);
@ -47,15 +54,15 @@ int main(int argc, char **argv)
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}

View File

@ -16,20 +16,27 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// Other initialization goes here. As a demonstration, we print hello world.
printf("Hello World!\n");
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
// Your code goes here

View File

@ -6,70 +6,91 @@
// Include the main libnx system header, for Switch development
#include <switch.h>
// Size of the inner heap (adjust as necessary).
#define INNER_HEAP_SIZE 0x80000
#ifdef __cplusplus
extern "C" {
#endif
// Sysmodules should not use applet*.
u32 __nx_applet_type = AppletType_None;
// Sysmodules will normally only want to use one FS session.
u32 __nx_fs_num_sessions = 1;
// Adjust size as needed.
#define INNER_HEAP_SIZE 0x80000
size_t nx_inner_heap_size = INNER_HEAP_SIZE;
char nx_inner_heap[INNER_HEAP_SIZE];
// Newlib heap configuration function (makes malloc/free work).
void __libnx_initheap(void)
{
void* addr = nx_inner_heap;
size_t size = nx_inner_heap_size;
static u8 inner_heap[INNER_HEAP_SIZE];
extern void* fake_heap_start;
extern void* fake_heap_end;
// Newlib
extern char* fake_heap_start;
extern char* fake_heap_end;
fake_heap_start = (char*)addr;
fake_heap_end = (char*)addr + size;
// Configure the newlib heap.
fake_heap_start = inner_heap;
fake_heap_end = inner_heap + sizeof(inner_heap);
}
// Init/exit services, update as needed.
void __attribute__((weak)) __appInit(void)
// Service initialization.
void __appInit(void)
{
Result rc;
// Initialize default services.
// Open a service manager session.
rc = smInitialize();
if (R_FAILED(rc))
fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM));
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM));
// Retrieve the current version of Horizon OS.
rc = setsysInitialize();
if (R_SUCCEEDED(rc)) {
SetSysFirmwareVersion fw;
rc = setsysGetFirmwareVersion(&fw);
if (R_SUCCEEDED(rc))
hosversionSet(MAKEHOSVERSION(fw.major, fw.minor, fw.micro));
setsysExit();
}
// Enable this if you want to use HID.
/*rc = hidInitialize();
if (R_FAILED(rc))
fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_HID));*/
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_InitFail_HID));*/
//Enable this if you want to use time.
// Enable this if you want to use time.
/*rc = timeInitialize();
if (R_FAILED(rc))
fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_Time));
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_InitFail_Time));
__libnx_init_time();*/
// Disable this if you don't want to use the filesystem.
rc = fsInitialize();
if (R_FAILED(rc))
fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_FS));
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_InitFail_FS));
// Disable this if you don't want to use the SD card filesystem.
fsdevMountSdmc();
}
void __attribute__((weak)) userAppExit(void);
// Add other services you want to use here.
void __attribute__((weak)) __appExit(void)
{
// Cleanup default services.
fsdevUnmountAll();
fsExit();
//timeExit();//Enable this if you want to use time.
//hidExit();// Enable this if you want to use HID.
// Close the service manager session.
smExit();
}
// Service deinitialization.
void __appExit(void)
{
// Close extra services you added to __appInit here.
fsdevUnmountAll(); // Disable this if you don't want to use the SD card filesystem.
fsExit(); // Disable this if you don't want to use the filesystem.
//timeExit(); // Enable this if you want to use time.
//hidExit(); // Enable this if you want to use HID.
}
#ifdef __cplusplus
}
#endif
// Main program entrypoint
int main(int argc, char* argv[])
{

View File

@ -166,7 +166,8 @@
"type": "debug_flags",
"value": {
"allow_debug": false,
"force_debug": true
"force_debug": true,
"force_debug_prod": false
}
}]
}

View File

@ -1,5 +1,6 @@
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <switch.h>
@ -12,22 +13,30 @@ int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("\x1b[16;16HPress PLUS to exit.");
printf("\x1b[17;16HTZ=%s\n", getenv("TZ"));
// Main loop
while(appletMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS) break; // break in order to return to hbmenu
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
//Print current time
time_t unixTime = time(NULL);
struct tm* timeStruct = gmtime((const time_t *)&unixTime);//Gets UTC time. If you want local-time use localtime().
struct tm* timeStruct = localtime((const time_t *)&unixTime); // Gets local time. If you want UTC use gmtime().
int hours = timeStruct->tm_hour;
int minutes = timeStruct->tm_min;

View File

@ -31,6 +31,13 @@ int main(int argc, char* argv[])
// take a look at the graphics/opengl set of examples, which uses EGL instead.
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
printf("usbhs example\n");
memset(&inf_event, 0, sizeof(inf_event));
@ -58,14 +65,14 @@ int main(int argc, char* argv[])
// Main loop
while (appletMainLoop())
{
// Scan all the inputs. This should be done once for each frame
hidScanInput();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// hidKeysDown returns information about which buttons have been
// just pressed in this frame compared to the previous one
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & KEY_PLUS)
if (kDown & HidNpadButton_Plus)
break; // break in order to return to hbmenu
if (R_SUCCEEDED(rc2)) rc = eventWait(&inf_event, 0);