arduino car with ultra sonic sensors [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a problem with my code. I wired everything correctly, but the values that the sensors read are either wrong. Or the code I wrote is wrong. The car never stops when something is within 20cm of the front sensor. It rather just keeps driving. The RC car is hooked up to the arduino with 3 ultrasonic sensors. And the RC motors are driven by an H-bridge(not the shield). The commented code parts are the code for if the RC car had a servo. But this car had 2 RC motors.
Here is the code:
//Libraries.
//#include <Servo.h>
#include <NewPing.h>
//Variables.
/*const int pos = 103; //Servo midden 103*
const int StrLeft = 70; //Serv0 naar links.
const int StrRight = 133; //Servo naar rechts.*/
int Left = 5;
int Right = 4;
int Forwards = 3;
int Backwards = 2;
int potPin = A0;
int speed = 0;
#define TRIGGER_PIN1 11 //Front
#define ECHO_PIN1 12
#define TRIGGER_PIN2 7 //Left
#define ECHO_PIN2 8
#define TRIGGER_PIN3 9 //Right
#define ECHO_PIN3 10
#define MAX_DISTANCE 200
#define MAX_DISTANCEF 1000
//Name of the objects.
//Servo MyServo;
NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCEF);//Front
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);//Left
NewPing sonar3(TRIGGER_PIN3, ECHO_PIN3, MAX_DISTANCE);//Right
//Start of the program.
void setup() {
Serial.begin(9600);
int Fwd = false;
/*MyServo.attach(9); //Pin number of the attached Servo.
MyServo.write(pos); //Resets to this posistion automatically.*/
pinMode(Left, OUTPUT);
pinMode(Right, OUTPUT);
pinMode(Forwards, OUTPUT);
pinMode(Backwards, OUTPUT);
}
//During the program.
void loop() {
//Sturen
/*MyServo.write(pos);
delay(1000);
MyServo.write(StrLeft);
Serial.print("Links");
delay(1000);
MyServo.write(StrRight);
Serial.print("Rechts");
delay(1000);
MyServo.write(pos);
delay(1000);*/
//Value of the potentiometer
speed = analogRead(potPin);
speed = map(speed, 0, 1023, 0, 179);
Serial.print(speed);
//Sensor
unsigned int distanceF = sonar1.ping_cm();//Front
unsigned int distanceL = sonar2.ping_cm();//Left
unsigned int distanceR = sonar2.ping_cm();//Right
Serial.print(distanceF);
Serial.print(distanceL);
Serial.print(distanceR);
Serial.print("cm");
delay(50);
//Values for driving
if (distanceF > 50 ) {
int Fwd = true;
Serial.print("true");
} else {
int Fwd = false;
Serial.print("false");
Stp();
}
delay(50);
if ((distanceF = true) && (distanceL > distanceR)) {
fwdLeft();
} else if ((distanceF = true) && (distanceR > distanceL)){
fwdRight();
}
delay(50);
}
void fwdLeft() {
digitalWrite(Forwards, HIGH);
digitalWrite(Backwards, LOW);
digitalWrite(Left, HIGH);
digitalWrite(Right, LOW);
}
void fwdRight() {
digitalWrite(Forwards, HIGH);
digitalWrite(Backwards, LOW);
digitalWrite(Left, LOW);
digitalWrite(Right, HIGH);
}
void Stp() {
digitalWrite(Forwards, LOW);
digitalWrite(Backwards, LOW);
digitalWrite(Left, LOW);
digitalWrite(Right, LOW);
}

In the comments, you said that that Fwd variable never changes. Note that you have three different variables name Fwd, though it seems you probably intended to have one global one.
The first is in setup:
void setup() {
Serial.begin(9600);
int Fwd = false;
// ...
}
This Fwd is local to setup. It's set but never read. Once setup is finished, it no longer exists.
The other two are here:
if (distanceF > 50 ) {
int Fwd = true;
Serial.print("true");
} else {
int Fwd = false;
Serial.print("false");
Stp();
}
Each of those is a new variable that's local to the scope in which it's defined (from the definition until the closing curly brace). Again, these are set but never inspected.
I think what you intended is to declare a global variable outside of any function:
int Fwd = false;
Then, whenever you want to change it, you'd just assign to it without repeating the type:
Fwd = true;
Then you have lines like this:
if ((distanceF = true) && (distanceL > distanceR))
I'm not sure what you intended by (distanceF = true), but I don't think that code does what you think it does. Since you used a single =, that's an assignment not a comparison. So your if-condition is actually changing the value of distanceF to true rather than checking to see if it is true (or non-zero). I suspect you wanted Fwd there:
if (Fwd && (distanceL > distanceR))
None of that explains why the car doesn't actually stop though. I suspect you also have a problem reading the data from the ultrasonic sensor. Perhaps the units aren't what is expressed in the code or you need to do some averaging (or other filtering) of the readings in order to reduce noise and faulty readings.

Here's code, you just need to adjust code for yourself, but logic Works, at least car will stop if is something in front. Also watch how you write your code. In if statment instead of == you have =
Also give proper names for variables and functions.
if (distanceF < 50)
{
// Code that will stop the car
}
else
{
// Code that will drive car forward
}
if (Fwd)
{
if (distanceL > distanceR)
{
// Code that will drive car left
}
else
{
// Code that will drive car right
}
}

Related

ATTiny85 Interrupts in Arduino IDE

I have an ATTiny85 which I program using a sparkfun programmer (https://www.sparkfun.com/products/11801) and the ATTiny Board Manager I am using is: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json
Below is my code, I am having trouble getting the interrupt to work when I ground Pin 2.
I have tested the LED does work outside of the interrupt (inside the loop). Any suggestions are welcome.
#include "Arduino.h"
#define interruptPin 2
const int led = 3;
bool lastState = 0;
void setup() {
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(interruptPin, pulseIsr, CHANGE);
pinMode(led, OUTPUT);
}
void loop() {
}
void pulseIsr() {
if (!lastState) {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
lastState = 1;
}
else {
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
lastState = 0;
}
}
I was way off.
Here is how to set up an interrupt on the ATTiny85 using the Arduino IDE (this example uses digital pin 4 (pin 3 on the chip):
#include "Arduino.h"
const byte interruptPin = 4;
const byte led = 3;
bool lastState = false;
ISR (PCINT0_vect) // this is the Interrupt Service Routine
{
if (!lastState) {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
lastState = true;
}
else {
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
lastState = false;
}
}
void setup() {
pinMode(interruptPin, INPUT_PULLUP); // set to input with an internal pullup resistor (HIGH when switch is open)
pinMode(led, OUTPUT);
// interrupts
PCMSK |= bit (PCINT4); // want pin D4 / pin 3
GIFR |= bit (PCIF); // clear any outstanding interrupts
GIMSK |= bit (PCIE); // enable pin change interrupts
}
void loop() {
}
I see one possible error with your Boolean data type. Boolean data types are either true or false. I see that your using it for variable lastState. The initialization to equal 0 is something that I don't think the compiler allows. Maybe you should try setting the bool variable to the following...
bool lastState = true;
if (!lastState) {
// what you want your code to perform if lastState is FALSE
}
else {
//what else you want your code to perform if lastState is TRUE
}
OR
bool lastState = true;
if (lastState) {
// what you want your code to perform if lastState is TRUE
}
else {
//what else you want your code to perform if lastState is FALSE
}
Here is a helpful pdf on Boolean data types, available for download through my Nextcloud instance.
https://nextcloud.point2this.com/index.php/s/so3C7CzzoX3nkzQ
I know this doesn't fully fix your problem, but hopefully this will help some.

Entering multiple SPI interfaces

I am having a problem with my code for arduino m0 (using microchip SAMD21). There are two SPI interfaces, first classic and second with int variable in front of the pin name, int MISO, for instance. Does someone know, how to control this classic SPI interface?
I have also attached my code.
PS: Code stucks in begin function of OZONE2CLICK sensor...
#include "Arduino.h"
#include <MQ131.h>
// include RFM69 library
#include <SPI.h>
// Local
#define PC_BAUDRATE 56700
#define MS_DELAY 0 // Number of milliseconds between data sending and LED signalization
#define LED_DELAY 100
#define Serial SerialUSB
// SD card
#define sd_cs_pin 35 // set SD's chip select pin (according to the circuit)
float PPMO2;
float PPBO2;
float MGM3O2;
float UGM3O2;
const byte pinSS = 2; //cs pin
const byte pinRDY = 12;
const byte pinSCK = 13;
const byte O2Pin = 10;
#define DcPin 8
// SD card file
File file; // SD library variable
// LEDS
#define D13_led_pin 42 // D13 LED
#define M_led_pin 36 // MLED
// Local variables
int idCounter = 1;
bool isBmeOk = true;
bool isSdOk = true;
bool isRadioOk = true;
bool isGpsConnected = true;
void OZONE2CLICKCalibrate ()
{
Serial.println("2");
//MQ131.begin(pinSS, pinRDY, O2Pin, LOW_CONCENTRATION, 10000); //(int _pinCS, int _pinRDY, int _pinPower, MQ131Model _model, int _RL)
Serial.println("99");
Serial.println("Calibration in progress...");
MQ131.calibrate();
Serial.println("Calibration done!");
Serial.print("R0 = ");
Serial.print(MQ131.getR0());
Serial.println(" Ohms");
Serial.print("Time to heat = ");
Serial.print(MQ131.getTimeToRead());
Serial.println(" s");
}
void OZONE2CLICKMeasure ()
{
Serial.println("Sampling...");
MQ131.sample();
Serial.print("Concentration O3 : ");
PPMO2 = MQ131.getO3(PPM);
Serial.print(PPMO2);
Serial.println(" ppm");
Serial.print("Concentration O3 : ");
PPBO2 = MQ131.getO3(PPB);
Serial.print(PPBO2);
Serial.println(" ppb");
Serial.print("Concentration O3 : ");
MGM3O2 = MQ131.getO3(MG_M3);
Serial.print(MGM3O2);
Serial.println(" mg/m3");
Serial.print("Concentration O3 : ");
UGM3O2 = MQ131.getO3(UG_M3);
Serial.print(UGM3O2);
Serial.println(" ug/m3");
}
void setup()
{
Serial.begin(PC_BAUDRATE);
// wait for the Arduino serial (on your PC) to connect
// please, open the Arduino serial console (right top corner)
// note that the port may change after uploading the sketch
// COMMENT OUT FOR USAGE WITHOUT A PC!
// while(!Serial);
Serial.println("openCanSat PRO");
Serial.print("Node ");
Serial.print(MYNODEID,DEC);
Serial.println(" ready");
// begin communication with the BME280 on the previously specified address
// print an error to the serial in case the sensor is not found
if (!bme.begin(BME280_ADDRESS_OPEN_CANSAT))
{
isBmeOk = false;
Serial.println("Could not find a valid BME280 sensor, check wiring!");
return;
}
// begin communication with the INA219
ina219.begin();
// check of Gps is connected
Wire.beginTransmission(0x42); // 42 is addres of GPS
int error = Wire.endTransmission();
if (error != 0)
{
isGpsConnected = false;
}
// begin communication with gps
gps.begin();
// Uncomment when you want to see debug prints from GPS library
// gps.debugPrintOn(57600);
if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID))
{
isRadioOk = false;
Serial.println("RFM69HW initialization failed!");
}
else
{
radio.setFrequency(FREQUENCYSPECIFIC);
radio.setHighPower(true); // Always use this for RFM69HW
}
pinMode(D13_led_pin, OUTPUT);
}
void loop()
{
pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);
pinMode(DcPin, OUTPUT);
pinMode(O2Pin, OUTPUT);
digitalWrite(DcPin, HIGH);
digitalWrite(O2Pin, HIGH);
delay(10000);
OZONE2CLICKCalibrate();
OZONE2CLICKMeasure();
}
It looks the code opening the SPI connection is commented out:
MQ131.begin(pinSS, pinRDY, O2Pin, LOW_CONCENTRATION, 10000);
You need to configure the SPI connection to get any data from your device.
Refer to reference code from the manufacturer or library you're using to make sure your programming against it correctly.
Please format your code with predictable spacing. This is pretty hard to read.
Since you're using C++, prefer to use:
constexpr <type> NAME = <value>;
rather than macros:
#define NAME (<value>)
Since this is a bare metal compilation, using return in the setup() or loop() functions does not stop them. You probably want something more like while (true) {}. This will loop the code indefinitely, rather than proceed in a bad state.
i.e.:
void stop_forever() {
Serial.println("fatal error detected, stoping forever.");
while (true) {}
}
// then, use it later:
// ...
if (error) {
stop_forever();
}
// ...

Arduino How can i store the last IR code to check if it needs repeating?

I'm just learning Arduino and i've got a DC Motor & IR Receiver connected. It's working fine if i press the button once but i can't figure out how to keep the motor spinning if i hold the button down as the REPEAT command is the same numbers.
I figured i would store the last code sent and check if the repeat command and last code match but it doesn't seem to be working and can't figure out why.
#include <IRremote.h>
int IRpin = 11; // pin for the IR sensor
IRrecv irrecv(IRpin);
decode_results results;
int lastCode;
void setup() {
// put your setup code here, to run once:
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Enable IR Receiver.
}
void loop() {
// put your main code here, to run repeatedly:
if
(irrecv.decode(&results)) {
Serial.println(results.value);
irrecv.resume();
Serial.println("Last Code is set to: ");
Serial.write(lastCode);
if(results.value== 16748655 || (results.value== 4294967295 && lastCode== 16748655)) // Your ON button value
{
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
analogWrite(9, 255);
delay(1000);
analogWrite(9, 0);
lastCode= 16748655;
}
else if(results.value == 16769055 || (results.value== 4294967295 && lastCode== 16769055)) // Your OFF button value
{
digitalWrite(8, LOW);
digitalWrite(7, HIGH);
analogWrite(9, 255);
delay(1000);
analogWrite(9, 0);
lastCode= 16769055;
}
}
}
A more reliable approach to running the motor until the button is released is to use a "no-code" timeout. That is, if the "no code" state persists for a period longer than the auto-repeat period, then it has been released.
It is not clear in your code what the 1 second analogue pulse is for, but placing long delays in your loop() function makes your system far less responsive. Better to poll the system tick and "do stuff" when it is time to do so. Also magic numbers should be avoided if you want anyone to understand your code and avoid errors in maintenance.
The following uses system tick polling to implement the "no-code" timeout. I have omitted the motor on/off code because it is not clear what you are doing there with the 1 second delays.
#define NO_CODE 0xFFFFFFFFul
#define MOTOR_ON_CODE 0xFF906Ful
#define MOTOR_OFF_CODE 0xFFE01Ful
#define STOP_TIME_MS 250ul // stop after button release for 250ms
void loop( )
{
static unsigned long last_on_time = 0 ;
if( irrecv.decode( &results ) )
{
irrecv.resume() ;
unsigned long code = results.value ;
// If motor off code or no code timeout...
if( code == MOTOR_OFF_CODE ||
(code == NO_CODE && millis() - last_on_time > STOP_TIME_MS) )
{
// Motor off
...
}
else if( code == MOTOR_ON_CODE )
{
// Continuously update last on time while button is held
last_on_time = millis() ;
// Motor on
...
}
}
}
I have included response to the motor-off code, but that may not be necessary, since the motor will be switched off 250ms (or whatever time you choose) after the ON button is released in any case. You might instead have a forward/reverse button and release either to stop:
#define NO_CODE 0xFFFFFFFFul
#define MOTOR_FWD_CODE 0xFF906Ful
#define MOTOR_REV_CODE 0xFFE01Ful
#define STOP_TIME_MS 250ul // stop after button release for 250ms
void loop( )
{
static unsigned long last_on_time = 0 ;
if( irrecv.decode( &results ) )
{
irrecv.resume() ;
unsigned long code = results.value ;
switch( code )
{
case NO_CODE :
{
if( millis() - last_on_time > STOP_TIME_MS )
{
// Motor off
...
}
}
break ;
case MOTOR_FWD_CODE :
{
// Continuously update last on time while button is held
last_on_time = millis() ;
// Motor forward
...
}
break ;
case MOTOR_FWD_CODE :
{
// Continuously update last on time while button is held
last_on_time = millis() ;
// Motor reverse
...
}
break ;
}
}
}

Arduino project:automatic room light controller

I am Working on an Arduino mini project. its to design an automatic room light controller using IR modules and arduino UNO R3. Before coming to my question i'd explain it a bit .Its like an arduino is connected to an IR module and a counter keeps count of people entering the room, when the room is empty light turns off automatically.But my Code isnt working the way im expecting it to work. . given below is the code for my mini project.
#define x 14 // x sensor 1
#define y 19 // y sensor 2
#define relay 2 // relay for output
int count = 0; // initialisation
// void IN() //{ count ++;} // void OUT() // { cout--; // }
void setup()
{
// put your setup code here, to run once:
pinMode(x, INPUT);
pinMode(y, INPUT);
pinMode(relay, OUTPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
if(digitalRead(x)) //IN();
{
count++;
}
if (digitalRead(y)) // OUT();
{
count--;
}
if (count <= 0) {
digitalWrite(relay, LOW);
delay(20);
}
else
digitalWrite(relay, HIGH);
}
The problem with my code is that the transmitter and receiver sense interference both at the same time resulting in turning of the light while the person is still inside the room.As im new to arduino need your inputs.

Arduino Class Redefinition Error

In my Arduino IDE I have set up a program that runs eight LEDs through a shift register and now am trying to make a class to control the shift register. So far I have created the file and created a constructor with a few functions for the class, but when I try to verify the code the IDE says that I am redefining the class shiftreg here is the error message:
In file included from Lab9_step3.cpp:97:
shiftreg.h:2: error: redefinition of 'class shiftreg'
shiftreg.h:3: error: previous definition of 'class shiftreg'
and my code for lab_9 is:
/* ---------------------------------------------------------
* | Arduino Experimentation Kit Example Code |
* | CIRC-05 .: 8 More LEDs :. (74HC595 Shift Register) |
* ---------------------------------------------------------
*
* We have already controlled 8 LEDs however this does it in a slightly
* different manner. Rather than using 8 pins we will use just three
* and an additional chip.
*
*
*/
#include "shiftreg.h"
//Pin Definitions
//Pin Definitions
//The 74HC595 uses a serial communication
//link which has three pins
shiftreg a(2, 3, 4);
int sensorPin = 0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
/*
* setup() - this function runs once when you turn your Arduino on
* We set the three control pins to outputs
*/
void setup()
{
a.pinmode();
}
/*
* loop() - this function will start after setup finishes and then repeat
* we set which LEDs we want on then call a routine which sends the states to the 74HC595
*/
void loop() // run over and over again
{
for(int i = 0; i < 256; i++){
a.update(i);
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
delay(sensorValue);
}
}
/******************************
/*
* updateLEDsLong() - sends the LED states set in ledStates to the 74HC595
* sequence. Same as updateLEDs except the shifting out is done in software
* so you can see what is happening.
*/
// void updateLEDsLong(int value){
// digitalWrite(latch, LOW); //Pulls the chips latch low
// for(int i = 0; i < 8; i++){ //Will repeat 8 times (once for each bit)
// int bit = value & B10000000; //We use a "bitmask" to select only the eighth
// //bit in our number (the one we are addressing this time thro
// //ugh
// value = value << 1; //we move our number up one bit value so next time bit 7 will
// // be
// //bit 8 and we will do our math on it
// if(bit == 128){digitalWrite(data, HIGH);} //if bit 8 is set then set our data pin high
// else{digitalWrite(data, LOW);} //if bit 8 is unset then set the data pin low
// digitalWrite(clock, HIGH); //the next three lines pulse the clock pin
// delay(1);
// digitalWrite(clock, LOW);
// }
// digitalWrite(latch, HIGH); //pulls the latch high shifting our data into being displayed
// }
//
//
// //These are used in the bitwise math that we use to change individual LEDs
// //For more details http://en.wikipedia.org/wiki/Bitwise_operation
// int bits[] = {B00000001, B00000010, B00000100, B00001000, B00010000, B00100000, B01000000, B10000000};
// int masks[] = {B11111110, B11111101, B11111011, B11110111, B11101111, B11011111, B10111111, B01111111};
// /*
// * changeLED(int led, int state) - changes an individual LED
// * LEDs are 0 to 7 and state is either 0 - OFF or 1 - ON
// */
// void changeLED(int led, int state){
// ledState = ledState & masks[led]; //clears ledState of the bit we are addressing
// if(state == ON){ledState = ledState | bits[led];} //if the bit is on we will add it to le
// //dState
// updateLEDs(ledState); //send the new LED state to the shift register
// }
// **********************************/
and my code for shiftreg.h is:
/*Shift Register
*/ (Error occurs here)
class shiftreg (and here)
{
private:
//Pin Definitions
//Pin Definitions
//The 74HC595 uses a serial communication
//link which has three pins
int data;
int clock;
int latch;
public:
shiftreg (int _data, int _clock, int _latch);
void update(int value);
void pinmode();
};
and my code for shiftreg.cpp is:
#include "shiftreg.h"
/*shiftreg constructor:
*/
shiftreg::shiftreg (int _data, int _clock, int _latch)
{
data = _data;
clock = _clock;
latch = _latch;
//Used for single LED manipulation
int ledState = 0;
const int ON = HIGH;
const int OFF = LOW;
}
/*
* updateLEDs() - sends the LED states set in ledStates to the 74HC595
* sequence
*/
void shiftreg::update(int value)
{
digitalWrite(latch, LOW); //Pulls the chips latch low
shiftOut(data, clock, MSBFIRST, value); //Shifts out the 8 bits to the shift register
digitalWrite(latch, HIGH); //Pulls the latch high displaying the data
}
/*
*/
void shiftreg::pinmode()
{
pinMode(data, OUTPUT);
pinMode(clock, OUTPUT);
pinMode(latch, OUTPUT);
}
Thanks for the help!
According to the error message you're including shiftreg.h on line 97 of Lab9_step3.cpp. What's on the 96 lines above that? The error probably lies somewhere in there.
If I had to guess, I'd say you're, either directly, or indirectly, including shiftreg.h twice (or more) in Lab9_step3.cpp, and the error's occurring because you don't have include guards in your header file.
Try adding the following to shiftreg.h
#ifndef SHIFTREG_H
#define SHIFTREG_H
class shiftreg
{
// ...
};
#endif