Converting potentiometer value to string for GLCD display - arduino

I'm trying to display a potentiometer's value on an Adafruit ST7565 GLCD. My serial monitor is giving me values between 1.62-1.67, while the GLCD ranges from -20,000 to +20,000. I'm not sure whether the arithmetic/data type is wrong or whether I am allocating memory improperly for the "sprintf" conversion.
#include "ST7565.h"
#include "stdlib.h"
char buffer[5];
int ledPin = 13; // LED connected to digital pin 13
char str[8];
// the LCD backlight is connected up to a pin so you can turn it on & off
#define BACKLIGHT_LED 10
// pin 9 - Serial data out (SID)
// pin 8 - Serial clock out (SCLK)
// pin 7 - Data/Command select (RS or A0)
// pin 6 - LCD reset (RST)
// pin 5 - LCD chip select (CS)
ST7565 glcd(9, 8, 7, 6, 5);
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
void setup() {
Serial.begin(9600);
// turn on backlight
pinMode(BACKLIGHT_LED, OUTPUT);
digitalWrite(BACKLIGHT_LED, HIGH);
// initialize and set the contrast to 0x18
glcd.begin(0x18);
glcd.display(); // show splashscreen
delay(3000);
glcd.clear();
Serial.println(" ");
digitalWrite(BACKLIGHT_LED, HIGH);
glcd.drawstring(0,0," ");
glcd.display();
glcd.clear();
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
digitalWrite(BACKLIGHT_LED, HIGH);
Serial.println(voltage);
sprintf(str,"%d",voltage); // converts to decimal base.
glcd.drawstring(0,0,str);
glcd.display();
delay(500);
glcd.clear();
}
Any insight is appreciated. I don't have much formal programming experience, so linking a tutorial about data types won't be of any use. I need to see a specific example like this worked out to truly understand.

You used %d to print out a float; this is undefined behaviour (in your case, it probably dumped out the integer representation of some part of the float's bit sequence).
Instead of using sprintf (since sprintf(..., "%f", val) is reportedly broken on Arduino), use dtostrf:
dtostrf(voltage, 0, 2, buf);
Also, if you're interested, you can see how Arduino prints floats here.

Related

Arduino: Oled not working when SD library is included

I'm currently trying to put together a datalogger with an OLED screen and am having issues when adding the SD library to the script. I've seen that others have gotten error messages when combining Oled and SD cards that is related to RAM. Though in my case, the code runs, there is no error message, but the screen doesn't display anything. The code below shows the "OLED code" where the Oled display wouldn't show anything when I added the "#include <SD.h>". Also, since I quite new to this, some constructive criticism of the code itself is also welcome
Thanks!
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "Adafruit_MCP9808.h"
#include <Adafruit_BME280.h>
Adafruit_BME280 bme; // use I2C interface
Adafruit_Sensor *bme_temp = bme.getTemperatureSensor();
Adafruit_Sensor *bme_pressure = bme.getPressureSensor();
Adafruit_Sensor *bme_humidity = bme.getHumiditySensor();
//oled definitions
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Create the MCP9808 temperature sensor object
Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3D); // Address 0x3D for 128x64
// Clear the buffer
display.display();
delay(2000);
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.setTextColor(WHITE);
while (!Serial);
Serial.println("Loading");
if (!tempsensor.begin(0x18)) {
Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
while (1);
}
Serial.println(F("Found MCP9808!"));
tempsensor.setResolution(3); // sets the resolution mode of reading, the modes are defined in the table bellow:
// Mode Resolution SampleTime
// 0 0.5°C 30 ms
// 1 0.25°C 65 ms
// 2 0.125°C 130 ms
// 3 0.0625°C 250 ms
if (!bme.begin()) {
Serial.println(F("Could not find a valid BME280 sensor, check wiring!"));
while (1) delay(10);
}
bme_temp->printSensorDetails();
bme_pressure->printSensorDetails();
bme_humidity->printSensorDetails();
}
void loop() {
float temp = bme.readTemperature(); // get temperature in degree Celsius
float humi = bme.readHumidity(); // get humidity in rH%
float pres = bme.readPressure(); // get pressure in Pa
tempsensor.wake();
//Serial.println (tempsensor.getResolution());
float c = tempsensor.readTempC();
float f = tempsensor.readTempF();
//float sensor=analogRead(A4);
display.setCursor(0, 0);
display.print(F("Temp_1: "));
display.print(c,2);display.println(" \tC ");
display.println("");
display.print(F("Temp_2: "));
display.print(temp,2);display.println(" \tC ");
display.println("");
display.print(F("Humidity: "));
display.print(humi,2);display.println(" %RH ");
display.println("");
display.print(F("Pressure: "));
display.print(pres/100,2);display.println(" kPa ");
display.display();
delay(1000);
display.clearDisplay();
Its just memory problem. I fix it by decrease the resolution only for usage area.. Its not the best solution however good enough for me
This was apparently a memory issue.
I've now connected an Arduino Mega instead of a Nano, and the code ran nicely. I've also added the remaining piece of code that was necessary to log the sensor readings.
According to what I've read on other forums, the SD and SPI libraries take up quite a lot of memory.

PIR sensor detecting continuosly therefore loop counter( "i") may be not incrementing and loop stay in a idle state

My project is: Read temperature and send it through SMS with 10 min span, and within this span if there is any motion then send SMS "MOTION DETECTED".
so, just for testing i used two LED one for temperate( it will stay on for 10 min) SMS and another for MOTION (it will blink once) and commented function call statement i.e. sendMessage ,sendMsg
everything is working fine but problem is " when i keeping and shaking continuously for a long time my hand in front of the PIR sensor , it continuously detecting motion and may be counter is not increasing therefore dled i.e. 1st one for temp stay on more than 10 min..., but if i keep my hand in front of the PIR sensor for a few sec just to detect Motion( as many time as i want) then its working fine... but for continuous detection something happening for what dled stay on more than 10 min..for example for 30 sec continuous detection dled stay on 10 min 30 sec ...for 1 min dled stay on 11mins..."
this is the problem hope i make you guys make it understandable...
so please help me out.. thanks
here is the code below...
#include <DHT.h> //DHT sensor
#include <SoftwareSerial.h> //this is a constructor for gsm
#include<LiquidCrystal.h> //this is for LCD display
#include "DHT.h"
#define DHTPIN 8 //blue 8 define pins for DHT
#define DHTTYPE DHT11 // DHT11
#define pir 6 //yellow 6
#define pled 13 //for PIR led
#define dled 7 //for DHT led
DHT dht(DHTPIN,DHTTYPE);
int pirState=LOW;
int prival=0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial mySerial(9, 10); //9-->Rx; 10-->Tx
void setup() {
// put your setup code here, to run once:
mySerial.begin(9600);
Serial.begin(9600);
delay(100);
Serial.println("SMS ALERT");
pinMode(pir,INPUT); //set pir pin as input
dht.begin();
lcd.begin(16,2);
pinMode(pled,OUTPUT); //LED for pir sensor... "set pled pin as output"
pinMode(dled,OUTPUT); //LED for DHT sensor... "set dled pin as output"
}
void loop() {
// put your main code here, to run repeatedly:
// block for sending temp information...
float t=dht.readTemperature();
Serial.print("Temperature: ");
Serial.println(t);
Serial.println("SMS INITIATING...");
// SendMessage(t); to sent temp...
/*stay HIGH for 10 min..when loop will end pin will be low i.e. LED will be
off then again for new loop it will be on ..and it will continue... */
digitalWrite(dled,HIGH);
Serial.println("DONE...");
lcd.print("Temp is: ");
lcd.print(t);
lcd.print((char)223);
lcd.print("C ");
delay(500);
//checking pir sensor.. whether motion is detected or not..
//when motion is detected sent msg "MOTION DETECTED"
//and loop will continue for 10 min span
int i=0;
while(i!=600){
prival=digitalRead(pir); //read pir pin = 6
if(prival==HIGH)
{
if(pirState==LOW)
{
Serial.println("Motion detected");
Serial.print("Temp is: ");
Serial.print(t);
Serial.print((char)223);
Serial.println("C");
lcd.setCursor(0,0);
lcd.print("temp is : ");
lcd.print(t);
lcd.print(char(223));
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Motion Detected");
/*when motion is detected only that time LED will be on.. and stay
high for 200mSec then it will be off i.e. it will blink for once */
digitalWrite(pled,HIGH);
delay(200);
digitalWrite(pled,LOW);
Serial.println("SMS INITIATING FOR MOTION...");
//sendMsg(); to send "motion detected msg"
Serial.println("DONE...");
pirState=HIGH;
}
}
else
{
if(pirState==HIGH)
{
Serial.println("Motion stopped ");
Serial.print("Temp is: ");
Serial.print(t);
Serial.print((char)223);
Serial.println("C");
lcd.setCursor(0,0);
lcd.print("temp is : ");
lcd.print(t);
lcd.print(char(223));
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Motion stopped ");
pirState=LOW;
}
}
i++;
delay(1000);
}
digitalWrite(dled,LOW);
delay(500);
}
/*
void SendMessage(float t )
{
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"XXXXXXXXXX\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("TEMP IS : ");// The SMS text you want to send
mySerial.println(t);
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
void sendMsg(){
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"XXXXXXXXXX\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("MOTION DETECTED...");// The SMS text you want to send
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
*/
The problem is that your code is written in a blocking fashion using delay(500); and so on. You execute the PIR sensing 10 * 60 times and delay(1000); each, thus you expect 10 mins delay for the LED toggle. However, the inner delay(200); will lengthen the time spent inside the PIR loop, as you noticed.
You can address this problem in multiple ways, but the easiest would be to do LED events asynchronously using a global timeout timer. You set the timeout timer to 10 mins, turn the LED on and then after 10 mins, your timer interrupt calls the relevant timeout service routine which turns the LED off. Same goes for the second LED.
Your project might in general benefit from using some kind of RTOS instead of writing plain Arduino code.

Arduino RFID (Wiegand) Continuous reading

I have this RFID reader "Rosslare AY-X12", and it's working with Wiegand 26bit. I have an arduino mini Pro and connected together it's working fine but it only reads the card one time and then I have nothing.
When I put on the card arduino reads that card but only one time during the card is near by the reader and it again reads that card when I put off the card and then I put on. But I want to read that card continuously, I mean when the card is near by the Reader still reading the card, every 1ms reads that card.
Do you have any idea how to do that ? Is there any RFID arduino library which can do that? I had got the Mifare and its can do that. But this 125Khz reader which can communicate over Wiegand can't do that or I don't know how to do that.
I'm using this library : https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino
My previous answer was deleted. I am going to make another attempt to answer the questions.
Do you have any idea how to do that ?
This cannot be done by Arduino because Arduino in your case is just reading the D0 and D1 pulses from your RFID reader. Since your RFID reader Rosslare AY-X12 does not send out continuous output of wiegand protocol, there is no way Arduino can read more than what was not sent to it.
The common RFID readers will not send continuous data of the same card because in the common use case (entry/exit/attendance), normally one tap is to check-in and another tap is to check-out. If the RFID reader sends continuous data of the same card, the main system receiving the multiple wiegand data will be confused and will not be able to determine if the user actually wish to check-in or check-out.
Is there any RFID arduino library which can do that?
No. There is no such RFID Arduino library. If the RFID reader is not sending out continuous data, there is no way the receiver (Arduino) can receive them.
Is there a way to achieve this?
Yes, there are some readers that has the option to turn on the continuous output of data, for example 714-52 Mifare® ID Reader with selectable outputs. In its specification :
Continuous output with tag in field or single transmission
With this reader configured to continuous output, you can then use Arduino and the monkeyboard wiegand library to read the data.
I wrote my own wiegand code. Its not that difficult. I attached interrupts to the data pins and when they change I log the zero or one. You then build up the binary string and once timed out because no bits coming in. Then you convert the binary to decimal.
#include <LiquidCrystal.h>
int data0 = 2; //set wiegand data 0 pin
int data1 = 3; //set wiegand data 1 pin
unsigned long bit_holder; //unsigned long (positive 32 bit number)
unsigned long oldbit = 0;
volatile int bit_count = 0;
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
unsigned long badge;
unsigned int timeout;
unsigned int t = 800;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("Present Badge");
delay(2);
Serial.println("Present Badge");
pinMode(data0, INPUT);
digitalWrite(data0, HIGH);
pinMode(data1, INPUT);
digitalWrite(data1, HIGH);
attachInterrupt(0, zero, FALLING); //attach interrupts and assign functions
attachInterrupt(1, one, FALLING);
}
void zero(){
bit_count ++;
bit_holder = (bit_holder << 1) + 0; //shift left one and add a 0
timeout = t;
}
void one(){
bit_count ++;
bit_holder = (bit_holder << 1) + 1; //shift left one and add a 1
timeout = t;
}
void loop() {
timeout --;
if (timeout == 0 && bit_count > 0){
lcd.clear();
lcd.print("Dec:");
lcd.print(bit_holder);
lcd.setCursor(0,1);
lcd.print("Hex:");
lcd.print(String(bit_holder,HEX));
Serial.print("bit count= ");
Serial.println(bit_count);
Serial.print("bits= ");
Serial.println(bit_holder,BIN);
oldbit = bit_holder; //store previous this value as previous
bit_count = 0; //reset bit count
bit_holder = 0; //reset badge number
}
}
You may need to find a reader that offer a continuously reading, as I know almost of Wiegand Reader in the market can't perform a continuously reading because they have a "onboard" control that controls this...
Maybe you can try with Arduino Serial RFID Reader...
try a this timer libary Timer1 and mayby try this code it worked for me, my tags and cards now reads continuously.
Greetings from Denmark
Gregor
#include <Timer1.h>
//******************************************************************
// ATmega168, ATmega328:
// - Using Timer 1 disables PWM (analogWrite) on pins 9 and 10
// ATmega2560:
// - Using Timer 1 disables PWM (analogWrite) on pins 11 and 12
// - Using Timer 3 disables PWM (analogWrite) on pins 2, 3 and 5
// - Using Timer 4 disables PWM (analogWrite) on pins 6, 7 and 8
// - Using Timer 5 disables PWM (analogWrite) on pins 44, 45 and 46
//******************************************************************
unsigned int lastTime;
#include <SoftwareSerial.h>
SoftwareSerial RFID = SoftwareSerial(2,4);
char character;
String our_id;
void setup()
{
// Disable Arduino's default millisecond counter (from now on, millis(), micros(),
// delay() and delayMicroseconds() will not work)
disableMillis();
// Prepare Timer1 to count
// On 16 MHz Arduino boards, this function has a resolution of 4us
// On 8 MHz Arduino boards, this function has a resolution of 8us
startCountingTimer1();
lastTime = readTimer1();
Serial.begin(9600);
RFID.begin(9600);
}
void loop()
{
unsigned int now = readTimer1();
while (RFID.available()>0)
{
character = RFID.read();
our_id += character;
lastTime = now;
}
if (our_id.length() > 10) {
our_id = our_id.substring(1,13);
Serial.println(our_id);
our_id = "";
}
delay(1000);
}

Arduino code combination - combine temp sensor and buzzer at max min temp codes

I love this site. Thank you all for what you do here!
I am finally getting into doing my own projects with Arduino Uno. I find I learn best when I just do it. I found a tutorial on getting temperature from my TMP36GZ to read out on my 16x2 LCD via Ardino. Way cool! But now, I want to figure out how to make a CEM1203(42) buzzer go off when the temperature hits a maximum and/or minimum. I found a simple code to get the buzzer to go too. Now I just need to combine the two.
Below are the 2 codes. I would like to, say, have the buzzer sound when temp is =/<65°F and =/>75°F.
Thank you for any help you can offer. I'm very excited to be learning this stuff!
/*
Piezo
This example shows how to run a Piezo Buzzer on pin 9
using the analogWrite() function.
It beeps 3 times fast at startup, waits a second then beeps continuously
at a slower pace
*/
void setup() {
// declare pin 9 to be an output:
pinMode(9, OUTPUT);
beep(50);
beep(50);
beep(50);
delay(1000);
}
void loop() {
beep(200);
}
void beep(unsigned char delayms){
analogWrite(9, 20); // Almost any value can be used except 0 and 255
// experiment to get the best tone
delay(delayms); // wait for a delayms ms
analogWrite(9, 0); // 0 turns it off
delay(delayms); // wait for a delayms ms
}
/*
September 12 2013
October 25 2012
Based off of a project by DJ Mentzik.
Enhanced and modified by WWC and citin.
Supporting documents can be found at http://www.instructables.com/member/WWC/
Use and modife as needed.
Displays Current, 8 sec Average, Max and Min Temperature.
To wire your LCD screen to your Arduino, connect the following pins:
LCD Pin 6 to digital pin 12
LCD Pin 4 to digital pin 11
LCD Pin 11 to digital pin 5
LCD Pin 12 to digital pin 4
LCD Pin 13 to digital pin 3
LCD Pin 14 to digital pin 2
LCD PIN 15 to POS
LCD PIN 16 to GND
*/
#include <LiquidCrystal.h> // include the LCD driver library
//declare variables
float tempC = 0; // Variable for holding Celcius temp (floating for decimal points precision)
float tempf = 0; // variable for holding Fareghneit temp
int tempPin = 0; // Declaring the Analog input to be 0 (A0) of Arduino board.
float samples[8]; // Array to hold 8 samples for Average temp calculation
float maxi = 0,mini = 100; // Max/Min temperature variables with initial values. LM35 in simple setup only measures Temp above 0.
int i;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins
void setup()
{
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bps
lcd.begin(16, 2); // Set up the LCD's number of columns and rows:
lcd.setCursor(2, 0); // Set LCD cursor position (column, row)
lcd.print("Waynes World"); // Print text to LCD
lcd.setCursor(3, 1); // Set LCD cursor position (column,row)
lcd.print("Thermometer"); // Print text to LCD
delay(5000); // wait 500ms // Delay to read text
lcd.clear(); // clear LCD display // Clear the display
lcd.setCursor(2, 0); // Set LCD cursor position (column, row)
lcd.print("LCD Displayed"); // Print text to LCD
lcd.setCursor(1, 1); // Set LCD cursor position (column, row)
lcd.print(" Averaged Temp "); // Print text to LCD
delay(5000); // Delay to read text
lcd.clear(); // Clear LCD
}
void loop()
{
Serial.println(""); // Blank line for spacing in the serial monitor
Serial.println("You are looking at a project built by WWC."); // Print text to Serial monitor
Serial.print("Feal free to use and modife as needed.");
Serial.println(""); // Blank line for spacing in the serial monitor
Serial.print("LM35 Raw data: "); // Print text to Serial monitor
Serial.println(analogRead(tempPin)); // Displays on serial monitor the sampled value before conversion to real Temperature reading
// Start of calculations FOR loop.
for(i = 0;i<=7;i++){ // gets 8 samples of temperature
samples[i] = ( 4.4 * analogRead(tempPin) * 26) / 1024.0; // conversion math of tmp36GZ sample to readable temperature and stores result to samples array.
Serial.println(samples[i]); // Print samples [i] to sertiual monitor
// ( LCD note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0); // Set LCD cursor position (column 0, row 0)
lcd.print("Current Temp is: "); // Print text to LCD
lcd.setCursor(1, 1); // Set LCD cursor position (column 1, row 1)
lcd.print(" Celcius "); // Print text to LCD
lcd.setCursor(12, 1); // Set LCD cursor position (column 12, row 1)
lcd.print(samples[i]); // print current Temp sample to LCD
tempC = tempC + samples[i]; // do the addition for average temperature
delay(800); // wait 800ms
} // END of FOR loop
Serial.println(""); // Blank line for spacing in the serial monitor
Serial.println(""); // Blank line for spacing in the serial monitor
tempC = tempC/8.0; // calculated the averare of 8 samples in Celcius
tempf = (tempC * 9)/ 5 + 32; // converts to fahrenheit
if(tempC > maxi) {maxi = tempC;} // set max temperature
if(tempC < mini) {mini = tempC;} // set min temperature
if(tempC >16.0)
// Send Results to Serial Monitor
Serial.println("New measurement:");
Serial.print(" Average Temperature in Celcius is " ); // Print text to Serial monitor
Serial.println(tempC);//send the data to the computer // Send the data to the computer
Serial.print(" Average Temperature in Farenait is " ); // Print text to Serial monitor
Serial.println(tempf);//send the data to the computer // Send the data to the computer
Serial.print(" MAX Temperature in Celcius is " ); // Print text to Serial monitor
Serial.println(maxi);//send the data to the computer // Send the data to the computer
Serial.print(" MIN Temperature in Celcius is " ); // Print text to Serial monitor
Serial.println(mini);//send the data to the computer // Send the data to the computer
// Send results to LCD.
lcd.setCursor(0, 1); // Set LCD cursor position (column 0, line 1)
lcd.print(" Fahrenheit "); // Print text to LCD
lcd.setCursor(12, 1); // Set LCD cursor position (column 12, line 1)
lcd.print(tempf); // Send the data to the LCD
delay(6000); // Wait 3 seconds to display the Fahrenheit temp and 3 seconds to display results to LCD screen befor starting the loop again = 6 seconds.
tempC = 0; // Set tempC to 0 so calculations can be done again
}
Your temperature code has the most in it so put the additions in there.
Usually you would transfer all from setup. In this case:
pinMode(9, OUTPUT);
is the only required code. You can put in the rest if you want it to beep on startup.
Transfer over the entire "void beep()" function. So you can call it the same way it is called in the "void loop()" function.
Then in your temp code after tempf is calculated in the line:
tempf = (tempC * 9)/ 5 + 32;
Put some code like:
if (tempf <= 65){
//low temp beep code here
}
else if (tempf >= 75) {
//high temp beep code here
}

Arduino pull-up resistor not working

I am using an Arduino board to read out the value of a soft potmeter. (a strip that detects touch). This works perfectly fine as long as the strip is being touched (a resistance is added to the current).
When the strip is not touched, a completely random floating number is read by the analog pin. Forums mention that you have to add a pullup/pulldown resistor to cancel this effect, but this does not seem te be working. What is wrong with this code?
int potPin = 2;
int curval = 0;
// detect potmeter value
void setup() {
//enable pullup resistor, but still results in erratic output
//when potmeter is not touched
digitalWrite(potPin, HIGH);
//write to serial
Serial.begin(9600);
}
void loop() {
curval = analogRead(potPin);
// this works when the potmeter is being pressed (displays 0 to 1024)
Serial.println(curval);
delay(150);
}
Change
int potPin = 2;
to
int potPin = A2;
Your original use of "2" in both places is assigning Digital Pin 2 to pull-up and reading from Analog Channel 2. As "2" maps correspondingly to is PortD bit 2 and Analog Channel 2 (aka ADC2) is PortC bit 2. As shown below
digitalWrite(2, HIGH); // Pin D2
curval = analogRead(2); // AMUX Channel 2
where A2 shown below is interpreted as follows
digitalWrite(A2, HIGH); // Pin (A2 aka D16)
curval = analogRead(A2); // AMUX Channel 2 on Pin A2
On an UNO (ATmega328) the analogRead() function will interpret 0-7 as channels and will convert the pins A0 through A7 (D14-D21) to corresponding channels, to read from.
Note:
ADC6 and 7 are not available on the chip used on the UNO.
A0-A7 are alias for Digital 14 through 21. Where the labels A0-A7 are typically used.

Resources