Need help with the coding


#1

I am building a smart trash bin, and it has an lcd screen 16x2 and ultrasonic sensor and a 9g servo motor, but the problem is the code is not how I want it to be, so can anybody help me with it?


#2

Sure thing Batman - post a link to the project so that we can see the components you’re using, and then explain what you want the code to do.


#3

here is the link to my project: https://www.circuito.io/static/reply/index.html?solutionId=5bb964e42b7189007f5f19f8&solutionPath=storage.circuito.io

So I want the ultrasonic sensor to sense an object then it activates the servo motor then after I move that object away. the servo motor should return backwards. And I want the lcd screen to say thank you after 2 sec, after the servo motor turn backward. thank you


#4

Thanks Batman, I hope to get onto that later today. It’s 6:30am now and I’m grape picking this morning, only back home this afternoon.

Sounds like a fun project and the code should be simple enough and a great opportunity for us to share it with others in a way that can teach other beginners as well. :+1:


#5

Thank you bhomfmann for helping me.


#6

Hello bhomfmann.
Any updates for today?


#7

I’m sorry, the sun was shining and it was a beautiful day here so I went canoeing instead. I’m working today but I might be able to spare some time for it later. In the mean time, I looked at the circuit and thought of some things you could do (if you’ve built it and it’s working):

  1. get readings from the distance sensor when something is the expected distance and when there’s nothing at that distance.
  2. play with the servo values to see if the positions are suitable for your purpose.

I’ll update you later. Meanwhile, here.are some photos from my canoe trip for you to enjoy:



#8

I’ve got about an hour before I have to start work so here’s a start.

You should edit the numbers (20 and 150) on these lines to values that make the servo move to the correct angle for your project.

// Global variables and defines
const int servo9gRestPosition   = 20;  //Starting position
const int servo9gTargetPosition = 150; //Position when event is detected

I’d suggest leaving the test code as it is for now in case you want to verify individual components are correctly wired and set up.

You’ll need the same sort of lines of code as the above for the sensor. The following line of code reads the distance measurement from the sensor:

int hcsr04Dist = hcsr04.ping_cm();

So you’ll need to read this in your loop and then check if the distance is shorter than the maximum distance you want the person to be to trigger the servo. So start with a definition of what that distance is (I’ve assumed 20cm for this and I like to include the unit (cm) in my variables for clarity):

const int triggerDistanceCm = 20;  // The distance from the censor to trigger the servo

After the call to get the distance, you need to see if it’s less than the trigger distance and then do the expected work:

int hcsr04Dist = hcsr04.ping_cm();
if (hcsr04Dist <= triggerDistanceCm)
{
    // Move the servo, print the message
}

In the block after the “if” statement you can copy code from the test code to move the motor and print what you want:

if (hcsr04Dist <= triggerDistanceCm)
{
    // Move the servo, print the message
    servo9g.attach(SERVO9G_PIN_SIG);         // 1. attach the servo to correct pin to control it.
    servo9g.write(servo9gTargetPosition);  // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
    delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
    servo9g.write(servo9gRestPosition);    // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
    delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
    servo9g.detach();                    // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.

    // Now show the message
    lcd.setCursor(0, 0);
    lcd.print("Thank you");

    // Turn off the display:
    lcd.noDisplay();
    delay(500);
    // Turn on the display:
    lcd.display();
    delay(500);
}

I don’t think this would be the behaviour you’d want due to all the delays, so I’d suggest changing the order of the calls to minimize delays.

if (hcsr04Dist <= triggerDistanceCm)
{
    // Start printing at the first character on the first row
    lcd.setCursor(0, 0);
    lcd.print("Thank you");
    // Turn on the display to show the message
	lcd.display();

    // Move the servo
    servo9g.attach(SERVO9G_PIN_SIG);         // 1. attach the servo to correct pin to control it.
    servo9g.write(servo9gTargetPosition);    // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
    delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
    servo9g.write(servo9gRestPosition);      // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
    delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
    servo9g.detach();                        // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.

    // Turn off the display:
    lcd.noDisplay();
}

The change above is to start with the message, then move the motor (you’ll probably want to change the delays from 500 milliseconds to something a little longer or shorter depending on your project.

You might also want to add a delay in before you turn off the display if the motor moving times are very short - you need to give the person a chance to see and read the message.

Putting it all together, you get the following program:

// Include Libraries
#include "Arduino.h"
#include "NewPing.h"
#include "LiquidCrystal.h"
#include "Servo.h"

// Pin Definitions
#define HCSR04_PIN_TRIG	3
#define HCSR04_PIN_ECHO	2
#define LCD_PIN_RS	9
#define LCD_PIN_E	8
#define LCD_PIN_DB4	4
#define LCD_PIN_DB5	5
#define LCD_PIN_DB6	6
#define LCD_PIN_DB7	7
#define SERVO9G_PIN_SIG	10

// Global variables and defines
const int servo9gRestPosition   = 20;  //Starting position
const int servo9gTargetPosition = 150; //Position when event is detected
const int triggerDistanceCm     = 20;  //The distance from the censor to trigger the servo

// object initialization
Servo servo9g;
NewPing hcsr04(HCSR04_PIN_TRIG,HCSR04_PIN_ECHO);
LiquidCrystal lcd(LCD_PIN_RS,LCD_PIN_E,LCD_PIN_DB4,LCD_PIN_DB5,LCD_PIN_DB6,LCD_PIN_DB7);

// define vars for testing menu
const int timeout = 10000;       //define timeout of 10 sec
char menuOption = 0;
long time0;

// Setup the essentials for your circuit to work. It runs first every time your circuit is powered with electricity.
void setup() 
{
	// Setup Serial which is useful for debugging
	// Use the Serial Monitor to view printed messages
	Serial.begin(9600);
	while (!Serial) ; // wait for serial port to connect. Needed for native USB
	Serial.println("start");
	
	// set up the LCD's number of columns and rows
	 lcd.begin(16, 2);
	servo9g.attach(SERVO9G_PIN_SIG);
	servo9g.write(servo9gRestPosition);
	delay(100);
	servo9g.detach();

	// menuOption = menu(); // Disabled to make the program run without serial input
	
}

// Main logic of your circuit. It defines the interaction between the components you selected. After setup, it runs over and over again, in an eternal loop.
void loop() 
{
	int hcsr04Dist = hcsr04.ping_cm();
	if (hcsr04Dist <= triggerDistanceCm)
	{
		// Start printing at the first character on the first row
		lcd.setCursor(0, 0);
		lcd.print("Thank you");
		// Turn on the display to show the message
		lcd.display();

		// Move the servo
		servo9g.attach(SERVO9G_PIN_SIG);         // 1. attach the servo to correct pin to control it.
		servo9g.write(servo9gTargetPosition);    // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
		delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
		servo9g.write(servo9gRestPosition);      // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
		delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
		servo9g.detach();                        // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.

		// Turn off the display:
		lcd.noDisplay();
	}

	// Leave the code here in case we need it, but comment it out to let the program run
	/*
	if(menuOption == '1') {
		// Ultrasonic Sensor - HC-SR04 - Test Code
		// Read distance measurment from UltraSonic sensor           
		int hcsr04Dist = hcsr04.ping_cm();
		delay(10);
		Serial.print(F("Distance: ")); Serial.print(hcsr04Dist); Serial.println(F("[cm]"));
	}
	else if(menuOption == '2') {
		// LCD 16x2 - Test Code
		// Print a message to the LCD.
		lcd.setCursor(0, 0);
		lcd.print("Circuito Rocks !");
		// Turn off the display:
		lcd.noDisplay();
		delay(500);
		// Turn on the display:
		lcd.display();
		delay(500);
	}
	else if(menuOption == '3') {
		// 9g Micro Servo - Test Code
		// The servo will rotate to target position and back to resting position with an interval of 500 milliseconds (0.5 seconds) 
		servo9g.attach(SERVO9G_PIN_SIG);         // 1. attach the servo to correct pin to control it.
		servo9g.write(servo9gTargetPosition);  // 2. turns servo to target position. Modify target position by modifying the 'ServoTargetPosition' definition above.
		delay(500);                              // 3. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
		servo9g.write(servo9gRestPosition);    // 4. turns servo back to rest position. Modify initial position by modifying the 'ServoRestPosition' definition above.
		delay(500);                              // 5. waits 500 milliseconds (0.5 sec). change the value in the brackets (500) for a longer or shorter delay in milliseconds.
		servo9g.detach();                    // 6. release the servo to conserve power. When detached the servo will NOT hold it's position under stress.
	}

	if (millis() - time0 > timeout)
	{
		menuOption = menu();
	}
	*/
}

// Menu function for selecting the components to be tested
// Follow serial monitor for instrcutions
char menu()
{

	Serial.println(F("\nWhich component would you like to test?"));
	Serial.println(F("(1) Ultrasonic Sensor - HC-SR04"));
	Serial.println(F("(2) LCD 16x2"));
	Serial.println(F("(3) 9g Micro Servo"));
	Serial.println(F("(menu) send anything else or press on board reset button\n"));
	while (!Serial.available());

	// Read data from serial monitor if received
	while (Serial.available()) 
	{
		char c = Serial.read();
		if (isAlphaNumeric(c)) 
		{
			if(c == '1') 
				Serial.println(F("Now Testing Ultrasonic Sensor - HC-SR04"));
			else if(c == '2') 
				Serial.println(F("Now Testing LCD 16x2"));
			else if(c == '3') 
				Serial.println(F("Now Testing 9g Micro Servo"));
			else
			{
				Serial.println(F("illegal input!"));
				return 0;
			}
			time0 = millis();
			return c;
			}
		}
	}

/*******************************************************

*    Circuito.io is an automatic generator of schematics and code for off
*    the shelf hardware combinations.

*    Copyright (C) 2016 Roboplan Technologies Ltd.

*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.

*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.

*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*    In addition, and without limitation, to the disclaimers of warranties 
*    stated above and in the GNU General Public License version 3 (or any 
*    later version), Roboplan Technologies Ltd. ("Roboplan") offers this 
*    program subject to the following warranty disclaimers and by using 
*    this program you acknowledge and agree to the following:
*    THIS PROGRAM IS PROVIDED ON AN "AS IS" AND "AS AVAILABLE" BASIS, AND 
*    WITHOUT WARRANTIES OF ANY KIND EITHER EXPRESS OR IMPLIED.  ROBOPLAN 
*    HEREBY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT 
*    NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY, TITLE, FITNESS 
*    FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND THOSE ARISING BY 
*    STATUTE OR FROM A COURSE OF DEALING OR USAGE OF TRADE. 
*    YOUR RELIANCE ON, OR USE OF THIS PROGRAM IS AT YOUR SOLE RISK.
*    ROBOPLAN DOES NOT GUARANTEE THAT THE PROGRAM WILL BE FREE OF, OR NOT 
*    SUSCEPTIBLE TO, BUGS, SECURITY BREACHES, OR VIRUSES. ROBOPLAN DOES 
*    NOT WARRANT THAT YOUR USE OF THE PROGRAM, INCLUDING PURSUANT TO 
*    SCHEMATICS, INSTRUCTIONS OR RECOMMENDATIONS OF ROBOPLAN, WILL BE SAFE 
*    FOR PERSONAL USE OR FOR PRODUCTION OR COMMERCIAL USE, WILL NOT 
*    VIOLATE ANY THIRD PARTY RIGHTS, WILL PROVIDE THE INTENDED OR DESIRED
*    RESULTS, OR OPERATE AS YOU INTENDED OR AS MAY BE INDICATED BY ROBOPLAN. 
*    YOU HEREBY WAIVE, AGREE NOT TO ASSERT AGAINST, AND RELEASE ROBOPLAN, 
*    ITS LICENSORS AND AFFILIATES FROM, ANY CLAIMS IN CONNECTION WITH ANY OF 
*    THE ABOVE. 
********************************************************/

If you have any questions, please let me know.

Worth noting:

  1. This is not efficient code; it’ll read the sensor very often, far more frequently than necessary, but I’ve tried to keep optimisation out of this for the sake of clarity and simplicity.

Please let us know how you get on.


#9

Thank you sooooo much bhofmann, It’s working so well, thank you for your time man.


#11

hey man!

I’m having some issues with this code, and I don’t know how to fix it.

So here what it’s telling me"Arduino: 1.8.1 (Windows 10), Board: “Arduino/Genuino Uno”

The sketch name had to be modified. Sketch names can only consist
of ASCII characters and numbers (but cannot start with a number).
They should also be less than 64 characters long.

C:\Users\stum20922804\Documents\Arduino\The_project\The_project.ino:3:21: fatal error: NewPing.h: No such file or directory

#include “NewPing.h”

                 ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences."

So can you help me with it please?


#12

by the way, the code is the same code as before.


#13

Rename your file “The_project.ino” and remove the underscore. Maybe “TheProject.ino”.