#include "ThingSpeak.h"
#include "WiFi.h"
unsigned long myChannelNumber = 2465326;
const char * myWriteAPIKey = "0DAN5L2E1ROK7WZY";
char ssid[] = "Wokwi-GUEST"; // your network SSID (name)
char pass[] = ""; // your network password
int x=0;
int y=0;
int realx=0;
int realy=0;
int state=0;
int pre_button=0;
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(100);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
// Connect or reconnect to WiFi
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println("Wokwi-GUEST");
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
}
void loop() {
joystick();
ThingSpeak.setField(1,realx);
ThingSpeak.setField(2,realy);
ThingSpeak.setField(3,state);
// Write value to Field 1 of a ThingSpeak Channel
int httpCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (httpCode == 200) {
Serial.println("Channel write successful.");
}
else {
Serial.println("Problem writing to channel. HTTP error code " + String(httpCode));
}
// Wait 20 seconds to update the channel again
delay(20000);
}
void joystick(){
int horz=analogRead(2);
int vert=analogRead(4);
if (pre_button==0 && digitalRead(21)==1){
state=1;
}else{
state=0;
}
pre_button=digitalRead(21);
if(horz<2048){
x=min(x+1,5);
}
if(horz>2048){
x=max(x-1,0);
}
if(vert<2048){
y=min(y+1,3);
}
if(vert>2048){
y=max(y-1,0);
}
realx=(x+3)*54;
realy=(y+2)*16.5;
Serial.println("realx="+String(realx)+"realy="+String(realy));
delay(200);
}