Arduino Serial.print() if Weight is Steady - arduino

I have a code in Arduino that runs a height and weight sensor combination with an ultrasonic sensor and load cells. I need the weights and heights to print to the serial monitor only when the weight has been steady on the scale for three seconds and the same for the height. What I mean by steady is that the weight or height would have to be the same for three seconds. Is this possible?
The code that I have for the circuit is as follows:
#include <LiquidCrystal.h>
#define calibration_factor -13180.00
//This value is obtained using the SparkFun_HX711_Calibration sketch
#define DOUT 7
#define CLK 6
HX711 scale(DOUT, CLK);
LiquidCrystal LCD(10, 9, 5, 4, 3, 2); //Create Liquid Crystal Object
called LCD
int trigPin=13; //Sensor Trip pin connected to Arduino pin 13
int echoPin=11; //Sensor Echo pin connected to Arduino pin 11
int myCounter=0; //declare your variable myCounter and set to 0
int servoControlPin=6; //Servo control line is connected to pin 6
float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
void setup() {
Serial.begin(9600);
Serial.println("HX711 scale demo");
scale.set_scale(calibration_factor); //This value is obtained by
using the SparkFun_HX711_Calibration sketch
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
Serial.println("Readings:");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
LCD.setCursor(0,0); //Set LCD cursor to upper left corner, column 0, row 0
LCD.print("Target Distance:");
}
void loop() {
Serial.println("Reading: ");
Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
Serial.println();
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in high state
pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds
pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
targetDistance= speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance= targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile)
LCD.setCursor(0,1); //Set cursor to first column of second row
LCD.print(" "); //Print blanks to clear the row
LCD.setCursor(0,1); //Set Cursor again to first column of second row
LCD.print(targetDistance); //Print measured distance
LCD.print(" inches"); //Print your units.
delay(250); //pause to let things settle
Serial.print(targetDistance);
Serial.println();
Serial.print(" inches ");
delay(250);
}

Related

Arduino/ESP8266 Using interrupts to take samples

I'm trying to measure the discharge time of a capacitor using a NodeMCU board. See complete sketch below. This code works fine, however I want to improve it to get to better time scales, by using the ESP.getCycleCount() function and interrupts for the timing. The part of interest is this:
startTime = micros();
while (digitalRead(capPos) == HIGH) {
delayMicroseconds (1);
}
endTime = micros();
The while loop I want to rewrite into some form of interrupt based function, listening to a falling edge of the capPos pin, replacing the above function with something like this:
startTime = micros();
attachInterrupt(digitalPinToInterrupt(capPos), dischargeInterrupt, FALLING);
}
void dischargeInterrupt() {
endTime = micros();
detachInterrupt(digitalPinToInterrupt(capPos));
After that the original code continues.
Te problem I have is how to take the required 100 samples. When setting the interrupt after the startTime is taken, this routine will finish and do the next of the 100 iterations. Instead it should wait: for the interrupt to come, then for the rest of the routine to finish, as per original sketch. Being rather new to interrupts, I have no idea where to start with that part.
So what has to be done:
- loop() calls getEC()
getEC() takes 100 samples:
charge the cap, set the pins for discharge, set interrupt to measure discharge time.
interrupt comes, time passed is measured. Negative cap cycle is performed and one sampling round complete.
The main purpose of this change is to make the timing more accurate: react instantly on pin dropping to LOW and use a much higher resolution for time. The current microsecond resolution does the job but it's a serious limitation.
Here my complete, working, sketch:
// capacitor based TDS measurement
// pin D5 C+ - 330 ohm resistor----------|------------|
// | |
// cap EC probe or
// | resistor (for simulation)
// pin D6 C- ----------------------------| |
// |
// pin A0 EC -----------------------------------------|
#include <Average.h>
int capPos = D5; //C+
int capNeg = D6; //C-
int EC = D7; //EC
float CAP = 47; // capacity in nF
#define calibration 150 // a calibration factor to link time with EC.
void setup() {
Serial.begin(9600);
}
void loop () {
float EC = getEC(); // get the EC as mS/cm.
Serial.println (", EC: " + String(EC) + " mS/cm");
delay(100);
}
float getEC() {
int samples = 100; // number of EC samples to take and average.
unsigned long startTime; // the time stamp (in microseconds) the measurement starts.
unsigned long endTime; // the time stamp (in microseconds) the measurement is finished.
unsigned int dischargeTime; // the time it took for the capacitor to discharge.
Average<unsigned int> discharge(samples); // Take measurements on both the positive and negative cycles.
unsigned int chargeDelay = 500; // The time (in microseconds) given to the cap to fully charge/discharge - about 10x RC is a good value.
int startLevel; // analog level of the pin.
int endLevel;
pinMode(A0, INPUT);
for(int i=0; i<samples; i++) { // take <samples> measurements of the EC.
// Stage 1: fully charge capacitor for positive cycle.
// C+ high, C- low, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, HIGH);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, LOW);
delayMicroseconds(chargeDelay);
// Stage 2: positive side discharge; measure time it takes.
// C+ disconnected, C- low, EC low.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, LOW);
// Measure time until capPos goes LOW. Can't use pulseIn() here as the pin will be high already.
startTime = micros();
while (digitalRead(capPos) == HIGH) {
delayMicroseconds (1);
}
endTime = micros();
// handle potential overflow of micros() just as we measure, this happens every 70 minutes.
if (endTime < startTime) dischargeTime = 4294967295 - startTime + endTime;
else dischargeTime = endTime - startTime;
discharge.push(dischargeTime);
// Stage 3: fully charge capacitor for negative cycle. C+ low, C- high, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, LOW);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, HIGH);
delayMicroseconds(chargeDelay);
// Stage 4: negative side charge; don't measure as we just want to balance it the directions.
// C+ disconnected, C- low, EC low.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, HIGH);
delayMicroseconds(dischargeTime);
}
float dischargeAverage = discharge.mean();
Serial.print("Discharge time: ");
Serial.print(dischargeAverage);
// Calculate EC from the discharge time.
return dischargeAverage;
}
So, got this answered myself.
For the time resolution: you can get a much more exact time by using ESP.getCycleCount() which counts processor cycles - on my 80 MHz NodeMCU board that's 12.5 ns per cycle or 80 cycles per microsecond. I should have mentioned that in the first part.
Interrupts: this is something I misunderstood. Now I solved it by having the main function wait in a loop until a timeout is reached (set to 1 millisecond, normal expected times are in the 1-100 microseconds range), or until a global variable is set by the interrupt function. So now I'm measuring in the 12.5 nanosecond resolution!
One thing that's missing from this sketch is a correction for program time taken to deal with the timing: the time it takes from dropping the value on the EC pin to starting to count, and the time it takes from receiving the interrupt to stopping the count. If that overhead is say 100 cycles, that would be 1.25 microseconds, which is well within my measurement time.
// capacitor based TDS measurement
// pin D5 C+ - 330 ohm resistor----------|------------|
// | |
// cap EC probe or
// | resistor (for simulation)
// pin D6 C- ----------------------------| |
// |
// pin A0 EC -----------------------------------------|
#include <Average.h>
int capPos = D5; //C+
int capNeg = D6; //C-
int EC = D7; //EC
unsigned long startCycle;
unsigned long endCycle;
#define CYCLETIME 12.5 // the time it takes in nanoseconds to complete one CPU cycle (12.5 ns on a 80 MHz processor)
float CAP = 47; // capacity in nF
#define calibration 150 // a calibration factor to link time with EC.
void setup() {
Serial.begin(9600);
}
void loop () {
float EC = getEC(); // get the EC as mS/cm.
Serial.println (", EC: " + String(EC) + " mS/cm");
delay(500);
}
float getEC() {
int samples = 100; // number of EC samples to take and average.
unsigned long startTime; // the time stamp (in microseconds) the measurement starts.
unsigned long endTime; // the time stamp (in microseconds) the measurement is finished.
unsigned int dischargeTime; // the time it took for the capacitor to discharge.
Average<unsigned int> discharge(samples); // The sampling results.
unsigned int chargeDelay = 500; // The time (in microseconds) given to the cap to fully charge/discharge - about 10x RC is a good value.
unsigned int timeout = 1; // discharge timeout in milliseconds - if not triggered within this time, the EC probe is probably not there.
int startLevel; // analog level of the pin.
int endLevel;
pinMode(A0, INPUT);
for(int i=0; i<samples; i++) { // take <samples> measurements of the EC.
// Stage 1: fully charge capacitor for positive cycle.
// C+ high, C- low, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, HIGH);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, LOW);
delayMicroseconds(chargeDelay);
// Stage 2: positive side discharge; measure time it takes.
// C+ disconnected, C- low, EC low.
startCycle = ESP.getCycleCount();
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, LOW);
// Use cycle counts and an interrupt to get a much more precise time measurement, especially for high-EC situations.
endCycle = 0;
startTime = millis();
attachInterrupt(digitalPinToInterrupt(capPos), capDischarged, FALLING);
while (endCycle == 0) {
if (millis() > (startTime + timeout)) break;
}
detachInterrupt(digitalPinToInterrupt(capPos));
if (endCycle == 0) dischargeTime = 0;
else {
// Handle potential overflow of micros() just as we measure, this happens about every 54 seconds
// on a 80-MHz board.
if (endCycle < startCycle) dischargeTime = (4294967295 - startCycle + endCycle) * CYCLETIME;
else dischargeTime = (endCycle - startCycle) * CYCLETIME;
discharge.push(dischargeTime);
}
// Stage 3: fully charge capacitor for negative cycle. C+ low, C- high, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, LOW);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, HIGH);
delayMicroseconds(chargeDelay);
// Stage 4: negative side charge; don't measure as we just want to balance it the directions.
// C+ disconnected, C- high, EC high.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, HIGH);
delayMicroseconds(dischargeTime/1000);
}
float dischargeAverage = discharge.mean();
Serial.print("Discharge time: ");
Serial.print(dischargeAverage);
// Calculate EC from the discharge time.
return dischargeAverage;
}
// Upon interrupt: register the cycle count of when the cap has discharged.
void capDischarged() {
endCycle = ESP.getCycleCount();
detachInterrupt(digitalPinToInterrupt(capPos));
}

Getting Distance in Inches and Cm from Ultrasonic Sensor in Arduino

I am tinkering with a simple Arduino sketch that detects distances using an ultrasonic sensor. From what I've understood, the trigger sends a ping. The echo listens for an echo that comes back to calculate the distance. This is measured in microseconds.
If that is correct, the question is, how can one determine inches and cm from that ping (that is given in microseconds)? Is this just basic math/physics, and is there just a basic formula for this?
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
This is the part that I'm having issues with. I want to divide ping time from microseconds to inches and then cm:
distance_in = duration ????;
distance_cm = duration ????;
Serial.print(distance_in);
Serial.print(" in, ");
Serial.print(distance_cm);
Serial.print(" cm");
Serial.println();
delay(1500);
}
Any help, with as much explanation as possible would be appreciated. I'm a newbie to Arduino (and not a heavy-lifter in math)
distance_cm = ( duration / 29 ) / 2;
distance_in = distance_cm * 0,393701;
1 m/s = 100/1000000 = 0.0001 cm/μs
343 m/s = 0.0001 * 343 = 0.0343 cm/μs
0.0343 cm/μs = 1 / 0.0343 = 29.155 μs/cm
Sound travels at 343 meters per second, which means it needs 29.155 microseconds per centimeter. So, we have to divide the duration by 29 and then by 2, because the sound has to travel the distance twice. It travels to the object and then back to the sensor.
1 cm = 0,393701 in
The best article I have found on this subject is actually at Arduino. https://www.arduino.cc/en/Tutorial/Ping
/* Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground
* SIG connection of the PING))) attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
// this constant won't change. It's the pin number
// of the sensor's output:
const int pingPin = 7;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}

How to start lighting up at 45 degree in aurduino flex sensor?

I want to make the led strips gradually lights up as the flex sensor bends. But I want the led strips start to light up when the flex sensor is 45 degree.
And I want the led strips to be off before 45 degree.
Here is my code which is in Arduino.
const int ledPin = 3; //pin 3 has PWM funtion
const int flexPin = A0; //pin A0 to read analog input
int degree; //save analog value
int sensor;
void setup(){
pinMode(ledPin, OUTPUT); //Set pin 3 as 'output'
Serial.begin(9600); //Begin serial communication
}
void loop(){
sensor = analogRead(flexPin); //Read and save analog value from potentiometer
degree = map(sensor, 460, 850, 45, 90);
Serial.print("analog input: ");
Serial.print(sensor,DEC);
Serial.print(" degrees: ");
Serial.println(degree,DEC);
Serial.print(" ---------------------------------- ");
analogWrite(ledPin, degree); //Send PWM value to led
delay(50); //Small delay
}
but this did not worked, so I tried this one:
const int ledPin = 3; //pin 3 has PWM funtion
const int flexPin = A0; //pin A0 to read analog input
int degree; //save analog value
int sensor;
void setup(){
pinMode(ledPin, OUTPUT); //Set pin 3 as 'output'
Serial.begin(9600); //Begin serial communication
}
void loop(){
sensor = analogRead(flexPin); //Read and save analog value from potentiometer
if(degree<45){
(sensor = 0);
}
degree = map(sensor, 460, 850, 0, 90);
Serial.print("analog input: ");
Serial.print(sensor,DEC);
Serial.print(" degrees: ");
Serial.println(degree,DEC);
Serial.print(" ---------------------------------- ");
analogWrite(ledPin, degree); //Send PWM value to led
delay(50); //Small delay
}
And this did not worked as well. They start lighting up from the 0 degree and gets more as it goes closer to 90 degree. But I want it to be off before 45 degree, start to light up at 45 degree and get more as it gets closer to 90 degree. I will be so thankful if you could help me. I am so exhausted trying and getting to no where.
One problem is that you are setting your sensor to zero when the map function is expecting a value in the range of 460 and 850. It may help to change your default sensor value when below 45 degrees to the lowest value in the expected range (460.)
You could also remove your if condition and shift it later in the program like so:
if (degree < 45) {
digitalWrite(ledPin, LOW);
}
else {
analogWrite(ledPin, degree);
}
It may also be worth noting that the analog read function uses in input between 0 to 255 to determine the duty cycle of the pin. With that said, you could create another variable and use it to map or otherwise change the degree value so it better utilizes this range. i.e:
int freq = map(degree, 0, 90, 0, 255);

arduino Ultrasound srf05 wrong value

My Arduino board is Arduino Due ATmega328p. My Ultrasound is srf05.
I measure the distance is 5cm but my serial show me "531".Serial Monitor show the int of distance which value is always be 531.Why?
Here are the codes.
#define ECHOPIN 2 // Pin to receive echo pulse
#define TRIGPIN 3 // Pin to send trigger pulse
void setup(){
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void loop(){
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW); // Send pin low again
int distance = pulseIn(ECHOPIN, HIGH); // Read in times pulse
distance = distance/58; // Calculate distance from time of pulse
Serial.println(distance);
delay(50); // Wait 50mS before next ranging
}
The srf05 times out if it doesn't receive the echo pulse. The width of the pulse is 30 ms.
30,000 / 58 is 517, which is close to 531. It looks like your device is not receiving an echo from the object. This makes your problem a hardware issue, and not a programming issue. (The code looks correct.)

Read Mutiple Channels of 9 Channel Transmitter Receiver

I have 9 channel RF RX/TX,i want to connect 3 motors to it.I am able to connect channel 1 with motor1 but unable to connect channel2 with motor2 simultaneously with ardunio.Pls take a look at code. cant able to rotate motors with different channels
int motor1Left = 7;// defines pin 5 as connected to the motor
int motor1Right= 9;// defines pin 6 as connected to the motor
int motor2Left = 22;// defines pin 7 as connected to the motor
int motor2Right = 26;// defines pin 8 as connected to the motor
int enable = 5;
int enable2 = 10;
int channel1 = 2; // defines the channels that are connected
int channel2 = 3;// to pins 9 and 10 of arduino respectively
int Channel1 ; // Used later to
int Channel2 ; // store values
void setup ()
{
pinMode (motor1Left, OUTPUT);// initialises the motor pins
pinMode (motor1Right, OUTPUT);
pinMode (motor2Left, OUTPUT);
pinMode (motor2Right, OUTPUT);// as outputs
pinMode (channel1, INPUT);// initialises the channels
pinMode (channel2, INPUT);// as inputs
//pinMode (enable, OUTPUT);
Serial.begin (9600); // Sets the baud rate to 9600 bps
}
void loop ()
{
Channel1 = (pulseIn (channel1, HIGH)); // Checks the value of channel1
Serial.println (Channel1); //Prints the channels value on the serial monitor
delay(1000);
Channel2 = (pulseIn (channel2, HIGH)); // Checks the value of channel1
Serial.println (Channel2); //Prints the channels value value on the serial monitor
delay(1000);
if (Channel1 > 1470 && Channel1 < 1500) /*If these conditions are true, do the following. These are the values that I got from my transmitter, which you may customize according to your transmitter values */
{
digitalWrite (motor1Left, LOW); // Sets both the
digitalWrite (motor1Right, LOW);// motors to low
analogWrite(enable, 100);
}
if (Channel1 < 1460) // Checks if Channel1 is lesser than 1300
{
digitalWrite (motor1Left, HIGH);// Turns the left
digitalWrite (motor1Right, LOW); // motor forward
analogWrite(enable, 100);
//delay(500);
//delay(500);
//digitalWrite(motor1Left, LOW);
//delay(1);
}
if (Channel1 > 1510) // Checks if Channel1 is greater than 1500
{
digitalWrite (motor1Left, LOW);// Turns the right
digitalWrite (motor1Right, HIGH);// motor forward
analogWrite(enable, 70);
//delay(500);
//digitalWrite (motor1Right, LOW);
// delay(50);
//digitalWrite (motor1Right, HIGH);
}
if (Channel2 > 1480 && Channel1 < 1500 ) // If these conditions are true, do the following
{
digitalWrite (motor2Left, LOW);// Sets both the
digitalWrite (motor2Right, LOW);// motors to low
analogWrite (enable2, 100);
}
if (Channel2 < 1300) // Checks if Channel2 is lesser than 1300
{
digitalWrite (motor2Left, LOW);// Turns the left
digitalWrite (motor2Right, HIGH);// motor backward
analogWrite (enable2, 100);
}
if (Channel2 > 1500) // Checks if Channel2 is greater than 1500
{
digitalWrite (motor2Left, HIGH);// Turns the right
digitalWrite (motor2Right, LOW);// motor backward
analogWrite (enable2, 100);
}
}
I see a couple of problems:
You mention 3 motors, but there appear to be only 2.
You print out th value read, but don't have any help to identify which one. Consider adding "Serial.print("Ch1 = ");" just before the first println to differentiate.
About line 72, you are have mixed Channel2 and Channel1.
In both channels, you have some dead zones for your readings. For example, for Channel 1, what will happen if Channel1 is 1465? Or 1460 or 1470? In all those cases none of your "if" statements will fire. In Channel2 the lower dead zone is much bigger, and the upper dead zone is still there (what if Channel2 is exactly 1500?).
Lastly, it still seems like your motor should have done something. Maybe it was because Channel 1 was less than 1500. But if it still doesn't work, check your wiring.
Also, a style note: You use channel1 to be the input pin to read. You use Channel1 to be the value read from that. These are extremely similar looking. If you had mistyped one, it would be almost impossible to spot. You should consider naming these in a way that makes it easier to spot a mistake, and more obvious. For example, channel1 could become pinCh1, and Channel1 could become inpCh1. Others might suggest even more descriptive names, possibly with the first letter indicating data type. e.g.,
int iChannel1_PinNumber;
int iChannel1_InputValue;

Resources