Analog pin value keep fluctuating in Arduino

I tried reading analog input for a switch.But the analog value is moving gradually from 0 to 1023 and back to 0 ,eventhough the switch is not pressed.
When switch is pressed,it reaches 1023.This is agreeable.
But when switch is not pressed,it reaches 1023.Please help me to resolve the issue.This will solve my other issue automatically…
I am using 20K ohm resistor.

#include <SPI.h>
#include <PubSubClient.h>
#include <Ethernet.h>
#include <util.h>
#include <ctype.h>

#define CLIENTID “ArduinoSensor”
#define TOPICNAME “switch/signal”
#define POLLINTERVAL 120000

#define PORT 80
//Connect to MQTT server
byte server1 = { X};
byte mac = {X};

IPAddress arduinoIP(X);
IPAddress dnsIP(X);
IPAddress gatewayIP(X);
IPAddress subnetIP(X);
EthernetServer server(PORT);

EthernetClient ethClient;
PubSubClient arduinoClient(server1, 8081, callback, ethClient);

void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}

int analogPin = 0; // potentiometer wiper (middle terminal) connected to analog pin 3

// outside leads to ground and +5V

int val = 0; // variable to store the value read

void setup()

{

Serial.begin(9600); // setup serial

Ethernet.begin(mac, arduinoIP, dnsIP, gatewayIP, subnetIP);
beginConnection() ;
}

void beginConnection() {
Serial.begin(9600);
//Ethernet.begin(mac) ;
int connRC = arduinoClient.connect(CLIENTID) ;
if (!connRC) {
Serial.println(connRC) ;
Serial.println(“Could not connect to MQTT Server”);
Serial.println(“Please reset the arduino to try again”);
delay(100);
exit(-1);
}
else {
Serial.println(“Connected to MQTT Server…”);

}}

void loop()

{

val = analogRead(analogPin); // read the input pin

Serial.println(val);
delay(100); // debug value
if(val == 1023)
{
Serial.println(“Button pressed and message published”);
arduinoClient.publish(TOPICNAME, “Button A is Pressed”) ;
}
}

Its working better…But I see a problem with the analogRead…
The readings goes as below,
0
0
0
0
19
20
49
71
117
126
227
322
451
571
702
809
923
1023
Button pressed and message published
1023
Button pressed and message published
1023
Button pressed and message published
1022
1003
966
929
905
842
748
615
480
356
229
122
1
0
0
0
0
0
0

The readings gradually increasing till 1023 and then decreasing gradually.This should not happen as it is publishing messages when it is reaching 1023 without even pressing the switch.
But When the switch is pressed,it reaches 1023 and publishing the message.This is fine as this is required scenario…

Can you please help how to control the flow of analogRead?If this is kept under control,then my problem would be resolved…

I had the same problem before with sensor readings 10k resistor to ground and output of switch did the job

Can you please help how to control the flow of analogRead?

Why are you using analogRead() to read a digital device? Are you expecting to have the switch a little bit pressed? That's like being a little bit pregnant.