Metal detector using Arduino Is anyone out there building serious metal detectors with the Arduino? By "serious" I mean metal detectors with phase sensitivity to discriminate between ferrous and non-ferrous metals, etc.  Seems like the Uno is a good platform for a smart metal detector project.

Update:
Arduino allows me to control phase discrimination which allows ferrous metals to be rejected.
I already know it can be done with an analog phase shift circuit.
Also Arduino can perform target ID function with readout to 16x2 LCD display.

A set of posts on Instructables uses an Arduino Nano to generate a Phase Induction pulse, with a capacitor instead of a dump resistor to set up a decaying oscillation, which is then limited with diodes and detected by the analog comparator with interrupts.  The comparator interrupts then count the frequency of the decaying ringing oscillation producing some ferrous/non-ferrous discrimination, and the duration of the ringing, producing some signal strength and size information.

Nano doing Pulse induction with LC-trap oscillation: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector-LC-Trap/
Nano meta detection software with high-frequency ADC sampling: https://www.instructables.com/id/How-to-Program-an-Arduino-Based-Metal-Detector/
Nano doing Pulse Induction, shifting the recovery pulse to match the arduino's analog comparator: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector/

The tricks in the Pulse Induction LC-trap system of using the analog comparator would be applicable to detecting phase shifts and detecting crossings in sync with a timer-based output.


Strobe Frequency Calculation, how its done? I'm using the Arduino sketch for LED stroboscope found here: http://mehax.blogspot.co.uk/2011/02/arduino-stroboscope.html.

Also below, I've inserted the loop part where this calculations are made:

void loop() {
// this while is a workaround for timer limitations using micros vs millis
sensorValue = analogRead(analogInPin);   //take potentiometer reading
hold = sensorValue*55 + 400;             //add some time to scale and for code execution
microsCurrent = micros();                // collect current time
if (microsCurrent > microsPrev + hold){  //set up timing loop
frequency = 1000000/(microsCurrent - microsPrev);
microsPrev = microsPrev + hold;            //set up millis for delay stuff

//set all 6 LEDs high (they were already plugged in)
digitalWrite(3,HIGH);
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
delayMicroseconds(.02*hold);  //leave LEDs on long enough to see

//set all LEDs low
digitalWrite(3,LOW);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);

if(millis() > millisSerial + 200){
  millisSerial=millis();    //reset timer
  holdFrequency = 1000000/hold;
  //do some math to find values
  rpm = frequency * 60;

I want to use this code in my project, but I don't really understand how this code calculates the stobing frequency.

So, I have following questions:

Why "hold" variable is calculated in the given way?
Why "microsCurrent", "microsPrev" and all other timings are executed?
How "frequency is calculated"?
What is "hold frequency" variable?

Sorry, I'm very new to Arduino and don't know much coding.
Will appreciate very much your help!

Why "hold" variable is calculated in the given way?

hold stores the intended delay between the strobe pulses, i.e. the
stroboscope period. It is computed as an affine function of the
potentiometer cursor position because... well, that's the simplest way
to make it user-adjustable. 400 µs is the shortest period that
(according to the program author) one may reasonably want to set.

  Why "microsCurrent", "microsPrev" and all other timings are executed?

See the Blink Without
Delay Arduino
tutorial.

  How "frequency is calculated"?

From the code:

frequency = 1000000/(microsCurrent - microsPrev);

The frequency is the inverse of the period. The period is the time
elapsed between this strobe and the previous one. The numerator is a
conversion factor to get the frequency in hertz from a period in
microseconds.

  What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period),
disregarding the timing jitter that makes the actual instantaneous
frequency slightly different.


How can I interrupt a delay() when a button is pressed? I have created a device that allows my son to track time spent on activities and exchanges that time into a time he can use with his electronics (eTime).

Full code in GITHUB

I am having trouble coding the part of the code that handles the countdown from his earned eTime. As it is right now it can count down and give him a warning when his eTime has run out, but the process can't be interrupted.

I would like to have him be able to stop his eTime and use the remainder later. I tried putting the function in a while loop.

while(digitalRead(button_9)==LOW){
    delay(60000);
    avail_time -= 1;
    if(avail_time<0){
      playAlarm();
      return;
}

This one registers the keypress but ignores the delay.

I have also tried using a for loop to count down and another to check every second for a keypress.

void useTime() {
  for(int i=avail_time+1; i>0; i--){
    displayTime(i);
    for(int minute=60; minute>0; minute--){
      if(digitalRead(button_9)==HIGH){
        avail_time = i;
        return;
      }
      delay(1000);
    }
  }
  while(digitalRead(button_9)==LOW){
    tone(buzzer, 2000);
    }
  noTone(buzzer);
  avail_time=0;
  displayOptions();
  return;
 }

That one does not register the keypress.

You can use the millis function to check the current 'time'. If you store this, and later call this function again, by subtracting you can see how much time has been passed. so instead of delay(500) you use if (millis() - timeStamp >= 500) { ... to continue your code.

As others said in comments,  you also need to debounce to prevent multiple button triggers.

Edit: Debouncing

There is not a library for debouncing (at least not one on the Arduino site), but you can easily copy the needed code from the following sketch:

Arduino Debounce


If a condition is ever met I want to run a loop permanently I am trying to run an LED to do SOS in morse code if a temperature is over 20 C and motion is detected, but I want it to continue doing SOS even after the motion goes away or the temperature comes down.

Right now it simply does SOS 1 time and stops.

(sorry if coding is messy)

   int counter;
   int motion = 0;

   void setup()
  {

    {Serial.begin(9600);
     pinMode(4, INPUT);
     pinMode(0, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(1, INPUT);
     digitalWrite(0, HIGH);

     }
  }

    void loop()
   {

   int sensorA0Value = analogRead(A0);
   float voltage = sensorA0Value * (5.00 / 1023.00);
   Serial.print("Voltage: ");
   Serial.print(voltage);

   float temp = (voltage -.5)*100;
   Serial.print("| Temp: ");
   Serial.print(temp);
   Serial.println(" Celcius|");

   motion = digitalRead(4);

   if(motion == HIGH)
    {Serial.println("Motion Detected");}
   if(motion == LOW)
     {Serial.println("No Motion");}

   if(motion == HIGH && temp > 30)
     {
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);

     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);

     delay(600);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(1000);

   }
     else {
     digitalWrite(2, LOW);

     }
   delay(1000);
    }

This may be unrelated to the actual question but... your Morse timings
are completely messed up. The standard timings are:

element         duration
------------------------
dot                 1
dash                3
interelement gap    1
intercharacter gap  3
interword gap       7

where the time unit is the duration of a dot. A correctly timed SOS can
be implemented as follows:

const uint32_t DOT_TIME = 150;  // 8 words per minute

void dot() {
    digitalWrite(2, HIGH);
    delay(1 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void dash() {
    digitalWrite(2, HIGH);
    delay(3 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void send_sos() {
    dot(); dot(); dot();
    dash(); dash(); dash();
    dot(); dot(); dot();
    delay(6 * DOT_TIME);  // interword gap
}

Notice that there are no intercharacter gaps within SOS, as this is a
procedural signal, transmitted with no letter boundaries. It
is not a three-letter word. The last delay is written as
6 * DOT_TIME as there is already a one DOT_TIME delay at the end of
the function dot().


Adafruit Flora V2 use onboard and external NeoPixels I am working on wearable project using an Adafruit Flora V2, and for this project I need to use the onboard NeoPixel. I also need to use Neopixels that are attached to the D6 pin (is it a pin?). I have a line at the beginning of my program that says #define PIN 6. I found that I can use the onboard NeoPixel by changing this to #define PIN 8. Is there a way to use the onboard NeoPixel and the ones attached to D6. I already have everything wired up, and the rest of my program is written, I just need to use both pins. Thanks for any possible help.

The #define is just letting you use a nice name for the numeric value of the pin.  If you want to use two different pins, you use two different names.

So you might define them at the beginning something like:

#define BOARDLED 8
#define STRIPLED 6

Then you create a NeoPixel object that uses that pin.  In your case, you'll do this twice.

Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

And then you call the one you want to set/modify/show/etc.

strip.show();
flora_led.show();


Tone() working on all digital pins? Looking at my Arduino Uno board, it appears the digital PWM pins are #11, #10, #9, #6, #5 and #3.

When playing around with the Theremin, it seems that the Tone() message works on all pins regardless of whether they are marked PWM or not?

Can anyone explain what is happening or how this is possible?

The Tone library doesn't use the PWM mode timer functions on the atmega, instead it uses an interrupt routine to toggle the pins. You can find the source code for Tone libary here for reference:

https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/


Uno r3 - Can't get USB Keyboards to work with an USB Host Shield I'm a day 1 beginner to Arduino, and I am trying to obtain input from a USB keyboard. I've connected the USB keyboard to an Arduino USB host shield attached to an Arduino Uno r3, and I am using the example HID sketch (USBHIDBootKeyboard.ino) provided with the USB Host Shield libraries : https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino

I am powering the Arduino Uno r3 + USB Host Shield via USB. Upon init, only Start is written to the Serial Monitor. Tests show that SetReportParser exits with 0. Yet the keyboards are silent. I've tried three keyboards, all of which work properly when connected to the computer.

When using USBHidBootMouse.ino with a mouse, movements & buttons are perceived and print messages as intended.

https://www.circuitsathome.com/mcu/hid-support-for-usb-host-shield-library-2-0-released/ states that

  Also, it is recommended to use external power supply while working with HID devices – I’ve seen many devices which would refuse to function when Arduino receives power from its USB port only.

EDIT : I tried to test if the power was the issue, so I used a 5V generator with intensity measurement. The results are : the Arduino Uno r3 uses 60mA, the keyboard uses 60 mA, connecting to the serial port uses 40 mA (much to my surprise).

This means the keyboard's power requirements shouldn't be the problem.

Then what would the problem be ? I'm helpless here. If the library linked on the official Arduino site doesn't work, then it should mean i'm using it wrong.

see last paragraph of this page https://github.com/felis/USB_Host_Shield_2.0

it says this:

  FAQ

  When I plug my device into the USB connector nothing happens?

  Try to connect a external power supply to the Arduino - this solves
  the problem in most cases.

  You can also use a powered hub between the device and the USB Host
  Shield.

  You should then include the USB hub library: #include <usbhub.h>

  and create the instance like so: USBHub Hub1(&Usb);.

your keyboard may be multiple HID devices with a USB hub to connect them


Controlling op amps amplification ratio by arduino Is there any option how to control amplification ratio of operational amplifier by some logic signal which can be produced by arduino? I am talking about some clasic op amp like lm356 or ui741 in basic inverting or non-inverting circuit (i would like to use non-inverting circuit in my application). I know only about digital potentiometer like solution but i think that it isn't profesional and most eficient solution, so I want to know your opinion. Thanks for reply.

The basic principle is easy to implement.  A non-inverting configuration has a resistor Ri from the inverting input to ground, and a feedback resistor Rf from the same input to the output.  The signal is applied to the non-inverting input.  The gain is 1+Rf/Ri.  You can control the gain by changing Ri, which can be done via a CD4016 quad analog switch and 4 resistors.
HOWEVER, the Arduino is a 0-5V device.  The CD4016 can handle 15V, but to switch it the digital input must pass through half the supply.  The op-amps you mention will require bipolar supplies to handle AC signals (which I assume is what you want), so you could run them with +/-7.5V, with the CD4016 powered between them.  Then to get the Arduino 0-5V to toggle the CD4016 you'd need some level-shifting transistors to get it to +/-7.5.  The upshot is that this is surely going to be more trouble than it's worth.
However, if you are willing to drop the ancient op-amps and use a modern single-supply type (MCP6021, LT1013, etc) that runs on 0-5V, you can use input and output capacitors to convert the signal to AC, then just use the CD4016 as-is. Or JFET transistors, or even bipolars to switch the gain resistor under Arduino control if you don't need audiophile quality.


Best way to add external power supply when main PSU is a solar charge controller? I have a 12V 20A Solar Charge Controller (which is part of my existing Solar Panel System Setup connected to a 12V Sealed Lead Acid Battery) that I will use to power up some pumps with the help of relays and some sensors. And because its a solar charge controller, the output varies depending on the sun, from 12.1v to 13.8v (I set the Load Reconnect, Load Disconnect, Float Charge etc which technically 12V to 13.8V)
How do I power my Arduino Mega safely in this case?
I am planning on using a separate buck converter that will give my Arduino a fixed 9V from the Solar Charge Controller.
Should I power the Arduino with the buck converter parallel to the same PSU (the 12V 20A Solar Charge Controller) I'm using for the pumps and is it safe that way?
or
Should I use a 9V battery to separately power the Arduino Mega?  and what is the explanation behind the concept of using an external PSU for the Arduino Mega when the total Amperes all in all is not exceeding the limit 20A at all?

Should I power the Arduino with the buck converter parallel to the same PSU (the 12V 20A Solar Charge Controller) I'm using for the pumps

Yes. However I wouldn't use a 9V buck regulator, but a 5V one and feed it to the 5V pin. That way you bypass the wasteful LDO on the Arduino, and when running from solar every bit of power saving you can muster helps.

and is it safe that way?

Yes, it's safe. As long as the buck regulator you are using is rated for the voltages in question.


How do I connect an Adafruit headphone jack to an Arduino 101? I just purchased Adafruit headphone jack and I want to know how to connect it to an Arduino 101. I'm trying to use a breadboard to play a sample tone melody from the Arduino libraries, which I want to hear with my iPhone headphones.

I have been looking online for instructions on how to do this, but found nothing. Please advise.

Thank you!

First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.

Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

simulate this circuit – Schematic created using CircuitLab

Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.


Programing AVR 32u4 via ISP with other ISP device connected I have a custom PCB with an Atmega 32u4 chip.  I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.

I now want to add wireless capability via the NRF24L01.  The NRF communicates with the 32u4 via ISP.  Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?

Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use.
You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.

Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.


Build an improved GSM antenna for arduino mkr gsm 1400 I want to use an Arduino MKR GSM 1400 in my area wich has a bad connectivity on mobile internet. On my phone it's very weak and if i drive to the next village it works sometimes on the arduino with the given standard antenna but I want it to work in a wider range. Is there any antenna available specifically for mobile connections wich you can put on a arduino? And how do you call them and where can I buy such a thing or even build it myself? Do you have any suggestions for such an antenna? And is there something I can improve with just using software to strengthen the signal?

On one end of the MKR GSM 1400 is a U.FL antenna connector.  To that you need to connect a U.FL To Female SMA Adaptor.  That adaptor can then screw into an SMA GSM Antenna of your choice.


How can I run the arduino IDE 1.8.9 on debian testing as regular user? When I start the arduino IDE as regular user from my debian testing system, I get a crash right after the splash screen:

Temp/arduino-1.8.9/arduino                                                              :)
Picked up JAVA_TOOL_OPTIONS:
java.lang.NullPointerException
        at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:679)
        at processing.app.Base.onBoardOrPortChange(Base.java:1317)
        at processing.app.Base$12.actionPerformed(Base.java:1544)
        at processing.app.Base.rebuildBoardsMenu(Base.java:1494)
        at processing.app.Base.<init>(Base.java:275)
        at processing.app.Base.main(Base.java:151)
Temp/arduino-1.8.9/arduino  7,28s user 0,50s system 183% cpu 4,243 total

When I start it with sudo I can use everything regularly. There are quite a few bug reports mainly in the archlinux community about a similar issue, where they suggest to install a package arduino-avr-core to solve it. But I assume, the reason why it happens for me, is different, since it runs fine with root privileges, and we do not have such a package in debian. Debians arduino IDE from the repos is way to old to use it these days with modern boards.

My Groups: tty uucp dialout cdrom floppy sudo audio dip video plugdev systemd-journal netdev bluetooth lpadmin scanner docker

The file permissions are fine for the ide and the arduino data directory.

The permissions for the usb device are also correct, just in case:crw-rw----+ 1 root dialout 188, 0 Mai  4 11:42 /dev/ttyUSB0

My Java environment:

java --version                                                                          :)
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+1-Debian-1)
OpenJDK 64-Bit Server VM (build 11.0.3+1-Debian-1, mixed mode, sharing)

Maybe someone ran into the same problem as well?

It turned out, that the current Arduino IDE is using a directory ~/.arduino15 for data. I was not aware of the existence of it. The comments to my question made that clear. I tried to delete the ~/Arduino and ~/.arduino direcory several times, but to no avail. Deleting ~/.arduino15 indeed fixed the issue.


Millis...alternate flash I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug

int LED3 = 5;
int LED4 = 6;

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED3=0;
unsigned long previousMillisLED4=0;

int intervalLED3 = 500;
int intervalLED4 = 500;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);

      digitalWrite(LED3,LOW);
      digitalWrite(LED4,LOW);

}

void loop() {
  //unsigned long currentMillis = millis();
      for(int P=0;P<6;P++){
        //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
        delay(500);
              //previousMillisLED3 = currentMillis;

      //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
       delay(500);
             //previousMillisLED4 = currentMillis;
      }
}

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.

The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.

But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.


What exactly does the Arduino preprocessor do? Arduino claims to be a "language," not just an "application framework," and Arduino files have their own extension, .ino.  The language is obviously C++, but not quite.  My understanding is that Arduino has some sort of special preprocessor which converts .ino files into C++ files before compiling them.

My question is: What exactly does this preprocessor do?  What exactly are the differences between "Arduino language" and real C++?  The Arduino documentation seems to gloss over this.

In particular, I've had weird things happen when I try to define my own classes in my sketch.  It's hard to figure out what I'm doing wrong when the language doesn't seem to be specified anywhere.

It does four things, basically:

It adds #include <Arduino.h> to the top of your file, which gives you access to all the classes, functions and defined variables/macros of the API.
It joins together all the INO files together into a single monolithic file (in the same order as the tabs in the window),
It matches #include entries with libraries and adds the files in those libraries to the list of files to compile, and
It scans through the ino file(s) looking for functions and adds prototypes to them to the top of your file.

It's the latter that can cause problems. Historically it never got the prototypes in the right place, and if you ever passed a structure of your own devising to a function it would break horribly.  It does a better job these days, but it's still not 100% perfect.

It basically means that you don't have to adhere to the "You must define it before you use it" rule of C/C++.  Which of course makes for lazy programmers.


I can't use buffer without printing in my Nodemcu esp8266 #include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

EDIT
here i created a compilable runnable code. basically i am trying to find a word in a http response. my real examples response isnt json and it is as long as this examples response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: https://jsonplaceholder.typicode.com/photos

if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.

The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.

To search for a string in a stream of data you can use function find(string). The networking Client class inherits this function from Arduino Stream class. find will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.


send serial monitor to server and save data in hdd I'd like stream data to my disk via serial and then send it to a central server. e.g. log an event.
i wouldn't use any separate modules.
Any helps appreciated.

You could look and see if there was any data logging libraries already written or you would need to develop a function that wrote to a file held on an SD card.  There are plenty of SD libraries.

If you mean you have a computer connected to the serial connection from the ATMega then there are probably logging programs out there, some terminal monitors save what they receive.


Arduino : distance measurement between fixed points I am creating a moving robot which needs to know its exact position on the map(known before, start point also known). My ideas were :

GPS : this is not accurate enough for me, does not work indoors
Acc + GYRO + Compass(Magnetometer): MPU-9150 : from that values I could compute the position but as small errors are continuously added after a while it becomes very inaccurate

Finally my idea is to put some fixed points into the area and robot can periodically check where they are and compute its position accurate.

Although I did some googlin' I could not find any appropriate sensor pair to do this. My idea is:

one(more if no other option) sensor on robot covering 360 degrees
few fixed points which sends a signal; each different one - let's say : I am the point one. I am the point two etc.
sensor on a robot is receiving those signals and give me some meaningful value e.g. time from which I can compute the distance from each of the fixed point.
10+ meters maximum range is fine for me
must be cheap (less than 30$ for all)

Questions:

Do you have any idea of such sensor pair ?
Or other solution which would fit to my needs?

Bonus:
* The best would be if the fixed points were passive and just reflected the signal sends from robot - but I have no clue if such a thing exist :-)

Thanks in advance for any answers/comments.

Seems to me you are looking for some kinda of SLAM thing. Depending on your knowledge in control theory and your precision goals you can go from simple rotary encoders on wheels to multiple sensor fusion like Extended Kalman filters (example videos). Probably the most precise thing you can have is sensor fusion with LIDAR (can be achieved precisions like 1cm), however the price range is way to far from described.

I would start with a small approach and go from there depending on the results I'd get:

rotary encoders (easy to calibrate and can be precise enough as a starting point)
9DOF IMU (use a Extended Kalman filter or similar to make an AHRS correction). And in this part I have many advices. You have suggested MPU-9150. I'm not familiar with it but looking at datasheet it seems very good, specially because gyro comes factory calibrated. In past I've used razor IMU / GY-85 (adlx345 + ITG3200 + HMC5883L) and gyro was very precise and low noise. Hope Invesense used the same sensor in MPU . First in hardware: Acc are easy to calibrate just use gravity. Gyros are easy to calibrate but hard to do. Why, because it may be hard to get something that spins at constant RPM and know that value. But as I've said, according to datasheet, MPU comes factory calibrated. Magnetometers calibration can be a bit tricky. Bottom line is you get readings from various points of your robot  in 3D space. you plot all and you will get an ellipsoid. Then you find a transformation equation that maps the ellipsoid into a perfect sphere take a look this article. Your concerns about Angle random walk can be minimized with kalman filter and similar. This page provides much great information and examples in how to make a good AHRS. Mr. Madgwick wrote a really nice algorithm that implements the IMU  filter and have it also written in C (nice for Arduino).

After integrate all things with Kalman and see the results, if things are not good enough, you can add more sensor and provide a better estimation for example: sonars, rangefinders, landmarks with image processing and as suggested also, RSSI and triangulation.

These links might help you in finding your way:

Introduction to Kalman Filters and SLAM
Indoor Location Tracking using Received Signal Strength Indicator


Arduino GPRS (GSM) shield (SIM900) no long pins I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno.
The shield I have is this:

As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that?
I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?

Yes, you can.

There is two methods of making shields stackable:

Use the quite hard to source extra long pinned headers to go right through and down (such as these https://www.adafruit.com/products/85) , or
Use separate headers and pins and (if you are using through hole) offsetting them.

Your shield uses the second method, but the descending pins haven't been populated.  By populating those pins you are just completing the build.


My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML So I just got my two ESP8266/ESP-12E WiFi development boards in the mail as I am trying to set up a few home automation devices in my house. I've gotten much further than I thought I would today, considering this is my first foray into working with circuits that involve microprocessors/WiFi, but I've run into a problem that I can't find a solution to myself.  Forgive me if there is another question similar to this, but I could not find it and this seems like the best place to ask.

I am using a tutorial/template program that Rui Santos from Random Nerd Tutorials was kind enough to create ( https://randomnerdtutorials.com/esp8266-web-server/ ), and although we have (as far as I can tell) identical boards, operating systems and Arduino code, I keep getting an HTML page that is text only, with none of the CSS or HTML elements showing.  It should look like this:

However, I am getting a page that looks like this:

His serial monitor is giving this response:

My serial monitor is giving me this response:

I've tried putting client.println("Content-type:text/html"); in a few places to see if it would help display the page, but to no avail.  Any help with getting this little program/website running would be greatly appreciated.

Thanks for your time!

Don't use the low-level tools to handle http, use the built-in http tools. They  make creating http responses trivial. No more concatenating headers or worrying about client status; it provides a nice clean function ex:server.send(404, "text/plain", message); and nice subscription method: server.on().

Checkout its usage on one of the Arduino ESP8266's built-in examples:
https://github.com/esp8266/ESPWebServer/blob/master/examples/HelloServer/HelloServer.ino


Sampling rate of analog read I have a simple following analog reading code:

void setup()
{
  // initialize serial comms
  Serial.begin(9600);
}

void loop()
{
  // read A0
  int val0 = analogRead(0);
  int val1 = analogRead(1);
  int val2 = analogRead(2);
  // print to serial
  Serial.print(val0);
  Serial.print(" ");
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait
  delay(50);
}

How do I determine the sampling rate? I understand for the serial print, it's 3*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.

How much time is spent on analogRead?

The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to about 64 Hz (1 sec / (15/960 lines/sec).

The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.

Update:

  So I could just use 50ms + 15.6 for the sampling rate, ignoring
  analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.

How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.

If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.

It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data,
you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.


converting an unsigned integer into a const char pointer I know this is simple basic C stuff, but I can't quite figure it out or find a solution when searching and reading.
I have a method I want to call from a library that wants a const char pointer
someclass::send(const char *data)

And the value I want to send is actually an unsigned integer:
enum messageTypeEnum
{
  REGISTER_CLIENT = 0x04,
  CLIENT_REGISTERED,
  UPDATE_CREDENTIALS,
  ADD_BRICK,
  GAME_FRAME,
  ERROR
};

enum clientTypeEnum
{
  GAMEBOARD = 0x01,
  BRICK_CONTROLLER,
  PLAYER_CONTROLLER,
  TOUCH_CONTROLLER
};

uint16_t message = GAMEBOARD;
message <<= 8;
message += REGISTER_CLIENT;

So I want to convert it, but I can't quite figure it out.
I know fundamentally the char pointer is just a pointer to a memory address and that c strings are null terminated, so I should be able to create the pointer, add the enum's underlying bytes to the pointer array, and then add a 0 at the end to terminate it, but I don't know how I would do that exactly.
I tried doing it via casting:
const char *data = (char *)&message;

So here I'm saying (if I'm thinking about it correctly), is:

&message take the memory address of message, our uint16
`(char *) interpret it as a pointer for a character string
const char * store that address in this const pointer

Even typing that out I feel like I'm misunderstanding parts.
This compiles, but it crashes my esp32 and I'm sure it's because I don't have a null terminator at the end, but I'm not sure how to add it (I tried to add it via array index but that failed).
What's the proper way of doing this (I'm sure there's a non-casting way that's probably easier)?
Update
More detail re: PMF and Edgar's comments.
I definitely want to send the binary numbers behind the enums up. I'm building a websocket based interactive project where "controller" websocket clients can drive interactions on "gameboards". Websockets don't have a concept of differentiating between client types (I know socket.io does, but I'm wanting to write it all with regular websockets), so I built a registration system into the server that looks at the first two bytes of an array buffer or blob message to determine the client and message type (it seems overly complicated, but I'm building this to give a talk on binary operations and I'm doing it give functional examples of data parsing).
So yeah, all of that to say I definitely want to send the underlying number values from the enums.
The library I'm using is ArduinoWebsockets and they do have a client method called sendBinary that does have a signature like the Serial.write:

Though when I tried this with a non-null terminated c-string my esp32 crashed. That said, I was fumbling around in the code so it may have been something else that caused the crash.
When I follow the method calls down, the library ultimately uses std::string to pull the data out of the passed in c string and takes in the length (meaning it doesn't need to be null terminated(?)):

So maybe I can use the casting to turn my two byte number into a c string and pass in the length of 16?

CORRECTED ANSWER
I dug back into my code after a comment from  Edgar and figured out some needed adjustments. My original solution was mostly correct, but there were some inaccuracies that I want to correct so I'm not goofing up anyone else in the future that may find this answer useful.

So I was overthinking things a bit. I still don't know that this is the best way of handling it, but it is working on the client side.
So, c-strings are just arrays of 8bit values with a null terminator at the end.
I want to end up my enum values, and my enums are define with byte enum-bases:
enum messageTypeEnum
{
  REGISTER_CLIENT = 0x04,
  CLIENT_REGISTERED,
  UPDATE_CREDENTIALS,
  ADD_BRICK,
  GAME_FRAME,
  ERROR
};

enum clientTypeEnum
{
  GAMEBOARD = 0x01,
  BRICK_CONTROLLER,
  PLAYER_CONTROLLER,
  TOUCH_CONTROLLER
};

So, to send up my bytes, I can just build a character array, set each byte in little endian order, and manually terminate it:
NOTE: this is the original assembly that was incorrect.
I put the null terminator at the beginning of the buffer thinking "oh, it's little endian so the terminator needs to be at the beginning". Classic sleepy brain mistake :|

void registerAsAGameBoard()
{
  char buffer[3] = {0, GAMEBOARD, REGISTER_CLIENT};
client.sendBinary((const char *)buffer, 3);
}

void registerAsAGameBoard()
{
  char data[3] = {GAMEBOARD, REGISTER_CLIENT, 0};

  const char *buffer = data;
  size_t size = strlen(buffer);

  client.sendBinary(buffer, size);
}

Now when I call sendBinary with my byte array and the length of the buffer my esp32 doesn't crash (hurray!) and the server receives the buffer correctly!!

I need to make a couple of adjustments on either the client and/or server side to account for the fact that the ESP32 is little endian and the server is already coded to receive payloads in big endian, but that shouldn't be too much of a lift.


Can I detect with software when a PIR sensor is physically connected to Arduino? I'm creating a circuit using an Arduino Nano + ESP8266 to allow LED remote (via mobile app) activation and configuration (RGB colour, timeout, etc.). The circuit also has an optional PIR sensor to switch on the LED when someone enters the room.

I'd like the circuit to behave differently when the PIR is physically connected to the Arduino (i.e. to light the LED in a different colour) but I have no idea of how detect if the sensor is physically connected to the circuit.

I tried reading the value of the Arduino PIN but (obviously) the signal is LOW whether nothing is detected by the PIR or is not physically connected.

I have two different PIR detectors that I can use for the project:

Arduino Compatible PIR Motion Detector (Description)
DFRobot PIR Detector (Description, Schematic)

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

The PIR sensor I have will overpower the internal pull-up resistor of the ATmega328P used on the Arduino Nano. This means if you turn on the pull-up and then get a read of LOW you know something is connected to that pin because the unconnected pin will always read HIGH with the pull-up on. With this approach you can get false negatives because the pin will also read HIGH if the PIR is triggered but you won't ever get false positives for PIR sensor detection. This means you can't rely on just doing a single test in setup() because the PIR might be triggered then so you will need to repeatedly run the test until the PIR sensor is detected. Example sketch:

int PIRpin = 2;    //the input pin for the PIR sensor
boolean PIRconnected = false;

void setup() {
  Serial.begin(9600);
  pinMode(PIRpin, INPUT);
}

void loop() {
  if (PIRconnected == false) {
    pinMode(PIRpin, INPUT_PULLUP);
    if (digitalRead(PIRpin) == LOW) {
      Serial.println(F("PIR sensor detected"));
      PIRconnected = true;
    }
    pinMode(PIRpin, INPUT);  //turn off the internal pull-up to reduce power consumption
  }
  Serial.println(digitalRead(PIRpin));
  delay(500);
}


3 input (on/off/off with delay) to control 1device using ESP8266 as Web Server I want to control one device in three ways : turn on / turn off / turn off with delay.
To do that i use an ESP8266 web server + android phone app.
The problem is that turn off with delay wont work.
It works with delay() but i dont want to use delay() as it stops other functions.
I would be grateful if you could help me.
here is my code :
#include <ESP8266WiFi.h>
const int device1 = 14;
unsigned long previousMillis = 0;
const long interval = 5000;
const char* ssid     = "****";
const char* password = "****";
#include <Arduino.h>
WiFiServer server(80);
String data = "";

void setup() {
 pinMode(device1, OUTPUT);
Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
WiFi.begin(ssid, password);
IPAddress ip(*,*,*,*);
IPAddress gateway(*,*,*,*);
IPAddress subnet(*,*,*,*);
WiFi.config(ip, gateway, subnet);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

 server.begin();

 Serial.println(WiFi.localIP());
 }

void loop() {
    unsigned long currentMillis = millis();

  WiFiClient client = server.available();
 if (!client) {
   return;
 }

 while(!client.available()){
 }

 String req = client.readStringUntil('\r');
 client.flush();
 if (req.indexOf("/on") != -1)
   { digitalWrite(device1, HIGH);}
 if (req.indexOf("/off") != -1)
   { digitalWrite(device1, LOW);}

 if (req.indexOf("/delay") != -1)
 {
  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    digitalWrite(device1, LOW);

}
}

You have various logic problems:
You block until WiFiClient has bytes available. Everything comes to a stop. So if you send a "/delay" command, it will receive and parse that command, turn on the device, then block again, indefinitely, until you send another command. Once you send another command, it will check the interval ONCE, and then lock up again. You need to rewrite your loop to check for bytes, read them if found, and do other work (like checking your time interval) if no bytes are available.
Next, your timing code is a mess. You only ever set currentMillis and previousMillis at the same time, so they will never be different. And you only ever check the times once when you first detect a "/delay" command.
Instead, refactor your logic. Only set previousMillis when you first detect the delay command, and then only compare if previousMillis to currentMillis if  previousMillis is not 0:
if (req.indexOf("/delay") != -1)
{
    previousMillis = millis();
}

if (previousMillis != 0 && millis() - previousMillis >= interval) {
    digitalWrite(device1, LOW);
    previousMillis = 0;
}

(Also note that you were declaring a second, independent variable  previousMillis inside your if statement, which only exists inside the curly braces for that if statement. Don't do that. Use the existing global variable you defined, as I show in my edited code.)


How to declare a Dynamic Array? I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)

Heres my code with vectors: https://pastebin.com/qBsRvk9Y

The vector is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by vect[index] or method vect.at(index). And as there are no exceptions available, who knows what it does after the out of range call.

You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.


Link to an project for remotely turning off light switch? I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!

This isn't exactly what you asked for, but may be a better idea.

Light switches are electrically just switches.  Either two points are connected or they are not.  In this case they are meant to be mechanically actuated by humans.

Instead of making a electrically controlled contraption that mechanically activates the existing switch, you could more easily use a electrically-activated switch directly.  Such things are called relays, and are quite common and readily available.  You can easily get a relay that can be actuated from 5 V that can switch 120 or 240 Vac at a few amps.

Put the relay in parallel across the switch if you want the switch to be able to override the light on, and in series if you want the switch to be able to override the light off.

To allow both the relay and the switch to toggle the light on/off independently, each needs to be a SPDT (single pole double throw) switch or relay.  Actually, you'll have a hard time finding a relay that isn't at least SPDT.  Ordinary wall switches aren't, but ones meant for multiple switches to control the same light are, like you often find at the top and bottom of the same set of stairs.


How do I specify a working directory when saving to SD card? I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:

// see if the directory exists, create it if not.
if( !SD.exists("/DCIM/100NIKON") )
{
  if( SD.mkdir("/DCIM/100NIKON") )
  {
    Serial.print("File directory created: ");
  }
  else {
    error("File directory not created");
  }
}
else
{
  Serial.print("File directory exists: ");
}

// Test file
char filename[] = "DSCN0000.JPG";

if (! SD.exists(filename))
{
  logfile = SD.open(filename, FILE_WRITE); // only open a new file if it doesn't exist
}

if (! logfile)
{
  error("Couldnt create file");
}

The Arduino creates the directory, but the file is still saved to the root.  I would love some help or tips on this.

You're creating a directory, and then not writing the file into it.

You need to change the filename to /DCIM/100NIKON/DSCN0000.JPG";

Note that SD.open() takes the full filepath to the file, not just the file*name*.

From the Arduino Docs:

  The file names passed to the SD library functions can include paths
  separated by forward-slashes, /, e.g. "directory/filename.txt".
  Because the working directory is always the root of the SD card, a
  name refers to the same file whether or not it includes a leading
  slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version
  1.0, the library supports opening multiple files.

(emphasis mine)


Is this a good way to filter noise due to vibration in limit switch? I have a circuit connected as follows

my limit switches which are attached to my structure sometimes gets falsely triggered, so I wrote this code to address it. My motor is supposed to go down skip the up limit switch at first hit the down one then go back to the up one. is this a good way to implement it?
https://pastebin.com/qVU1Gp0q

//Switch pressed ->  reading HIGH
//Switch not pressed -> reading LOW
//Motor direction 0 is down, 1 is up

const int uplimit = 32;
const int downlimit = 34;
const int motorspeed = 9;
const int motordirection = 28;
//const int pumpspeed=5;
//const int pumpdirection=6;
const int motorenable = 26;
//const int pumpenable=;
int Finishedcleaning = 0;
int Reachedup = 0;
int Motorinitialsetup = 0;
int Motorsecondsetup = 0;
int downfiltered = 0;
int upfiltered = 0;
void setup() {
  // put your setup code here, to run once:

  pinMode(motorspeed, OUTPUT);
  pinMode(motordirection, OUTPUT);
  pinMode(motorenable, OUTPUT);
  //pinMode(pumpspeed, OUTPUT);
  //pinMode(pumpenable, OUTPUT);
  pinMode(uplimit, INPUT);
  pinMode(downlimit, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int average1 = 0;
  int average2 = 0;
  if (Motorinitialsetup == 0 ) // to be run before hitting initial switch
  { digitalWrite(motorenable, HIGH);
    analogWrite(motorspeed, 190);
    digitalWrite(motordirection, 0); // Bring motor down
    //   digitalWrite(pumpenable,HIGH);
    //  digitalWrite(pumpdirection,1);
    // analogWrite(pumpspeed,240);
    Motorinitialsetup = 1; //so this if statement does not run again

  }

  for (int i = 1; i < 100; i++)
  { downfiltered = digitalRead(downlimit);
    average1 = average1 + downfiltered;
  }
  average1 = average1 / 100;

  if ((average1 > 0.9) && Finishedcleaning == 0 ) // Function after hitting down switch
  {
    delay(1000); // wait until motor cross switch
    analogWrite(motorspeed, 0); // stop motor
    Finishedcleaning = 1; //indicate cleaning is over for next loop
    delay(500); // wait until motor cross switch
  }

  if ( (Finishedcleaning == 1) &&   (Reachedup == 0)  && (Motorsecondsetup == 0))
  {
    digitalWrite(motordirection, 1); // reverse motor direction
    analogWrite(motorspeed, 190); // start motor again
    Motorsecondsetup = 1;
  }

  if ( Motorsecondsetup == 1) // only checks switch up switch after motors comes back
  {

    for (int i = 1; i < 300; i++)
    { upfiltered = digitalRead(downlimit);
      average2 = average2 + downfiltered;

    }
    average2 = average2 / 300;
    if ((average2 > 0.9) && (Finishedcleaning == 1)) // Stop Motor after returning
    { analogWrite(motorspeed, 0);
      delay(1000);
      Reachedup = 1; // indicate finished returning after cleaning cycle
    }
  }
}

Hardware:

You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.

If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.

You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.

The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.

The ground path is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.

Software:

An integer can not be 0.9, therefor your filter does not work.

The function digitalRead() returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.

Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.

int digitalReadFiltered(int pin) {
  int result;
  const int n = 20;                // maximum 30
  int count = 0;                   // an integer can hold 30 analog samples

  for (int i = 0; i < n; i++) {
    if (digitalRead(pin) == HIGH) {
      count++;
    }
    delay(1);        // 1 ms for sampling during 20 ms with 20 samples
  }

  if (count > (n / 2)) {
    result = HIGH;   // counted enough HIGH values
  } else {
    result = LOW;
  }

  return(result);
}

In short, a pull down (or pull up) resistor with a low value makes the circuit low impedance, and the electrical noise will have less influence.

When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.

When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.

A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.

It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.

A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.


I2S read() is which channel? The Arduino I2S reference describes the I2S standard and functions available with the standard I2S library, (Bizarrely it doesn't reference the existing read() function which is used in the examples but that is beside the point). There also exists an ArduinoSound library, however I have the same issue with this.
I would like to record audio from WM8731 connected up to Arduino. I am using an SAMD arduino part.
But, I have a tremendous issue with the I2S.read() function. The I2S.read() function only returns a singular value, however the I2S standard is intrinsically stereo.
This is particularly important for my project as I am only interested in the LEFT channel as the RIGHT channel is muted.
I would expect this to either:

return a pair of values (i.e left /right) samples for that particular point in time , OR
return a singular sample with extra information telling me which channel that is was retrieved from.

However it seems this is not the case. (Github)
I also assume that the I2S is buffered making it impossible to simply read the WS pin state, as I will probably be popping a sample from the buffer that was push into the buffer at some point in the past.
So, is it possible to know which channel the sample was returned from the I2S.read() function or does this mean that the library needs to be modified?
I am more interested in using the samd library as other libraries such as AudioLibrary is limited to 16-bit - I need 32-bit resolution.

From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the read(buffer, len) variant to read two (or more) samples at once.
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));


What does "Arduino compatible" mean? I wanted to buy an Arduino (ATmega) 2560 (8 Bit MCU) via Amazon. But there was no Arduino visible. There was only a

SainSmart 2560 and

SunFounder 2560

On both websides (SainSmart and SunFounder) there is the information that they are Arduino compatible. But all three boards (Atmel-orginal, SainSmart, SunFounder) do not look similar... There are differences. Is it possible to buy one of those boards without:

checking the datasheet differences
having problems with the Arduino Ethernet Shield !?

So, what is compatible ?

Arduino Compatible can mean many things, but most of the time it means that some company has made something they sell to a customer that supports development with the Arduino IDE.

The thing is that most Arduino Compatible units use the Atmel processors, but some use others too. Third party developers then make "board"-projects that you can add into the Arduino IDE.

Be aware though that you in some cases can run into issues if you dont do your homework, here are some of the issues you can run into:

Some "compatible" boards use different architectures, so even if you can do many things with the Arduino IDE, maybe some sensor libraries are not supported. (Might have to be hacked or updated)
Some "compatible" boards have different USB-circuits (if they have them at all)
Most of the boards you buy off aliexpress, banggood etc. do not come with instructions at all and some times they differ from the "original" design (might be better, might be "the same" or might be worse.).

I'm not trying to scare you off, but just my experiences. You can find a lot of fun things on those sites like clones of lilitiny with the AtTiny 85. One example is in my blog heer: http://mjelde.blogspot.no/2015/12/lilytiny-lilypad-attiny85-wearable-iot.html

The main issue with the clones I've had is that some times they differ in some ways that the first times will make you scratch your head. Like: ESP8266 is Arduino Compatible with the boards manager added ( https://github.com/esp8266/Arduino ), BUT: The input pins are not "correct" marked. So you should then add constants to "remap" them in your code.

Also the ESP8266 does only support 1V analog read, while many Arduinos support 5V. But you can "fix" this with an 16bit ADC (analog to digital converter). The ESP8266 only has 3.3V also, so you cant run sensors that "must" have 5V, without then giving them a different power circuit :)

The AtTiny 85 LilyTiny clone i bought in a pair of 2 from AliExpress works fine and works different than the rest of the Arduinos. Uploading to those for instance means you leave them disconnected and then you hit upload in the IDE. Then it says in the status window to connect it, which you then do.

Then it uploads. It has very few inputs, but it's very cute id say. Primarily it's made for wearable and of course it has a lot of short comings compared to a large arduino board. But you can of course use it to control RGB leds, etc.

Remember to always check specifications (3V vs 5V, how much analog read resolution can it handle, etc). There is the sensor vs board (some sensors work on both 3.3V and 5V, some work only on 5V, some only on 3.3V).

For going to 5V to 3.3V you usually use a voltage divider. Either you can buy pre made ones or you can make it based off three resistors and some math :-)


How to use DO pin on ldr module? I have ldr module with 4 pins
 1. Vin
 2. Gnd
 3. AO
 4. DO

I want to know how can i take advantage of DO suppose i want to turn on lcd display when light falls on the ldr sensor!

I have noticed when light falls on ldr sensor the Green  led with DO written next to it lights up.

The DO pin gives a Digital Output that is HIGH when the light falling on the LDR is above a threshold, and LOW when it's below a threshold. Just connect it to a digital input pin and read that pin with digitalRead().

You can change the threshold by adjusting the small blue trimpot.


How to correctly read a string from Arduino serial port? I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:

var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

server.listen(8080);
app.use(express.static('public'));

var brightness1 = 0;
var brightness2 = 0;
var string;

io.sockets.on('connection', function (socket) {
    socket.on('led', function (data) {
        brightness1 = data.value1;
        brightness2 = data.value2;
        string = brightness1 +","+brightness2;
        var buf = new Buffer(1);
        buf.write(string);
        serialPort.write(buf);
        console.log(buf);
        console.log(string);
        io.sockets.emit('led', {value1: brightness1, value2: brightness2});

    });

So based on that, I'm sending a string over the serial and the console log showed above gives me that:

<Buffer 32>    //console.log(buf);
23,0           //console.log(string);

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the

Arduino side I used the sketch provided here and retouch it a bit based on my needs:

void setup()
{
  Serial.begin(115200);
}
void loop()
{
  while(!Serial.available());   //wait until a byte was received
      Serial.println(Serial.read());
      int a = Serial.parseInt();
      int b = Serial.parseInt();
      Serial.println(a);
      Serial.println(b);
      //analogWrite(3, a);
}

but the result of my Serial.print() are really incongruents, something like:
5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?

This is a common (and my favorite) approach:

Choose an “end of message” character. CR or LF can be good choices,
especially if you want to test your program with a terminal emulator.
On the Arduino, buffer all the received bytes until you see the end of
message.
When you see the end of message, handle the buffer to a function that
will parse and process it.

I would avoid parseInt() for anything but the simplest tests, because
it is both blocking and sensitive to the timing of the input.

For an example, you can take a look at this
Simple Arduino command line
interpreter
(look at loop()). It's non blocking, so you can add background
processing to perform while waiting for input characters.


How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code? I am attaching my code below :

int cwled=9;
int wwled=10;
int button=8;
int buttonpress;
long startTime=0;
long endTime;
long holdTime;
boolean previous = LOW;
boolean current;
int state=0;
int pot = A0;
boolean cwState = HIGH;
boolean wwState = LOW;
int brightness;
int counter = 1;
boolean pressB;

void setup(){
  pinMode(cwled,OUTPUT);
  pinMode(wwled,OUTPUT);
  pinMode(button,INPUT);
  Serial.begin(9600);

}

void loop() {
  if(state == 0){
    brightness= map(analogRead(pot),0,1023, 0, 255);
        analogWrite(cwled,brightness);
       // analogWrite(wwled,0);
        Serial.println("Initialized");
  }
  current= digitalRead(button);
  if(current == HIGH){
  pressDetection();
  state =1;
  }
}

void pressDetection(){
  pressB=digitalRead(button);
  if(pressB==HIGH && previous == LOW)
  {
    state =1;
    startTime = millis();
  }
  while(digitalRead(button) == HIGH){
    endTime = millis();
    Serial.println("Inside loop");
  }
  previous = LOW;
  holdTime = endTime - startTime;
  if(holdTime> 500){
    longPress();
  }
  else{
    shortPress();
  }

  }

void shortPress(){
  cwState = !cwState;
  wwState = !wwState;
  //brightness= map(analogRead(pot),0,1023, 0, 255);
  if(cwState == HIGH && wwState == LOW){
   brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
   Serial.println("cwState");
   return;
  }
  if(cwState == LOW && wwState == HIGH){
  // brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,LOW);
   Serial.println("wwState");
   return;
  }
 /*else if(cwState == HIGH && wwState == HIGH){
   //brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
  }*/
}

void longPress(){

   cwState =wwState = HIGH;

   //if(cwState == HIGH && wwState == HIGH){
 //  brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,HIGH);
  cwState = !cwState;

 //}

}

I understand there are so many variables unused, this program needs a lot of improvising.
My question is:

How do I improve this code?
How do I add dimming via pwm in this code?
And if I have to add one more type of LED or say n number of LEDs and want to toggle between them what should be the algorithm.

My aim is to use a push button to switch between different types of LEDs (in my case between warmwhite LED and coldwhite LED, if Arduino registers long press off the push button all the LEDs light up, in my case both warmwhite and coldwhite LEDs turn on, and short press of push button toggles between warmwhite and coldwhite LED. The program by default switches on coldwhite LED first and after a long press, shortpress sets default LED to high which is coldwhite.

I am not a hardcore programmer but I have more than basic knowledge of OOPS programming. I am an ECE Engineer and I believe I have slightly more than basic understanding of OOPS and procedural programming. I am aware of C++, C and JAVA only. Any advice or help would be highly appreciated.

How do you improve your code?

Firstly there is nothing disastrously wrong with you code, it could do with a polish, but who's code couldn't?

In the dim and very distant past I was told "you write code once but read it many times" so try and make your code readable and clear.

If the values aren't going to change then they should be constants or #defines.
ALWAYS initialise variables.  (Doesn't matter on an Arduino because the compiler does it for you, but its good practice).
Boolean should be true or false.
You are writing C/C++ not Java.  Opening braces { should be on a new line.  It makes the code easier to read and match up the braces.
Unless your space bar is broken, put spaces after commas and either side of equals.
Using function parameters and less global variables will make you code more reusable.  Imagine the day when you start a new project and copy and paste functions from previous projects and finish the code in 15 minutes.
One statement per line.  cwState = wwState = HIGH;.  In this case its not a problem, but you can get into states where side affects screw everything up.  Also its easier to read.
Comment the code as you go, because you'll never go back.
Explain what each function does, because you'll have forgot by
tomorrow.

I hope that helps you write better code and none of it has caused offence.


Programming arduino via bluetooth module issue I followed a tutorial on how to setup arduino and bluetooth so it can be programmed without usb cables. I didn't use capacitors or resistors asthere doesn't seem to be a need for them. I have the serial output appearing on arduino serial console via bluetooth (no usb cable connected). Since the is a working connection that means it is working to a point. However when trying to upload I get "avrdude: stk500_getsync(): not in sync: resp=0x4c" error.

I didn't connect pin 32 of hc-05 to arduino reset pin yet, could that be the issue? I don't actually need arduino to be reset since I can just kill the power to it manually at least for now. I also used 9600 as baud rate instead of 115200 as in the tutorial, because my arduino code used 9600 but maybe I misunderstood this and it actually needs to be 115200 regardless or my baud rate in arduino code?

What else could be the cause?

Edit 1:

From the answer by @sachleen I changed the baud rate as per the tutorial and soldered pin 32 of the hc-05 module to rst pin of arduino.

After baud rate change opening arduino serial console no longer outputs anything. Why did this happen? I was getting serial output before when baud rate of hc-05 was 9600.

After soldering the rst pin arduino also seems to reset after serial console is opened. I did not add the capacitor, is it required and if so why? I also excluded resistors since it seems they are only for voltage reduction from 5v to 3V (my arduino is 3.3V version).

I wrote the tutorial you were following so maybe I can help. When I was building the circuit initially I used some of the other tutorials out there on Arduino Bluetooth programming which don't have a lot of the extra resistors and capacitor.  However, I couldn't get any of those to work reliably.  Using a circuit simulator and some trial and error, I ended up with the circuit shown in the tutorial which worked for me.

While there "doesn't seem to be a need for" some of the extra passives, if your circuit doesn't work without them, perhaps there is a need for them after all? ;-) Now, I have heard from other people that they were able to leave out certain bits so it seems that there is some variability in the hardware. But we're talking four passives to ensure reliable operation, so why leave them out?

Anyway, a couple of points:

Pin 32 on the HC-05 becomes active upon Bluetooth connection.  We configure the pin to be active low so we can use it to auto-reset the Arduino upon serial connection to emulate what happens with the normal USB connection.  You can leave out the connection to pin 32 only if you want to have to manually reset the Arduino to program it.
The 115200 baud rate is the rate for programming the Arduino and is set by the Arduino bootloader.  It is possible to re-flash the bootloader with a different configuration if you needed to for some reason.
So, the programming baud rate is fixed in the bootloader, but the communication baud rate is configurable in software using Serial.begin(). However, the HC-05's baud rate has to be the same as the Arduino's, so you need to stick with the same baud rate for both programming and communication (115200 by default).
There are two resistors involved with the reset, R3 and R2.  I believe R2 is only necessary for 5V Arduinos to act as a voltage divider with R3.  However, R3 should be included for any voltage Arduino. See this Atmel design note - "The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically ... This pull-up resistor makes sure that reset does not go low unintended." R3 should be 4.7k or greater; most designs stick with 10k.
The capacitor C1 is necessary because Pin 32 stays low the entire time Bluetooth is connected.  If you connect RST to Pin 32 directly, the Arduino will just stay reset until the Bluetooth connection drops and nothing will work just as if you held down the reset button and never let go.

With C1 in place, when Pin 32 goes low it will momentarily discharge C1, pulling RST low and resetting the Arduino. C1 will immediately begin charging through R3 back up to VCC which will restore RST to high, bringing the Arduino out of reset.  The values of R3 and C1 affect the timing of the reset and must be chosen appropriately.
Don't forget R1.  I can't remember the reason it is helpful, but it has something to do with the Arduino/Atmel UART.  I found the recommendation for adding it one day on an Atmel discussion board and it has solved a non-working circuit for me many times.

Hope that helps!


Why are the Do While loops not stopping? Ive been staring at this for a while now and I am going cross-eyed.  I am writing a simply program to change colors of a 3 color LED.  It is working, but then I noticed the LED would sometimes flash.  I did a variety of tests and eventually, using the serial monitor, found out the issue.  The brightness should count down to a brightness level of 0 and up to a level of 255.  However, sometimes it counts below 0 to -1 and sometimes it continues infinitely past 255.  I cant figure out why.  Below is the code and the serial monitor outputs.  The only way I can stop is by manually setting the value outside the loop.  You can see those lines commented out to allow for the error.
int randLeg;  // var to pick a random leg

// set all 3 legs to max brightness at start
int legThreeBrightness = 255;
int legFiveBrightness = 255;
int legSixBrightness = 255;
int delayTime = 15;
int increment = 1;

void setup() {

    Serial.begin(9600);

    // set pins as output
    pinMode(3, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);

    // turn all the LEDs on
    analogWrite(3, legThreeBrightness);
    analogWrite(5, legFiveBrightness);
    analogWrite(6, legSixBrightness);

    randomSeed(analogRead(0));  // seed rand num generator

}

void loop() {

    randLeg = random(4, 7);  // pick a random leg

    switch (randLeg) {
    case 4:  //-1 for pin 3
        if (legThreeBrightness == 255){
          do {
                Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness - increment;
             } while (legThreeBrightness >= 0);
             //legThreeBrightness = 0;
        }
        else {
         do {
                Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness + increment;
             } while (legThreeBrightness <= 255);
             //legThreeBrightness = 255;
        }
      break;

    case 5:
        if (legFiveBrightness == 255){
          do {
                ////Serial.println(legFiveBrightness);
                analogWrite(5, legFiveBrightness);
                delay(delayTime);
                legFiveBrightness = legFiveBrightness - increment;
             } while (legFiveBrightness >= 0);
             //legFiveBrightness = 0;
        }
        else {
         do {
                ////Serial.println(legFiveBrightness);
                analogWrite(5, legFiveBrightness);
                delay(delayTime);
                legFiveBrightness = legFiveBrightness + increment;
             } while (legFiveBrightness <= 255);
             //legFiveBrightness = 255;
        }
      break;
    case 6:
        if (legSixBrightness == 255){
          do {
                ////Serial.println(legSixBrightness);
                analogWrite(6, legSixBrightness);
                delay(delayTime);
                legSixBrightness = legSixBrightness - increment;
             } while (legSixBrightness >= 0);
             //legSixBrightness = 0;
        }
        else {
         do {
                ////Serial.println(legSixBrightness);
                analogWrite(6, legSixBrightness);
                delay(delayTime);
                legSixBrightness = legSixBrightness + increment;
             } while (legSixBrightness <= 255);
             //legSixBrightness = 255;
        }
      break;
   }

}

10 9 8 7 6 5 4 3 2 1 0 -1

and

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

change >= and <= to > and < respectively.
You want it to stop at 0, but your do-while will do another round, since 0>=0 is true. So your code only stops at -1 and 256.
When legThreeBrightness is 256 it should be counting down, but your if (legThreeBrightness == 255){ doesn't detect this, so the code will continue counting up. I'd probably change this line to if (legThreeBrightness >= 255){ to prevent this from ever happening (which it shouldn't, but still).


Complex Arduino programs Im working on a RGB LED matrix project (10 x 10 Neopixels) and I'm using classes to handle the different hardware components. Whats the best way to deal with multiple files in the project eg, I have a class which holds the various display functions such as writing text and drawing circles, but every time I change something it takes ages to compile (Greater than 30 seconds) is there a way to have multiple files without using classes?

Any help would be greatly appreciated.

Cheers

I noticed that it is very hard to use classes with the default IDE.
Each file will be in a different tab, but normally each class has a header (.h) and implementation (.c) file, so 2 extra tabs per class.

If you have just 3-4 classes you can use the default IDE.

However, if you want to use more, you have to use e.g. Eclipse or Visual Studio, whatever IDE you like best.

Search for Eclipse/Arduino, I think there are multiple options.

Myself I use visualmicro ... it is free except you cannot use the debugger option.

I used several classes in my sketch and don't think the compile time was 30 seconds; it might be depending also on the amount of include files.

Also a complex program is not necessarily a program with many classes. I would say, that if you put too much functionality in one class (or one single sketch), you get a complex program.


For what is used an ESC with a PWM? So I was reading a few questions on drone, and I reach this one.

It said that an ESC is used between the PWM Arduinno's port and the motor. I don't really understand what it means. According to what I understand, a PWM is a varying signal and you just need an electric relay to receive this signal so that the motor receives correct voltage.

However, in other article I read that there are many different ESCs, with firmware and many other parameters to be taken into account. It seems quite overkill for what a relay does, so I am wondering:

What is inside an ESC?
More important, what does it do with PWM signal that could not be achieved with a relay and is essential to command the motor?

An ESC is an Electronic Speed Controller. It's purpose is to control the speed and direction of a Brushless DC Motor.

A Bushless DC Motor ("BLDM") is not like other motors. You can't just provide it power and it will spin. Instead it is made up of three (or multiples of three) electromagnets along with a permanent magnet on the rotor. Energising these electromagnets in the right order at the right time (and the right amount, too) pulls the permanent magnet around in a circle, making the motor spin.

It's the ESC that has the job of controlling these electromagnets.

You provide a PWM signal as a digital speed indication. The ESC then interprets that as an indication of how fast you want the motor to turn, and excites the electromagnets in the right way to make that happen.

Oh, and no, you certainly never want to provide a PWM signal to a relay. A PWM signal switches hundreds, if not thousands, of times per second. A relay is capable of switching, at best, maybe 10 or 20 times per second.  Relays don't drive motors. Motor drivers (or at the bare minimum, MOSFETs) drive motors.


I want to log GPS coordinates using my Arduino and other sensors I want to log GPS coordinates using my Arduino and other sensors.  The difficulty is that I will be in forested conditions.  Would it be better to hardwire a gps device to the Arduino or to bluetooth an external device (a much more accurate, Trimble device that I know will give me the accuracy I need)?  Can such devices pair to a bluetooth receiver that would hardwire to my Arduino, or do I need an intermediate device like my iPhone?

The GPS receiver I've always used is the Adafruit Ultimate GPS:

https://www.adafruit.com/products/746?gclid=CjwKEAjwoPG8BRCSi5uu6d6N5WcSJABHzD8FmldH1vIvTt8h-S-948CJmDR6fR_BcF20UZMS4I-AEBoCt9Tw_wcB

It comes with a spot for you to plug in an external antenna (with an adapter), so you can get more precision and presumably be able to receive data much more accurately in places like forests. However, I'm not sure of this, so an external device may be the way to go. Bluetooth would be possible, but it can be a little difficult to set up with Arduino if you lack the experience, so if you can I'd go with a wired connection (with an RS232 or other).


Detecting Motion behind a robot I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side.
When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance <= 50 cm and > 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it.
 I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.

This is a basic problem of only having two sensors.  There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors.  Anything else is, and always will be, ambiguous.
If you think of it as a circle divided in two, you have only three possible conditions:

That is, left, right or somewhere.  Not ideal.
So you need more data to be able to make a decision.  That means more sensors.  The ideal scenario is four sensors - left, right, front and rear.  That gives you many possible scenarios, including:

As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on.  For instance, using sailing terminology, those 8 circles would mean (in order):

Motion on the left beam
Motion on the port bow
Motion dead ahead
Motion on the starboard bow
Motion on the starboard beam
Motion on the starboard quarter
Motion dead astern
Motion on the port quarter

Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off.  You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.


Can't upload any code to my Arduino board I have an Arduino Uno R3 with an ATmega238 microchip. I can't upload any code to it: the green led and pin13 LED are always on (without flashing ) and the RX and TX LEDs don't flash when I upload code or press the reset button. Is the microchip malfunctioning?

And what happens when a reverse current returns to Arduino from a relay?

You basically have 2 questions here.

1: Why is my Uno not uploading code.

2: How does back EMF effect a microcontroller. We'll address 2 first

When a relay module is activated, it energizes a coil to close a switch. This coil is an inductor, which is an energy storage device. When the signal to the relay tells it to turn off, your trying to de-energize the coil. Whereas before you let current run through the coil to establish a magnetic field, now you cut the current supply and let the magnetic field die out.
The problem this creates is back EMF. As Faraday's law will tell us, a change in a magnetic field causes a voltage (an EMF) in a coil. When we were charging the circuit, this was the voltage applied to the coil. When we discharge the inductor, this voltage is back EMF, and is in the opposite direction as charging voltage.

How does this affect your arduino? Well, it can be anything ranging from harmless to catastrophic. It may simply reset your arduino (as one I was working with did on a past project [where an occiliscope showed back EMF spikes in excess of -30V]) or it might straight-up burn the ATMega328p that acts as the Uno's brain. Or it might take out the voltage regulator, or cause a host of other problems.

The simplest fix for back EMF is to put a diode in parallel with the relay with cathode to your positive terminal and anode to your negetive terminal. This creates a short for the relay's coil to discharge through. Some better solutions (especially for sensitive digital equiptment) involve entirely isolating the relay's power supply form the rest of your circuit with an optoisolator.

Problem 1: Assuming that these problems were related to the use of a relay without the proper safeguards, you might try a few things to verify your chip is still alive. If  you have a second arduino you might try using it to build an ISP, which will allow you to both reburn the bootloader and upload sketches independently of the uno's onboard usb com port programmer. If that works but the onboard programmer still does not, you may need to reflash the programmer (which I've read can also be done with an ISP, though I've never tried it.)

Hope that helps!


Interfacing to scale over RS-232 Objective: interface and Arduino MEGA to a Mettler Toledo SB32001 using the RS-232 communication protocol described in the manual.

Equipment Used:

SB32001 Mettler Toledo 32 kg scale
Arduino MEGA
Sparkfun RS232 Shifter - SMD

Background:

I am using the SoftwareSerial library to try to communicate with the scale through MEGA pins 52 and 53. I have the level shifter connected to the scale using a through cable.

So far, I have tried to send the most basic command to the scale, and the command is both not executing, and not causing a status code to be send back (i.e. failure OR success). My Tx light on the level shifter flashes, but the Rx light never does.

Write string to screen:

D "String"

Because I have a through cable, I have tried switching the Tx and Rx pins in code. Neither has worked.

The from the scale has the following options I can set:

Baud Rate: 150, 300, 600, 1200, 2400, 4800, 9600
Parity: 7b-E, 7b-no, 8b-no, 7b-odd

Here is a minimal (non)working example of my code:

#include <SoftwareSerial.h>

const int pinTX = 53;
const int pinRX = 52;

scale = SoftwareSerial(53, 52);

void setup(){
    Serial.begin(9600);
    scale.begin(9600);
    delay(100);
}

void loop(){
    scale.println("D \"Hello!?\"");
    delay(100);

    while (scale.available()){
        Serial.print(scale.read());
    }
    Serial.println()
    delay(100);
}

What I need:

I need help figuring out where I should look next to solve this issue. I have tried switching the transmit and receive pins in software. I have tried using jumpers to switch the Tx and Rx pins in hardware. I have tried 7 and 8-bit settings with no parity. Nothing give me a signal back. Totally perplexed?

Is it my converter chip? Does anyone know of problems with this shifter? I know that it does not contain the industry standard MAX232

The solution turned out to be a couple of things, some of which mentioned by others in the comments.

Problems that needed to be fixed:

My level-shifter was a huge part of the problem. I switched to a MAX232-based chip and then I was a least able to get responses shorted lines 2 and 3 (Tx and Rx).
I needed a cross-over cable. I had tried this while troubleshooting, but because that alone didn't fix the problem, I had not idea whether or not that was the problem, or just one of the problems.
I needed to use the onboard UART (Serial1) rather than SoftwareSerial. The problem was that I needed to be able to set the protocol to 8 bits with no parity. This configuration parameter cannot be changed on SoftwareSerial, but is as simple as Serial1.begin(9600, SERIAL_8N2).

Thank you for the help, and hopefully my mistakes make the process easier for others.


Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3? I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.

Writing to SoftwareSerial seems to be working but reading not.
As I write "AT", the module returns me "-5" which should be "OK".

As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.

#include <SoftwareSerial.h>
SoftwareSerial ss(rx, tx);

void setup() {
  Serial.begin(9600);
  ss.begin(9600);
}

void loop() {
  while (Serial.available()) ss.write(Serial.read());
  while (ss.available()) Serial.write(ss.read());
}

You may get better results if you do not nest the read and write function calls as you did.  That is, read everything then write everything.

The reason for this is that softwareserial.read() returns 1 character.  If you immediately turn around and pass that character to softwareserial.write() you will devote the resources of the processor to sending that character.  In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.

That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the Mega 2560 processor on the Arduino Mega.

Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater.  A hardware serial port or UART can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.


Arduino motor shield orange/white pin usage I have an Arduino motor shield like this one plugged into my Mega board.

I would like to know some more information about the orange and white pin blocks on the board. The Arduino website has the following information, but it doesn't give any explanation of what is best to use them for or which pins are mapped to the data pins etc.

TinkerKit connectors for two Analog Inputs (in white), connected to A2 and A3.
TinkerKit connectors for two Aanlog Outputs (in orange in the middle), connected to PWM outputs on pins D5 and D6.
TinkerKit connectors for the TWI interface (in white with 4 pins), one for input and the other one for output.

What I want to do is connect a servo up to the board and was hoping I could use one of the orange OUT blocks. I haven't been successful in finding any examples of this which leaves me in doubt as to whether it is possible or not. I would just plug it in, but I'm afraid of frying the shield/mega/servo. Probably an irrational fear, but I can't afford another one of any at the moment!

I don't know which pins in the block are assigned to the data, vcc and out, so if anyone know I would be grateful for the answer.

Also, just because it is annoying not to understand, what are the TWI connectors for?

I hope this isn't too general a question as I could really use some answers!

...which pins are mapped to the data pins etc.

The shield page provides a schematic

I would like to know some more information about the orange and white pin blocks on the board

These have the reference printed on the board

TWI IN and TWI OUT
They are the same and are both connected to the same I2C pins of Arduino (SCL, SDA). They are intended to help in case you want to connect more than one device.

OUT 5, OUT 6
Connected to Arduino pins 5 and 6 (PWM outputs)

IN 2, IN 3
Connected to Analog in A2 and A3

The power outputs of L298 intended to drive the motor are the blue screw connectors.