text:
Arduino not running code without connection to PC via USB
I have an Arduino UNO and esp8266 connected to it. Both devices has separate power lines. Each connected via USB cable, for Arduino USB used as power line and standard firmware uppload line, for esp8266 only as power suppli line. If I connect all to computer's USB ports, everything working fine. But, if I connect Arduino to separate charger that has USB port, then Arduino not running code. I can see it by Serial interface work, because code using it intensively, and when I'm turning Arduino on the RX and TX lines are down all the time, that I think indicates, that code is not running, and Arduino in boot mode, somehow.
I've made a search through same issues and nothing helped from theirs suggestions. I tried to pull RX line to GND through resistor, to make sure that there are no noise on the line, added capacitors for power supply line, to make exclude pulsations on the line. But nothing helped.
Arduino not running code independently from esp8266. I tried to run Arduino separately, without any other connections, but it not helped. Still not running.

Diagrams would help ("a picture is worth 1000 words...") but it seems like everything regarding the ESP8266 can be removed from your question because at the end, you say: "I tried to run Arduino separately, without any other connections, but it not helped. Still not running." You didn't say exactly how you know it is not running. Overall, I suggest to simplify your test and clarify your question; add diagram / photos of minimum non-working config; remember not all "chargers" are good quality; this topic might be better moved to the Arduino SE, as they have more Arduino experience there.

This problem happened to me when I first started dealing with electronics.
Power supplies connected to the AC line usually have an "isolated transformer" inside them. What this does is both to lower the AC voltage down to a more operable AC voltage (which is then rectified to DC voltages) and also protect the user/equipment/(your house) in case of failure of the power supply (AC 230/110 V will seriously damage you!). You see, the transformer's output is "isolated" from the AC line.
Because of this, every power supply connected to the AC line has an "isolated/separate" GND and VCC level. So, if you wanted to power and use two or more PCB's together using separate power supplies, then you need to connect all of their (power supplies) GND's together so that you have a "common ground".
In your case, powering both  "Arduino UNO and esp8266" from the same computer works because the computer is fed from a single power supply and that the computer's GND wires on the USB line are "common" i.e. not isolated.
When you power your Arduino from a separate supply, your Arduino and esp8266 has a different GND level so the RX and TX line between them must be floating. To solve your issue, connect a wire from Arduino GND port (it is next to Analog read pins) to Esp8266 GND pin (somewhere suitable, of course).

Have you made sure that the ground of both the arduino as well as esp8266 are connected together? Also since you are using esp8266 you must have connected it to rx and tx pins. Make sure you remove it while uploading the code and connect it afterwards.

Failure to provide common ground is almost certainly the reason. Connecting both devices to the same PC will most probably connect grounds together via USB GND.

This answer can apply in some cases, but it does not seem to fit with the last part of the OP's question: "I tried to run Arduino separately, without any other connections, but it not helped. Still not running." So if a separately-powered Arduino without any other connections isn't working (not clear how the OP decided that...) then missing ground connections between devices cannot be the cause, as they would not be needed when there is no other device involved :-)

@DmitryGrigoryev, Thanks a lot. This helped. Could you explain how? I have me own suggestions, but don't want believe them.

I believe this is happening because of electrical interference between wires. If you are running somewhat long wires (100mm or longer), every wire you run acts as an antenna that can either transmit or receive singles to/from other close wires. If you separate your wires or better yet, shield your data wires from each other, your issues should resolve.
Signals out of an Arduino board are very weak and are easily susceptible to interference from your environment such as motors, radio waves, wifi, or even a microwave oven running.
Either shield your data wires, make your wires shorter, or add circuitry that can transmit/receive signals over long distances, even if it's only 100mm. At 3.3volts with very low amps doesn't take much to noise up your data signals.
Hope this helps!


text:
Electrostatic Discharge Protection on Arduinos
I have been using Arduino for quite some time without providing any kind of ESD protection. Does the Arduino have on board ESD protection?

What does the documentation tell you?

Check the Arduino documentation, that will probably tell you with words. Alternativly you could check the schematic of the Aruduino board you're using, and see what it has there.

Almost certainly not. What's the point in protecting the inputs to a bare board where people can touch any point? You can't protect every single trace on the board, that would result in a system where ESD protection took up half the board area.

ohkk, I did check the documentation and schematic of arduino but such a thing is not mentioned there. But, I came across the datasheet of atmega 328 maybe it will give me a better insight. Thanks for your comments

Does the arduino have on board ESD protection? The chips on the board will have ESD protection. As long as you're not purposely exposing the board to excessive ESD events, that protection is enough. Next time, do more research on what is ESD, what does a protection circuit look like etc, what does ESD mean to a user like me. Before asking here.

Just use ESD protection, better safe than intermittent

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How do I repurpose Arduino's reset button
Is there a way to repurpose the reset button for the code, like an on-board button? I don't need it to reset, but it would be useful to make it run through a list of RGB LED cycles.

You can store the current state in EEPROM, and detect when the board has been reset (there is a special register for it). So at startup you load the state back from the EEPROM and see if a reset has occurred. If so select te next pattern (and save that to the EEPROM).

If you just want the reset button to change the program mode, the
simplest thing would be to let the button reset the Arduino and switch
modes each time your program restarts. Then you do not need to change
the fuses or get a high voltage programmer. The code would look like
this:
void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    // etc...
}

There is just a small issue here: when the program starts, all the
global variables (like mode above) are supposed to be initialized by
the C runtime. This can be avoided by using a non-standard feature of
gcc: if you request the variable to be stored in the special .noinit
section, then it will not be initialized. Here is the program I used to
test this idea:
const unsigned int NUMBER_OF_MODES = 5;

__attribute__((section(".noinit"))) unsigned int mode;

void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    Serial.begin(9600);
    Serial.print("Current mode: ");
    Serial.println(mode);
}

void loop() {}

Now, each time I press the reset button, it goes to the next mode among
(0, 1, 2, 3, 4). The main drawback compared to using a regular input is
the delay added by the bootloader, which is slightly more than one
second.
A word about the cold boot initialization: the RAM is not initialized
by the hardware and contains essentially random bits. This means you
cannot count on mode having initially a valid value. This is why:

I am testing for ++mode >= NUMBER_OF_MODES rather than
++mode == NUMBER_OF_MODES, as the initial mode could be way larger
than NUMBER_OF_MODES
mode is an unsigned integer, otherwise I would need to also test for
it being negative.

Reset button is connected to the reset pin of Atmega328P-PU. So, when you press that button, the reset pin gets a LOW, which resets the chip!
Here is the thing, yes, you may disable the reset pin to use it as general I/O. However, if you disable it, you will not be able to reprogram your Arduino anymore! You'll effectively brick your Arduino...
By the way, yes you do need it to reset. When you program your arduino, the IDE sends a reset command from your PC via USB to reset your Arduino. When Arduino is resetted, bootloader looks for an incoming sketch, which is provided by the IDE and so on....

As noted in other answers, if you re-purpose the reset pin, PC6, by programming the RSTDISBL fuse, then some of the usual methods of loading a program into flash memory are made unavailable.  Specifically, the usual serial-port programming using Arduino's Optiboot depends on the chip resetting upon demand.  So does ISP programming, as done for example using a USBasp or similar device.
However, parallel programming remains available.  This requires an STK500 or similar, or can be simulated using another Arduino.
Here are a couple of references from Atmel's doc8271 datasheet for ATmega48A/PA/88A/PA/168A/PA/328/P:

§14.3.2 Alternate Functions of Port C
  “When the RSTDISBL Fuse is programmed, this pin [PC6] functions as a normal I/O pin, and the part will have to rely on Power-on Reset and Brown-out Reset as its reset sources. ...”
§28.6 Parallel Programming Parameters, Pin Mapping, and Commands
  (Describes Parallel Programming wiring and protocol)

As it can be inconvenient having to hook up a parallel programmer to load new programs, instead of programming the RSTDISBL fuse you could modify the hardware.  You would cut the trace from the reset switch close to the switch (for example, lightly touch the trace with a fast-spinning 1-mm drill bit, using a small Dremel or drillpress), then run a fine jumper wire from the switch or its trace to an input pin.
This method leaves all the other reset-circuit stuff (pullup resistor to 5V, capacitor to DTR) in place so that ISP programming would work without change.

I concur with everything Maximus has said.
It is possible - you can change the reset pin to be a normal I/O pin.
To do so you will need to program one of the ATmega328P's fuse bits. For that you will need an ISP programmer like the AVRISPmkII or Atmel ICE. You will also need a program such as Atmel Studio or AVRdude.
The reset disable fuse is part of the high byte fuses. First you will need to calculate high fuse. I use eleccelerator Fusecalc for this
Based on my boards.txt file, the default for the high fuse on the Arduino Uno is DE. Adding the reset disable fuse makes it 5E.
Program the fuse using Atmel Studio or AVRdude using your ISP programmer.
Complete Fusecalc settings

The other answers weren't working for me (on an ATmega168), but I found this solution:
const unsigned int NUMBER_OF_MODES = 5;
int * mode;

void setup() {
    mode = (int *) malloc (sizeof (int));

    // At startup, switch to the next mode.
    if (++(*mode) >= NUMBER_OF_MODES) (*mode) = 0;

    Serial.begin(9600);
    Serial.print("Current mode: ");
    Serial.println((*mode));
}

output:
Current mode: 0
Current mode: 1
Current mode: 2
Current mode: 3
Current mode: 4
Current mode: 0

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Power issues with RFDuino
I am new to hardware, I have always used plug and play shields to accomplish simple projects. A while back I purchased RGB LED Shutter Shades from Macetech. I got the hacker version thinking I would add a RFDuino and use that to power the glasses and receive commands from my iPhone. I found out that the glasses needed 5v and the RFDuino could only do 3V. So i used a Sainsmart Nano v3 to control the LED's and I added a RFDunio to receive commands from my iPhone, the RFDuino is powered by the Nano.
The issue I am having is that when Im using an external battery pack, the kind you use to charge your phone, I'm guessing the power is not consistent enough and the RFDuino drops its connection to my phone. When I run the glasses using my computers USB port I do not have that problem.
My question: Is there something I can add to my circuit to make this inconsistency with my power stop happening?

I am the designer of the RGB Shades and co-own macetech LLC. The RFDuino specifications claim only 18mA on transmit and receive, so there should not be a current draw issue from that module.
Known power issues with the RGB Shades include high current draw on startup. They can pulse about 1.3 amps (the blue flash) before your software sets them to a more reasonable level. Most USB power packs made today can handle 1.0 amps, some can supply more, but it's still common to find packs limited to 500mA...that would be one thing to check.
Since you are using your own code, please also note that our default code on the controller-included RGB Shades sets the maximum brightness to about one-quarter the actual maximum brightness of the LEDs. This is done to conserve power as well as reduce brightness to non-blinding levels. If your code is attempting to operate at normal brightness, please be aware the RGB Shades could draw up to 4 amps.
The best way to detect the problem would be to get a multimeter and compare the supply voltage when connected to your computer and when connected to the USB power pack.

Upon closer inspection both of the battery packs I have were 500mA. Im thinking that must be the issue. Thanks.

Wireless modules usually draw bursts of big currents in small amounts of time. For example ~1000mA for 1 uS (microseconds). Their overall power consumption can be low, however.
Perhaps, your external battery pack has a low current output which can not supply the burst current that RF module needs, but your PC is sufficient enough.
I would suggest adding capacitors (their size and amount depends, but put some big ones like 10000 uF in parallel and observe) so the burst current is compensated from the capacitors.
Make sure that those battery packs have enough current (hence, power) to power your RF module.
You can always use high rated battery packs such as LiPo's used in RC planes/copters, but be aware, they react badly when shorted so it may not be a good idea to use those batteries on your glasses...

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How can I maintain switch state when in sleep mode?
I'm using a esp8266 to build a remote control to power a gas fireplace. I'm using this guide to try and maximize battery life.
The concept is the controller uses its built in WiFi to access a RESTful API on a remote server; If the API discovers"1", it should close a switch and the fireplace turns on. If the arduino reads a "0" via the API it opens the switch and the fireplace turns off. After discovery and performing the required action the unit calls Deepsleep and shuts off for ten seconds, whereupon it powers up and the cycle repeats itself again.
I just realized that if the controller powers off, I don't know what happens to the switch. If the fireplace was turned on,  what happens when deep sleep starts. Is there a way (special switch?) that maintains its state in deepsleep mode?

Please edit question to clarify meaning of  “I'd it sees”

Save the last state in EEPROM. Or, since you are using a remote server, store the state on the server.

@Gerben I think he means the physical state of the IO pin - when in deep sleep the general consensus (though I haven't found a definitive answer) is that the GPIO pins will lose their drive state when the chip goes to sleep.

@Majenko that indeed makes more sense.

Yes, there is such 'switch'. You could use JK Flip-Flop to hold the last output. JK Flip-Flop has J, K and clock inputs and If J and K are different then the output takes the value of J at the next clock edge.

Wouldn't the flip-flop require power all the time, reducing the benefits of the deep sleep mode?

ESP8266 draws from 50 up to 200 mA while J-K flip-flop draws 5-6 mA + less than 100 µA per input. Everything reduces the benefits of the deep-sleep mode, even the ESP8266's counter which is still running during deep sleep.

So that's a "Yes, but the difference is marginal"? I was asking for enlightenment, so thanks for the info.

Well, the difference between the deep sleep mode and 'deep sleep + J-K flip flop' is indeed considerable because the current draw in deep sleep mode is only about 10 µA but 5-6 mA might still be acceptable when using batteries because a few seconds of ESP8266 drawing full power everytime it wakes up will probably drain the battery more than J-K flip-flop drawing a few mA continuously. Depends on waking up intervals and for the remote control to be acceptably responsive ESP has to wake up quite frequently.

You can get a latching relay. These come in two flavours - Unipolar, where you energise one pin to turn it on, and energise the other to turn it off, and Bipolar, where the direction of the current through the coil turns on or turns off.
Unipolar is easier to drive since you just need two transistors, diodes and resistors. Bipolar is harder, since you need a H-bridge (motor driver), but requires less wires to connect it up (2 as opposed to 3).
In both cases it is just a short pulse that is needed to switch the relay into a different state - there is no need to maintain the output, so is ideal for deep-sleep mode where everything is turned off except the RTC.

During my Deep Sleep experiments I noticed that a couple of pins held their state through a Deep Sleep reset, but I didn't write it down anywhere.  Simple observation suggests that any of the pins that wiggle during boot will NOT be retained, which leaves just GPIO4 and GPIO5 for likely candidates.  Try it and see!
During Deep Sleep the pins hold their state, although they're using weak FETs equivalent to 2uA source/sink current.  The boot cycle following Sleep clobbers most of the GPIOs.  Sigh.

authors: Сергей Корягин


text:
Which key is KEY_LEFT_GUI?
This might be a very simple question but I don't know which key represents KEY_LEFT_GUI on my keyboard. I thought it was the windows key but when I program Arduino Micro to execute it. Run does not open and it prints powershell on the "Search Programs and Files" section in Windows7 VM.
  Keyboard.press(KEY_LEFT_GUI);
  delay(1000);
  Keyboard.press('r');
  delay(1000);
  Keyboard.releaseAll();

  delay(500);

  Keyboard.print("powershell");
  typeKey(KEY_RETURN);

KEY_LEFT_GUI is the left Windows key. I think the problem may be that your code is only holding those keys down for microseconds. You need to give the computer a little bit of time to recognize the keypresses because it's expecting a human using a keyboard, not a microcontroller running at 16MHz. Try adding a delay before Keyboard.releaseAll();.

it's still just opening the start menu and typing it there instead of opening run I added a 1000 delay before releaseAll and a 1000 delay above press('r') but it is only detecting the windows press not the r

I guess I just didn't know how fast a millisecond really is. I changed the delay to 4000 and it's working now.

I know it's a late answer, but you can use to open the run window:
Keyboard.press(KEY_LEFT_GUI);
  Keyboard.press(114);
  Keyboard.releaseAll();
And yes, as per1234 says, KEY_LEFT_GUI is the left windows key


text:
Cannot run arduino as web client
I have ethernet shield mounted on arduino mega, I am able to run it as server but when i try to run it as client it doesnt work , most of the time it assigns itself 255.255.255.255 ip address which i get to know as i am printing from my sketch using Ethernet.localIP()  it sometimes randomly works but then it does nt establish connection with server, I have double checked there is no firewall on my router that can block arduino ethernet web client.
#include "Ethernet.h"
#include <SPI.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
//IPAddress ip(192, 168, 1, 177);

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,177);

byte subnet[] = { 255, 255, 255, 0 }; //assigning subnet mask
byte gateway[] = { 192, 168, 1, 1 }; //assigning gateway

EthernetClient client;
char server[] = "192.168.1.3"; // IP Adres (or name) of server to dump data to

String data;

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

  while (!Serial) {
    ; //wait for serial port to connect. Needed for native USB port only
  }
  Ethernet.begin(mac, ip, gateway, subnet);

  Serial.print(F("connected. My IP is "));
  Serial.println(Ethernet.localIP());
  // give the Ethernet shield a second to initialize:
  delay(1000);
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  delay(200);
  tempInC = DHT.temperature;
  humidity = DHT.humidity;
  Serial.print("Temp: ");
  Serial.print(tempInC);
  Serial.print(" Humidity: ");
  Serial.println(humidity);
  if (client.connect(server, 80)) {

    // Make a HTTP request:
    client.print(F("GET /arduino/add.php?temp1="));
    client.print(tempInC);
    client.print(F("&hum1="));
    client.print(humidity);
    client.println(F(" HTTP/1.1"));
    client.print(F("Host: "));
    client.println(server);
    client.println(F("Connection: close"));
    client.println();

  }
  else {
    Serial.println(F("connection failed"));
  }

  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  else {
    Serial.println("Client not available");
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  //  delay(60000); // WAIT FOR A MINUTE BEFORE SENDING AGAIN
  delay(10000);
}

Here is the output of what I get from above sketch
connected. My IP is 255.255.255.255
Temp: 26.00 Humidity: 63
connection failed
Client not available

Even when it gets correct IP assigned which I am setting up in the sketch the connection to server fails.
I am very upset not being able to run client. Please help.

This could be an SD card SPI bus issue.
Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are
using both peripherals in your program, this should be taken care of by the corresponding libraries. If
you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do
this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a
high output.

Check the Arduino shield datasheet.

Changing pin mode:
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);

So that means to be able to use both I would have to flip flop between SD card and w5100 ?

Yes most probably you will make pin 4 OUT when you will not use then 4 IN when you will be using it. And i think it is preferable not to use pin 4 for any i/o data. Like don't put your DHT on pin 4. I can see from your code you are using pin 8 so its fine.

thanks that helps, however even after it is connected I see it is not pushing data based on the web client call to URL as shown in above post !

@Ciastopiekarz try changing the GET method to POST.

Done that already

I don't know what the problem is, but I can see some issues with your code.  Perhaps fixing them will make it work, or at least get you closer.
Reading between the lines in your code, it looks like you are expecting an IP address from DHCP.  You won't get that, according to the documentation because you are specifying one.  Just so that you know.
You're calling the four-parameter version of Ethernet.begin() but using an invalid set of parameters.  You're probably meaning to use one of these:
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);

or if you want to use DHCP (which I'd recommend, if you can, because managing them yourself is a pain), just use
int success == Ethernet.begin(mac);
if (success) { /* it worked */ }

Lastly -- and this is a guess --  I wonder if adding a delay(1000) after Ethernet.begin() would change the behaviour.  It's not really a solution, but it might help you debug.

I removed SD card I inserted yesterday night, and then it seems to work but not able to insert into db also instead of using server port 80 I used port 443, since I have HTTP to HTTPS redirection on apache web server running at home.

I don't understand the significance of what you're saying. New problems for a new question perhaps?

however , atleast you can tell me why removing SD card make it works.

I can't, sorry.


text:
How to merge HCSR04 code with DF Player mini mp3
As the title says, I have a problem to merging the HCSR04 code with DF Player mini mp3 codebases so that they are working together in the one sketch.
The idea is when the ultrasonic sensor reads a certain range, it will trigger a specific mp3 files via the DF player.
I'm using 5 Ultrasonic sensors, and I wanted each sensors to trigger different mp3 files.
Ultrasonic code:
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int trigPin3=6;
int echoPin3=7;

int trigPin4=8;
int echoPin4=9;

int trigPin5=10;
int echoPin5=11;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
  pinMode(trigPin4, OUTPUT);
  pinMode(echoPin4, INPUT);
  pinMode(trigPin5, OUTPUT);
  pinMode(echoPin5, INPUT);

}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= duration2/58;

long duration3, distance3;
  digitalWrite(trigPin3, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin3, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin3, LOW);
  duration3 = pulseIn(echoPin3, HIGH);
  distance3= duration3/58;

  long duration4, distance4;
  digitalWrite(trigPin4, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin4, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin4, LOW);
  duration4 = pulseIn(echoPin4, HIGH);
  distance4= duration4/58;

  long duration5, distance5;
  digitalWrite(trigPin5, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin5, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin5, LOW);
  duration5 = pulseIn(echoPin5, HIGH);
  distance5= duration5/58;

  Serial.print (distance1);
  Serial.print (",");
  Serial.print(distance2);
  Serial.print(",");
  Serial.print(distance3);
  Serial.print(",");
  Serial.print(distance4);
  Serial.print(",");
  Serial.print(distance5);
  Serial.println(",");
  delay(100);

}

DF Player code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

void setup()
{
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30
}

void loop()
{
  static unsigned long timer = millis();

  if (millis() - timer > 2000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 3 second.
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

Please clarify your question.

How to merge these 2 codes, I tried many ways but can find the right one, i'm literally new to writing codes like this

I've refactored it a bit, to remove the need to repeat the same code, 5 times, for 5 sensors.
#include "Arduino.h"
#include "SoftwareSerial.h"

#include "DFRobotDFPlayerMini.h"

const byte SENSOR_COUNT = 5;
byte triggerPins[SENSOR_COUNT] = {2,4,6,8,10};
byte echoPins[SENSOR_COUNT]    = {3,5,7,9,11};

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX

DFRobotDFPlayerMini myDFPlayer;

void printDetail(uint8_t type, int value);

void setup()
{
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);

  for( byte i=0; i<SENSOR_COUNT; i++ )
  {
    pinMode(triggerPins[i], OUTPUT);
    pinMode(echoPins[i], INPUT);
  }

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30

}

int currentSound = -1;
void loop()
{

  for( byte i=0; i<SENSOR_COUNT; i++ ) // loop through all distance sensors
  {
    if( detectPresence(i) ) // check if there is an object near it
    {
      if(currentSound!=i) // check that it's a different sensor than the one that was last triggered
      {
        Serial.print("play song number ");
        Serial.println(i);
        myDFPlayer.play(i+1); // play song nr `i+1`
      }
      currentSound = i;
    }
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }

}

// detectPresence will return TRUE if there is an object close to it.
bool detectPresence(byte sensorNr)
{
  if( sensorNr>=SENSOR_COUNT )
    return false;
  long duration, distance;
  //digitalWrite(triggerPins[sensorNr], LOW);  // Added this line
  //delayMicroseconds(10); // Added this line
  digitalWrite(triggerPins[sensorNr], HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(triggerPins[sensorNr], LOW);
  duration = pulseIn(echoPins[sensorNr], HIGH);
  distance = duration/58;

  return distance<30;// choose your own value here, from which distance it should trigger a sound
}

void printDetail(uint8_t type, int value){

  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

Thank you very much Gerben! this works absolutely perfect, buy yet there is one last problem, sensor #1 now trigger mp3 player to play "song #0", how do i switch it so sensor #1 plays song #1, sensor #2 plays song #2 and so on? thank you for all your help man! appreciate it much!

It should already do that! Doesn't it? There is only a problem if multiple sensors are triggering at the same time.

From what i'm seen and heard, when sensor#1 triggered it plays song#0 and its not playing anything since the DFPlayer files start with 1, not 0, or something, correct me if i'm wrong but it does plays song#0, and nothing come out, and the first file on my mp3 list played when sensor#2 triggered. so it become Sensor#1 Plays Song#0, Sensor#2 plays Song#1... Sensor#5 plays Song#4

I've changed myDFPlayer.play(i); to myDFPlayer.play(i+1); in the code above. That should fix that.


text:
SPFD5408 for TFT in Arduino Due
I have interfaced HC024071 TFT Display with Arduino Due using SPFD5408 Adafruit library. It works perfect.
But using the same library with Arduino Due (with pin connections modified as follows):
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
//   D0 connects to digital pin 8  (Notice these are
//   D1 connects to digital pin 9   NOT in order!)
//   D2 connects to digital pin 2
//   D3 connects to digital pin 3
//   D4 connects to digital pin 4
//   D5 connects to digital pin 5
//   D6 connects to digital pin 6
//   D7 connects to digital pin 7

But unfortunately, errors occur (which made me guess Due is incompatible with the same)
Build options changed, rebuilding all
In file included from C:\Users\Arun Baby\Desktop\test\sketch_dec16c\sketch_dec16c.ino:2:0:

sketch\TFTLIB.H: In function 'void Draw_Welcome_Screen()':

sketch\TFTLIB.H:154:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S",55,150,BLUE,3);

                                    ^

sketch\TFTLIB.H:155:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zone Adaptive Response System",25,180,BLACK,1);

                                                           ^

sketch\TFTLIB.H:157:57: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Touch anywhere to continue!",30,280,BLACK,1);

                                                         ^

sketch\TFTLIB.H: In function 'void Draw_Menu()':

sketch\TFTLIB.H:166:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S Main Menu",120,300,WHITE,1);

                                                ^

sketch\TFTLIB.H:168:42: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Driving Mode",20,45,0x1220,2);

                                          ^

sketch\TFTLIB.H:169:46: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zones Supported",20,135,0x1220,2);

                                              ^

sketch\TFTLIB.H:170:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",20,225,0x1220,2);

                                       ^

sketch\TFTLIB.H: In function 'void Draw_Settings()':

sketch\TFTLIB.H:179:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",160,300,WHITE,1);

                                       ^

sketch\TFTLIB.H:181:43: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Re-Caliberate",20,45,0x1220,2);

                                           ^

sketch\TFTLIB.H:182:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("GPS Lock",20,135,0x1220,2);

                                       ^

sketch\TFTLIB.H:183:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("BACK",20,225,WHITE,2);

                                  ^

sketch\TFTLIB.H: In function 'void Manual_Recaliberation()':

sketch\TFTLIB.H:189:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:191:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 1",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:192:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the BLUE dot...",40,250,WHITE,1);

                                                            ^

sketch\TFTLIB.H:198:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:200:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 2",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:201:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the RED dot...",40,250,WHITE,1);

                                                           ^

sketch\TFTLIB.H:209:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:211:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 3",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:212:62: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the YELLOW dot...",40,250,WHITE,1);

                                                              ^

sketch\TFTLIB.H:224:61: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Recaliberation \n    Complete",30,100,WHITE,2);

                                                             ^

sketch\TFTLIB.H:227:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("BACK",20,225,WHITE,2);

                                    ^

In file included from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_Adafruit_TFTLCD.cpp:30:0:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\pin_magic.h:306:33: warning: backslash and newline separated by space [enabled by default]

   #define read8inline(result) { \

 ^

In file included from C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/pins_arduino.h:20:0,

                 from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:6:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp: In member function 'TSPoint TouchScreen::getPoint()':

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:61:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xp_port = digitalPinToPort(_xp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:62:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t yp_port = digitalPinToPort(_yp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:63:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xm_port = digitalPinToPort(_xm);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:64:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t ym_port = digitalPinToPort(_ym);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:77:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(yp_port) &= ~yp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:78:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(ym_port) &= ~ym_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:86:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xp_port) |= xp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:87:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xm_port) &= ~xm_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:102:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:106:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) |= yp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:125:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:129:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(ym_port) |= ym_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:133:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) &= ~yp_pin;

     ^

Is it actually true? Is SPFD5408 completely incompatible with Due?
Trying out UTFT Library with Due gave errors and with Uno, Blank white screen.
Is there any library that is compatible with Due then?

Yes, that is true. It looks like it tries to do some low-level port manipulation for speed, but it doesn't know how to do that on a Due since it's a completely different beast.
You could always read the datasheet and look at the initialisation code (the hardest part to work out yourself) and roll your own code to control the TFT - it's not actually that hard usually.


text:
Why do I get access denied when I do have mysql root user added to grant all privileges?
I am using the below mysql example sketch to upload data directly to mysql db.
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress server_addr(192, 168, 1, 3);
//char server_addr[] = "192.168.1.3";

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

char user[] = "root";
char password[] = "secret";
char INSERT_SQL[] =
 "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

void setup() {
  Ethernet.begin(mac_addr, ip);
  Serial.begin(9600);
  delay(1000);
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password))
  {
    delay(500);
    Serial.println("Connection Successfull,inserting to database.");
     /* Write Hello, World to MySQL table test_arduino.hello */
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

I am getting the error in serial Monitor:

Connecting...
Error: 76 = Access denied for user
  'root'@'192.168.1.177' (using password: YES).
Connection failed.

even when I have all prvialages on root user for the ip of client !
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT host FROM mysql.user WHERE User = 'root';
+---------------+
| host          |
+---------------+
| 127.0.0.1     |
| 192.168.1.177 |
| ::1           |
| localhost     |
| raspberrypi   |
+---------------+
5 rows in set (0.00 sec)

I ran the following query :
mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

and got the below result !
+-----------+----------+------+------------------+
| ip        | hostname | port | current_database |
+-----------+----------+------+------------------+
| localhost | ceres    | 3306 | test_arduino     |
+-----------+----------+------+------------------+
1 row in set (0.00 sec)

however I am trying to access the test_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have 192.168.1.177 as well ? if so How do I insert ip to database test_arduino ?
then what am I missing ? please help.

Did you do flush privileges; after grant?

Yes off course , I did flush permissions.

Try to investigate if this is the case.

How do I check on stored procedures ? I also later grant on 'root'@'%' which shows up in list of host shown above. But I m not sql guy don't know how to get rid of host from above list like raspberrypi host is not even there, I just realised ceres host is missing

For that you can find notes here and here.

Are you sure there isn't a firewall issue here?

Well, @Gerben if that was a firewall issue I would have not got that error message in serial monitor

My last bought w/:mysql access denied" had to do with where I was logging in from.  Perhaps you can check by using the same credentials on the machine you are running mysql on.  If that works, then start looking at how you have setup the mysql security w.r.t. "trusted" IP addresses. (oh, I see you tried 'root'@'%'.  Just the same, try logging in from the mysql host machine anyways.)

@Chupo_cro i do not see any precedure definer if I run the command , show procedure status; however I ran the query SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database; while test_arduino database selected, and it did not listed 192.168.1.177 ip from which I am trying to insert !

I finally figured out
By default it may proabbly have an IP address 127.0.0.1 bind to the 3306 port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP 192.168.1.145. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP 192.168.145 bind to 3306 port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN.
Then you login to mysql server , and create a user :
CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then you grant privileges as shown below.
GRANT ALL ON *.* TO 'myuser'@'192.168.156';
GRANT ALL ON *.* TO 'myuser'@'%';

Important Note:  the ip address shown in above mysql queries 192.168.156 is the ip address of my ethernet client establishing connection with database on mysql remote server.
Thats it.


text:
I2C and SPI at the same time?
I would like to ask a question relating to the following communication setup:
STM32 -- Arduino Pro Mini -- ADNS3080 sensor
The interface between STM32 -- Arduino is I2C and the interface between Arduino Pro Mini--ADNS3080 is SPI.
I have tested the communication between the STM32 and the Arduino Pro Mini, and between the Arduino Pro Mini and the ADNS3080 sensor. Both of them work fine; I can successfully send and receive data in both cases.
Now, I want to read the register of the ADNS3080 sensor using the STM32. First, I start an I2C communication between the STM32 and the Arduino Pro Mini, then I send the register address of the ADNS3080 to the Arduino Pro Mini. The Arduino Pro Mini reads the register address and in the same function starts a communication, using SPI, with the ADNS3080 sensor.
But I receive I2C errors in the STM32. Is it possible to use I2C and SPI at the same time? Do I have to introduce delays between the I2C and SPI commands?
Regards, Ali

I feel like their interrupts would be bumping into each other.

I smell a real time issue but not sure. Is the I2C finished before stating SPI?

They are on separate busses, so yes you can do both in one program. However if one is being triggered by an interrupt from the other and it itself relies on interrupts there may be a problem there. You should have one interrupt telling your main program it's time to do the second operation rather than run it direct from inside an interrupt.

Are you expecting that the Arduino can execute the SPI transaction and return the data to the STM32 in the same I2C transaction? That isn't likely to work. You're going to need some sort of flow control or handshake mechanism that tells the STM32 when the data is actually available. This could be anything from clock stretching to splitting it into multiple I2C cycles in which the STM32 polls the Arduino for status.

You will get better answers if you post your code. You are asking about errors in unposted code, with no schematic. Any answers thus are general, and largely guesswork.

I feel like their interrupts would be bumping into each other - interrupts don't really "bump into each other". They are executed in priority order in an orderly way.

I would like to inform you all that, a few days back, I managed to solve my problem by following the suggestions made by @Majenko. Thanks everyone for the help.

is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

Do I have to introduce delays between the I2C and SPI commands?

No you don't.

Your Arduino code probably needs to implement clock stretching as an i2c slave. This tells the master to chill for a little while as the slave does some work to get an answer.


text:
Random analog input
I'm trying to build a midi controller that takes the input from a photoresistor and a reed switch anemometer and outputs midi signal.
I've constructed the circuit as in the diagram below but when I test the inputs I receive only random numbers from analog input 3. I get a clear signal on A5.
I'm confused as to what's going on. I've seen other solutions to this problem mention the circuit not being grounded properly but as far as I can see I have the correct grounding.

220Ω is incredibly small for your inputs. 10K is better. Especially for the LDR.

Could you post a picture of your setup? The schematic looks fine, so there might be an error in your wiring, maybe.

Often problems are code, hardware or both. Can you please post your code? (Edit your question to do that. Indent it with Ctrl+K so it looks nice).

Thanks for the input guys. Originally I was finding that my circuit, which i had soldered myself, was not working. I rebuilt it on a bread board and it is working fine now, must have been an issue with my soldering!

Random numbers usually mean that the pin is floating (i.e. not touching anything)
You need to check your connections to A3.
Try this:

Remove the LDR and R6. Check their resistance using multimeter. (To see if they are not burnt etc.)
Connect R6 to its place. You should get 0 V (0) because R6 is connected to GND.
Remove R6 and put it in place of LDR. Now, you should be seeing 5V (1024) on A3.
After you complete this for R6, try it with using LDR only. You should see same results (Make sure LDR has some light on it to lower its resistance)
Put everything back in place. You should not be seeing random values because now everything is properly connected.

If you are still seeing random values, then that LDR may be disfunctional. Get another one.
Oh and one more thing, make sure LDR illumination does not change while you're getting readings.


text:
SIM800L GSM Module, no network signal RSSI
I am using a GSM 800L module to send SMS messages. When I test the module with Arduino, it shows a 0 : -115dbm signal strength.
So basically there is no signal. SIM800L is a quad-band GSM/GPRS module that works on frequencies GSM850MHz, EGSM900MHz, DSC1800Mhz, and PCS1900MHz.
My SIM card carrier uses the frequency bands GSM 900, GSM 1800 for 2G-capablities.
What might be the possible reasons my GSM module doesn't work properly with my SIM card? I have tried different locations, still no signal.
The code I use for testing is provided by Adafruit-Fona.

Where do you live? 2G has been switched off in some countries.

Check antenna cable/connection, maybe shorted?

there is no cable for the antenna. I don't really what is the problem

Please can you accept your own answer (using the green tick below the voting buttons) in order to remove your question from the unanswered list. Thank you.

The Problem was that I used 5 V Dc to power the module , it worked but in order to function I must use lithium battery. ( its mentioned in the manual)

Please can you accept your own answer (using the green tick below the voting buttons) in order to remove your question from the unanswered list. Thank you.


text:
How do I control arduino uno multiplexed digital pin (using HC74595)
Edit:
I moved the whole initial post to avoid misunderstanding and confusing everyone, sorry
after all the reading i came up with this:
this is my code for ultrasonic sensor that going into digital pins in my arduino:
int trigPin1=2;
int echoPin1=3;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

  Serial.print (distance1);
  Serial.print (",");
  delay(100);
}

and this is the idea i wrote to set the "extra digital outputs" on the 595 chip:
int DS_pin = 8;
int STCP_pin = 9;
int SHCP_pin = 10;

void setup()
{ // put your setup code here, to run once:
  pinMode(DS_pin, OUTPUT);
  pinMode(STCP_pin, OUTPUT);
  pinMode(SHCP_pin, OUTPUT);
  writereg();
}

bool registers[8];

void writereg()
{
  digitalWrite(SHCP_pin, LOW);

  for (int i = 0; i<=7; i++)
  {
    digitalWrite(STCP_pin, LOW);
    digitalWrite(DS_pin,registers[1]);
    digitalWrite(STCP_pin, HIGH);
  }
    digitalWrite(SHCP_pin, HIGH);
}

void loop()
{// put your main code here, to run repeatedly:

}

now if you guys have a little time to check it, and tell me what should i wrote so the ultrasonic sensor will be working with the 595 chip's outputs?
Let say im going to put the Trigger pin into Q0 and Echo pin into Q1
thanks in advance

Can you clarify what you mean by "the extra slot"? What extra slot?

by extra slot i mean extra digital input, because im running out of digital input on the actual board, so i've been searching and found out that you can pull "extra" digital input with multiplexing it using IC - HC74595

You mean outputs, right?  As in "extra digital output" as the 74HC595 has 8 digital outputs.

Yes sir, output, my bad

i want to use the extra slot from HC74595 - what extra slot on the HC74595? im running out of digital input on the actual board - what "actual board"? Can you post a schematic?

@Nick Gammon, sorry for the confusing words nick, simply saying is i want to use the extra output from the 74HC595, but i dont know how to abstract them to the code. - Actual board means the arduino uno.

See my post about the 595 chip

Let say im going to put the Trigger pin into Q0 and Echo pin into Q1 -- The echo pin connects to an INPUT on the Arduino. Q1 (and all the pins on the 595) are OUTPUT pins. That can never work. Ever. Time to rethink your requirements.

It is good that you are thinking of abstraction in order to simplify programming.  Simplifying programming by using familiar names makes it easier to understand the code.
In your example:
int triggerPin=2
pinMode(triggerPin, OUTPUT)

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin".  You could have just as easily wrote the same code as:
pinMode(2, OUTPUT)

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595.  The truth is, you don't have to.  But to make it easier to write & read the code you can use what ever names make sense to you.  In this example of connecting an Arduino to a 74HC595 there are 3 Arduino pins connected to the 74HC595.  They called them "dataPin", "latchPin" and "clockPin".  If these make sense to you use these names.

Add: can i address the output like this?
 #define LED_PIN     Q1

No, nothing knows what "Q1" is.  Remember, you are adding this hardware to the Arduino.  So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.
First you need to understand how to set Q1 through Q8.  Refer to the 74HC595 Arduino tutorial linked to above.  Inspect the example programs.  Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.
If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.

@Mahardika, if this is what you were asking about great.  If you want to go further and ask about the output pins of the 74HC595, re-word or add-to your question to make it clear what you want.

this is all making more sense to me, and for others who viewed this question haha.. thank you!

This all makes a lot of sense. But I don't see where "extra slot" comes into it.

Yes, I think Mahardika meant to say "extra output".  It did occur to me to edit the Question to make things clearer.


text:
What is this shield? (AST Space Arduino Kit)
I recently got a box with Arduino components from someone who didn't want it (in part, because the manual was (probably) in Chinese). However, to my surprise, I could not find this kit on the internet. I would like to know: is this a copy of another kit?  Or, is there documentation available for this particular kit?
Box contents:

Arduino Uno
Unknow shield "by AST Space" with

AI-THINKER wi-fi module
Songle relais
YLB3641AH 4-digit LED display
DHT-11 relative humidity, temperature sensor
IR receivers, switches, microphone/buzzer, light sensor, connectors to the other components

MPU6050 accelerometer
HC-SR04 ultrasonic rangefinder
QAPASS LCD unit
"Car MP3" IR remote
2x green, 2x red LED, 5x resistor
17x10 green breadboard
2x DC motor, 1x geared stepper motor
40-wide female-female jumper ribbon cable
USB connector cable (black)

It came in an intricate folding box, bright orange. The QR code links to http://weixin.qq.com/r/2kgtNVXEKwhUrRFW9x3I (which did not get me anywhere - visiting this link is at your own risk). Pictures:

Did you try scanning the QR code? I can't because your picture is too blurry.

@Majenko Yeah, it was a broken link; further inspection revealed it was a link to a sponsor. I checked the internet archives, but nowhere was any reference to anything related to this kit or Arduino in general.

It looks like "AST Space" is the online name of a Chinese blogger...

You could just backwards engineer the shield.  Other than what appears to be a WIFI at the top and, maybe, a bluetooth at the bottom - everything else appears to be simply hanging off the Arduino Uno's pins.  But it is hard to tell as the  picture is not all that clear. Guessing, there is no single point to this shield.  It is a collection of different devices. So other then for teaching, its use (mainly because it's huge) is rather limited.

@st2000 That's what I've been doing, but there's a few components whose function I don't know, and I am afraid I could miss a few things. I was mostly wondering whether this was a known board, but given these reactions, it's probably a one-off.

Looks like a great shield. Maybe something here https://translate.googleusercontent.com/translate_c?depth=1&hl=en&prev=search&rurl=translate.google.co.uk&sl=zh-CN&u=http://www.yiweibiying.com/p/J9MPkxx.html&usg=ALkJrhg47ONSQlf2deaRdrkbCgRtG6qgOA

Take a close up of the bits that are confusing you. There are plenty of people here who enjoy backwards engineering hardware.  Just try to ask one question per post.  Try to make it as specific as possible.  And alter your question in order to clear up any misunderstandings or to clarify the question.

@st2000 I will in due time. But, as for now, I was hoping to avoid having to ask various bits and pieces if there was a comprehensive overview for this particular shield. Thanks for your time, nevertheless!

There are no links that I can find to the PDF or the downloads or anything else anymore. I was given one of these kits at work and asked to look into it. Does Anyone have a working link to English Manual or link to the Download site above etc.. Thanks in Advance. Scott

@ScottPinard I made a rough translation of a PDF found in the RAR linked in dda's answer. I uploaded it here for you: https://we.tl/5j77KOe99E Feel free to upvote this question if you find it useful!

My name is Bing Zhu. I the host of ASTSpace a community open lab sponsored by Zhejiang Association for Science and Technology(ZAST). AST is situated inside the Zhejiang Museum of Science and Technology. We are non-profit. The Kit you have gotten must be from someone got it free at one of ASTSpace's events. I remembered that we had brought some with us to the Manchester Science Festival where we did a tinkering activity for the public, 3 years ago.
This kit was designed by one of our members who is currently a Ph.D. student of automation at Zhejiang University. It was developed for the purpose to increase public experiences in a 90 minutes session. Therefore, in order to shorten the time of wiring while most times participants with no backgrounds or exposures to electronics make no sense anyway, we purposely had most of the functioning parts soldered on. In this way, we think it would be more manageable as well for teaching as most times one instructor has to manage more than a room full of over 25 participants. Making sure that parts are connected and in place can be a life-saver. We had it designed this way so the kit can be used in classes by schools in remote areas. These kits are given away and the introduction sessions are free to the public, and we intended to provide online help to those who decide to venture on with this kit at their own time. But, it never took off for time and resource restriction.  With this kit we have gone through two major cities in the Zhejiang Province and 4 remote rural areas.
All our expenses are supported by ZAST through two projects, one to make it and one to distribute it. When we did what we did, it was always for the public to know electronic control and coding was made easy by Arduino where it was first invented by an Italian who wanted to teach artists electronics.
This kit was used to demo how easily and readily everything can be controlled and through these electronics, we can take the parts of the physical world into our hands to follow our wills. We did use it to demo the on and off lighting system of the entire science center and controls of a remote camera inside the security room.
So, ASTSpace Arduino kit is a tailor-made kit for a specific purpose. We did not change anything but redesigned the wiring of the sensors for easy use for our events.

Hi Bing, thanks for your answer. I indeed got it from a young student who attended one of your sessions. They gave it away due to a lack of skills and interest in programming (which can seem very daunting to novices). The board is now part of an Internet of Things project, and I'm planning to use some of the peripherals as a robotics demonstrator.

AST stands for Art, Science and Technology. The learning kit is produced by AST Space who also run maker competitions.

I'm Xiaotian, the designer of this arduino learning Kit. We designed that for people who love DIY but without electronic backgrounds. In the past events, we found everybody (12-16 year old kids usually) could start wiring and coding and finish a little projects with the kit and its examples in 90 mins. All of hardware and software are modular, you could assembly them you want and make your great ideas real quickly.
If you want to know more details about it, feel free to let me know. My email is xtchen@zju.edu.cn.
Thanks for your attention!
Xiaotian

On http://astspace.org/ you can download a PDF related to this AST Space Kit[rar archive].

I took the schema in the PDF and translated in English. Looking at the examples (see below), it looks like the "Wifi Module" is an ESP8266.
The QR code in the PDF is actually readable, but you have to scan it in WeChat (a social platform that mixes chat, Instagram and shopping).
The QR code links to AST Space's account:

The download mentioned above contains schematics and sample code. Download that and you should have a much better understanding on how to use it.


text:
Arduino add two spi slaves that has no slave select pin
I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.
How Can I solve this issue?
Sensor example
Thanks

Then, they are really not SPI devices.  Are you sure they are not I2C where different devices have different addresses?  More information like part numbers would help here.

No, They are using SPI serial interface

I just edited it to show example of SPI examples I mean

Ss or cs pin ISS not mandatory for SPI.
A few solutions.

Power on or off the devices. A group pin can do that.
Cut off mclk.
Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.
Software SPI.

...
I'm sure others will come up with more solutions.

Looking at the MS5540C specifications and assuming there are no other significant parts on the PCB you identified, there does not appear to be a SPI port available.
Neither "SPI" not "I2C" appear in the document.  Please check your self to verify.
Instead there is a section on serial communication with the MS5540C part its self.  In this section there are a number of diagrams.  Here is one:

In the text we find this:

Every  communication  starts  with  an  instruction  sequence  at  pin
  DIN.  Fig.  6  shows  the  timing  diagrams  for  the  MS5540C.

Which is very nearly if not exactly how I2C works.
The text goes on to say:

he  device  does  not  need  a  ‘Chip  select’  signal.  Instead
  there  is  a  START  sequence  (3-Bit  high) before  each  SETUP
  sequence  and  STOP  sequence  (3-Bit  low)  after  each  SETUP
  sequence.  The  SETUP  sequence consists in 4-Bit that select a
  reading of pressure, temperature or calibration data. In case of
  pressure- (D1) or temperature- (D2) reading the module acknowledges
  the start of a conversion by a low to high transition at pin DOUT
  during the last bit of the STOP sequence.

Unfortunately, this design appears to prohibit using more than one identical device on the same serial bus.
Workarounds to this design flaw (if it truly exists) include blocking the SCLK or the DIN signal to the un-selected MS5540C.
In many other cases where multiple identical I2C devices are used on the same bus, vendors provide a pin on the device which can be used to alter the address of an individual device.

They also use 15 bit words, which I'm not even sure the Arduinos SPI supports. I'd just bitbang the protocol, and use different pins for the two sensors.

Sounds like a plan.  But again, it does not look like a SPI bus device.  I know the web page you linked to / bought the device from lists SPI.  But I believe this to be in error. The Chip Select or Slave Select line on a SPI bus is necessary!  It is the only way for the slave and master SPI devices to synchronize.  With out this line, if either device looses sync, they will never be able to talk to one another with out being power cycled.


text:
Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno?
I was wondering if I can use a GPS (in my case a U-BLOX) and a hc-05 at the same time connected to a arduino uno without a breadboard? I have tried my GPS on the arduino uno alone and it works very good. Now my question is, can I add a hc-05 on the board directly and put the VCC on the empty 5v?
I put together a schematic of what I had in mind below:

Would this schematic work or would I need a breadboard?

Are you expecting to use them both at once? Note of caution: you cannot reliably use two SoftwareSerial objects at once.

I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.
Note that some male-female header might get handy.
I'm not sure that the HC05 can handle 5V though. You migh want to check.


text:
Arduino Uno Bluetooth connection
I'm trying to connect two Arduino Unos with Bluetooth modules (HC-06 and HC-05). Does anyone know the steps required to do that?
I still haven't figured out:

How to pair the two Bluetooth devices, and;
How to pair each Bluetooth with each Arduino.

If you have any useful tutorials, please let me know.

There is a nice example for Arduino here.
Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link
The Uno works the same way as the board in the example.
Arduino 1

Arduino 2


text:
Reading values from SQL Arduino ethernet
I'm about to do this project where I will make some lights flash up depending on some values that are in an SQL database on a server. I have already bought my Arduino and waiting for it to arrive. But I've been stuck at how to read the SQL data from the Arduino, connected to ethernet only.
Is there a library where I can select from the database directly or do I have to make a web service, in which I can make a http request to when needed?
If it's a web service, can I be directed to some examples of this being used with Arduino? I've been looking around the past few days but haven't been able to find a decent example.
Best regards and thanks a lot in advance for your time! :-)

I would make a small http REST API on your SQL server. The Arduino could use the API to get the data.
The API can easily be done in php, ruby or whatever.

Connecting to an SQL database from the Arduino would be the hard way. Creating a simple web page that can read data from your database and display said data would be the easier way. You could then access this data on the Arduino via an http request.
Here's an example of how to write such a web page in PHP: https://www.w3schools.com/php/php_mysql_select.asp
And here's the Arduino example for an HTTP request with an ethernet shield: https://www.arduino.cc/en/Tutorial/WebClient


text:
Minimum circuitry required to program an AVR
Where is the information what is the minimum-required circuitry to program any AVR via ICSP?
Sometimes I see schematics that show just the chip and the six wires for the ICSP header (RESET, VCC, GND, MISO, MOSI, and SCK).
Other times, I see some passive components connected to some of the pins.
So why is it different some times? How do people know when to use extra components when wiring up the chip for programming? Do the datasheet for these MPU's provide the details?

I have a page about a minimal board. The minimal circuit is the chip itself, and a couple of decoupling capacitors. A pull-up on /RESET is advisable (however the processor has a weak pull-up on it).

The six wires you mention are required for ICSP programming. An example from my page is:

That is using an Arduino as an ICSP programmer.
I think most designers would mandate the decoupling capacitors. You may get away without the pull-up on /RESET but probably at the expense of reliability.
The wires changed colour between the two photos because my earlier board (shown second) had the capacitors further away from the chip pins than they should have been. They really should be next to the chip for maximum effectiveness.

Note that, depending on the fuses, you may need to supply an external clock. In my case I did it like this:

The default chip fuses (from the manufacturer) does not require a crystal.

All good advice, but it might be worth mentioning that if the target AVR has its fuses set to expect an external clock, you need to provide one.

@Nick Gammon
Great post!
Does the wiring of the circuitry generally hold up for all AVR's? Or are more complex AVR's (such as ATmega32U4) going to require different circuitry?

All 8 bit AVRs I know of work with this protocol, except for the 4/5/9/10 6-pin variety.

I added a bit more about the external clock. As for the other AVRs, I have programmed the ATmega32U4 and the ATtiny chips in a similar way (the actual wiring varies, of course). Ditto for the larger chips (Atmega1280, Atmega2560 etc.).

This post was very useful thanks. I did my own diagram for use with a Pololu AVR programmer. https://www.flickr.com/photos/qu1j0t3/49712305953/in/dateposted/

authors: עידן מנעולן ופורץ מנעולים


text:
Where is the inaccuracy of my arduino thermistor circuit coming from?
I've setup four thermistors and a known resistor in series and connected them to the 3.3V output (as I've heard it's cleaner than the 5V) of an Arduino Uno (with the 3.3V also connected to ARef to increase accuracy), with the four analog inputs testing the voltage drop across each thermistor to determine its resistance, and hence temperature.
But even with no change in the thermistor temperatures, the voltages I get from the arduino vary significantly. See below an example readout of the four arduino inputs (with thermistor temperatures/resistances same throughout):
230 424 634 849
212 412 597 819
241 415 611 857
204 413 654 845
The accuracy I come out with is around 5-10 degrees - way more than I expected. Why is this? And what can I do to get it down to less than one degree? Many thanks
UPDATE:
A MASSIVE THANKYOU to all those who helped me on this, particularly @NickGammon, @Talk2 and most of all @JRobert for the brilliantly clear and simple to follow circuit instructions to follow, all of which helped to thoroughly solve my problem! The sensor works great now, many thanks!!

Have you check your thermistor specs for their rated accuracy ? Also your 3.3v Vref how stable is it ? Maybe attach a schematic and thermistor p/n may help providing a better answer.

Perhaps if you post your code? And the thermistor model? Are those analog input readings? If so, a reading of around 200 is only 20% of the range of the ADC (which can go up to 1023) so any errors are going to be amplified by 5.

Hi Andre and Nick, thanks for your comments. The thermistors are ATC Semitec 104GT-2 Gt Thermistor 100k 3% - rated %3 - but I've checked them with a multimeter and they're not source of this error. They'll flicker a KOhm (about 1%) either side of their resistnace but will not vary more than that. Some of the values above change 15% between readings. The 3.3Vref I was told was better than the 5V, that's all I know. I can draw you a schematic but its a very simple circuit as described with no extra bells and whistles so far

I can also post my code if you want but I don't see how it would help as the values above are literally the analog values themselves as measured by the arduino (using ARef as well). The code simply takes the analog input values, and converts them into temperatures using the steinhart equation. It also takes an average but this doesn't really help.

Nick, good point about how the voltage of each thermistor is being described by only 20% of the 1023 range of the analog inputs - but if this were to blame wouldn't this mean the values varied less, rather than more as you can see above?

You did set analogReference(EXTERNAL) before connecting AREF to 3.3V, right?

Please do show a schematic - or at the very least a photograph of your setup.

Hi Edgar, what do you mean by 'before'? My setup code sets analogreference(EXTERNAL), before the loop code if that's what you mean. But the 3.3V and ARef pins are already physically connected before I plug the arduino into the laptop.

@Andre and Majenko please see picture above

Wouldn't it be better to connect the themistors individually, instead of all in series? Inaccuracies in one sensor, will influence the others. Also, since you can only read one analog pin at a time, the value of the previously read themistor could have changed, when reading the next. I think you are also losing some range, as you have to share the range between 4 readings.

@Gerben how do you mean individually? Do you mean have one arduino per thermistor?

No. You have wired it so that each reading will be influenced by the values from the other thermistors. Why not have each one wired with their own resistor (for the voltage divider)? In fact, why have four anyway? They are all adjacent aren't they?

if this were to blame wouldn't this mean the values varied less, rather than more as you can see above? - yes perhaps, but the calculated temperature will lose precision. You will be converting 0-200 into degrees when you could be converting 0-1023 into degrees.

What I would like you to do is remove the "thermistors in series" effect. Take a single thermistor, and your 100k resistor, and take some readings. ie. +5V --- 100k --(A0)-- thermistor --- Gnd - see if a) It gives the desired temperature; and b) Do they vary by such a large amount?

My bad, as long as analogReference(EXTERNAL) is done before the first analogRead(), you are fine. 2) Now, I just did a small experiment. For lack of a suitable thermistor, I used an LDR with a 10 kΩ pullup. Out of 4399 readings, I only got 4 distinct values: 572 (11 times), 573 (1698 times), 574 (2599 times) and 575 (91 times). The RMS amplitude of the fluctuations was about 0.53 ADC steps. All this with the 5V reference.

Why are you using the voltage divider and measuring by parts? As @nickgammon points out, you are measuring only a 1/5 of full scale at each measurement, meaning your resolution is down by 5:1 over what the A/D is capable of. Also, the divider network comes to around 500KOhms. Work out the current through that and you get a very feeble <7 microAmps. The wires are antennas that could well be contributing noise at a significant fraction of that level.
Is there a reason for the divider circuit? Could you use a single thermistor from Vcc to Gnd plus a resistor in a 2-way divider? That will have the advantages of:

Using (more of) the full range of A/D;
Taking only one reading instead of several (and the several are necessarily skewed in time since you're multiplexing the one A/D);
A larger current (ok, only 33 microAmps, but 5x better than before);
Presumably less pickup into the network than with 5 leads. Keeping the measurement lead as short as possible may help, too.

Update:
Then you probably want a 2-component divider for each temperature you need to measure, paralleled between the power rails. I just guessed, not calculated, the resistances of R1, R3, R5, & R7. You'll want to estimate the maximum and minimum temperatures of interest in each channel and pick values that will give you the best ranges without drawing excessive currents when the thermistor values are low.

simulate this circuit – Schematic created using CircuitLab

No I need four temperature sensors for purpose. Could using smaller resistance thermistors help?

I still think that by connecting the thermistors in series you are summing the errors. So if the first one has a 1% error (or some jitter) then that will vary the voltage being received by the second one, and so on. I'm testing with a thermistor and a 100k resistor (not your thermistor exactly) and I am seeing a couple of mV jitter (probably noise being picked up).

Without exactly knowing part names, models and source code is difficult to tell what to expect. But a few techniques can be used to improve the stability of an analog reading. Here a few things you might want to consider:

Use INTERNAL vref of 1.1V, this is a very stable voltage reference
Use a stable/good quality series resistor, with little tolerance, like 1%
Add a 22pF capacitor, connecting the analog input to ground. This helps stabilizing the signal
Perform multiple consecutive readings, let's say 5 readings, and use the average. You might also want to remove the biggest and lowest values before averaging.

Hi Talk2, thanks very much for the suggestions. The parts are Arduino Uno SMD A000073 Board Rev3, ATC Semitec 104GT-2 Gt Thermistor 100k 3%, and Vishay CNS020 Series Radial Thin Film Resistor 100kΩ ±0.02% 0.5W ±10ppm/°C.

The values above are literally printouts of analog inputs (using Aref again), so the source code doesn't explain the variance in values there.

I do use an average in the main code, but it doesn't really help as the intial inputs are so variable.

What exactly do you mean by adding a 22pf capacitor between input and gnd? Do you mean wire the thermistors to the analog inputs and then from there to GND across the capacitor?

If I changed the 10 bit Uno for a 12 bit Due board, do you think that would improve the quality of the readouts?

or would it just increase the resolution, rather than the accuracy or precision of the analog readings above?

From 10bits to 12bits you only going to get more resolution. The Arduino analog ports are quite good for what you need. Why are you chain all the sensors? Have you tried with a single one? The capacitor needs to be between the Analog port and ground, so it works like a "buffer" to stabilize the voltage output from the voltage divider made of the Thermstor and the Resistor.

I may be mistaking, but what you did is a voltage divisor where you read the voltage across resistors in series (your thermistors).
When resistors are in series as you know you add their value. So A4 is reading the value across TR1+TR2+TR3+TR4. A3 is reading the value across TR1+TR2+TR3 and so forth.

Yes Andre I had worked that out - my code takes this into account. By taking the differential between voltage readings all the resistance values can be worked out. But I don't think any of this is relevant unfortuately as the analog readings themselves, before even being processed by the code at all, are so instable as you can see.

You did look at this reference right :
https://www.arduino.cc/en/Reference/AnalogReference


text:
Does this code work as a PWM?
I'm working on an Arduino project and I need to write some code that controls the frequency and duty cycle of a square wave signal (pulse width modulation). I'm not allowed to use the PWM function, I have to write my own code.
I've tried this code on Proteus (virtual Arduino) but there are two problems:

The frequency is always high (hundreds of Hz) even if the input voltage is zero. It never reaches 0.5 Hz or 1 Hz.
The duty cycle is very high or very low. I never see 50% or 75% duty cycle on an oscilloscope. When I change the position of the potentiometer it becomes 90% or 10% (I think) and there are no other values.

Would you tell me what's wrong with this code please? I can not find my mistake:
unsigned long Time = 2000000; unsigned int Volt; float dutyCycle = 0.5;
void setup() {
  pinMode(13, OUTPUT); //set Pin 13 or On-board LED to output
}

// the loop function runs over and over again forever
void loop() {

  Volt = analogRead (1);    // Frequency: input voltage is through potentiometer at analong pin 1
  dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0
  Time = ( 2000954 / (1 + Volt) )- 954; //This equations is linear. When input voltage is zero, frequency = 0.5Hz. When input voltage is 5v, f=1000Hz.

  digitalWrite(13, HIGH);   // turn the LED on
  delayMicroseconds(Time * dutyCycle );              // wait
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(Time * (1-dutyCycle) );          // wait
}

dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0

Dividing a small integer by a bigger integer leaves you with 0. If analogRead() returns 1023 you will get a result of 1. Everything else will give you 0. You need to divide by a floating point number - either 1023.0 or 1023f.
analogRead() is slow. Because it is happening between every single cycle of your square wave you can expect to never get to anywhere near 100% duty cycle. There will always be a LOW period where the analog input is being read.
You should:

Fix your integer division problem
Make the ADC "free running" or interrupt driven so it doesn't interfere with your PWM generation

... Or ...

Fix your integer division problem
Make your PWM generation timer driven, either using the OC peripheral or manually with interrupts, so it doesn't interfere with the analog reading.

... Or ...
You could even do both. Make everything as asynchronous as possible leaving your loop() free to just do the heavy work of calculating the values.


text:
Why FIFO is important in camera?
I want to buy a camera module for Arduino. I came across this OV7670 CMOS Camera Module Lens CMOS 640X480 SCCB W/ I2C Interface Arduino and CMOS With AL422 3M-Bits OV7670 FIFO Camera .
I want to know what difference does FIFO makes in a camera? If I dont use a FIFO will the quality of video be compromised?

It is all about data transfer mode and performance.

Its not FIFO that is the issue, its the FIFO Buffer that you need with an Arduino.  The Arduino can't download the data from the camera at the same speed as the camera can send it.  Adding this extra buffer in lets the camera generate the data and the Arduino download it (in the same order that it was generated) at its own pace.
You might not need the FIFO buffer for faster microprocessors, but you do need it for the Arduinos.  You could get your own buffer and rig that up, but for a few extra bucks let them do it for you.


text:
Stepper and Line tracker
I am making a program which will use stepper motors and a line tracking sensor. The idea is that when the linetracker detects a black surface both steppers must move forward, and when the linetrackers is not detecting black surface it should scan the surface for a black surface.
I made some code which makes the robot move forward if the linetracker has a set value. The problem is that when I implement the code for the line-tracker. My steppers are going to run very laggy probably because the arduino is constantly scanning if the value of the linetracker is below 500.
My question is, is there a way to program the line tracker without having it interfere on my stepper motors? (The stepper motors run smooth without the linetracker)
#include <RedBot.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//Code voor de LCD
#define I2C_ADDR       0x3F // Define I2C Address (use i2c scanner if necessary)
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define LED_OFF        0

#define LED_ON         1
//Hier worden de eigen functies gemaakt door HEX code
uint8_t battery_1[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x11,0x1f};
uint8_t battery_2[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x1f,0x1f};
uint8_t battery_3[8]=   {0xe,0x1b,0x11,0x11,0x11,0x1f,0x1f,0x1f};
uint8_t battery_4[8]=   {0xe,0x1b,0x11,0x11,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_5[8]=   {0xe,0x1b,0x11,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_6[8]=   {0xe,0x1b,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_7[8]=   {0xe,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

RedBotSensor left_sen    =    RedBotSensor(A3);
RedBotSensor right_sen   =    RedBotSensor(A2);
int lineStandard         =    800;

void setup()
{
  scherm();
  //stepper 1
  pinMode(13,OUTPUT);   // Step
  pinMode(12,OUTPUT);   // Dir
  //stepper 2
  pinMode(11,OUTPUT);   //Step 2
  pinMode(10,OUTPUT);   //Dir 2
  Serial.begin(9600);
  Serial.println("IR Sensor Readings:: ");
  //delay(500);
}

void loop()
{
  Serial.print(left_sen.read());
  Serial.print("\t");
  Serial.print(right_sen.read());
  Serial.println();

  if(right_sen.read() > lineStandard)
    {
      left();
    }

  else if(left_sen.read() > lineStandard)
    {
      right();
    }

  if((left_sen.read() > lineStandard) && (right_sen.read() > lineStandard) )
    {
      Stop ();
    }

  else
    {
      forward();
    }
}

void right()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, rechter kant
  //digitalWrite(3,HIGH);
}
void Stop ()
{
  digitalWrite(13, LOW);
  delay(1500);
  digitalWrite(11, LOW);
  delay(1500);
  //Rood lampje aansturen
  //digitalWrite(2,HIGH);
}
void left()
{
  //stepper 1
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, linker kant
  //digitalWrite(4,HIGH);
}
void forward()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Groen lampje sturen
  //digitalWrite(1,HIGH);
}

void scherm()
{
  lcd.begin(16,2);
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(LED_ON);
  //Hier worden de eigen symbolen benoemd
  lcd.createChar(1, battery_1);
  lcd.createChar(2, battery_2);
  lcd.createChar(3, battery_3);
  lcd.createChar(4, battery_4);
  lcd.createChar(5, battery_5);
  lcd.createChar(6, battery_6);
  lcd.createChar(7, battery_7);
  lcd.home();
  lcd.print("Batterij Status");
  lcd.setCursor(0, 1);
  //Schrijf de batterij icoontjes naar het LCD
  lcd.write(1);
  lcd.write(2);
  lcd.write(3);
  lcd.write(4);
  lcd.write(5);
  lcd.write(6);
  lcd.write(7);
}

Try removing your serial print statement. It's detrimental to performance. And then read up on how to use interrupts, which you could use in combination with a competitor.

You could use a driver for stepper motors, so you can control the motors using PWM. You call the PWM from Arduino using analogWrite(). After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (Read this link from the Arduino page). This will help you in your project, and maybe find the solution to your problems when reading the sensor at the same time. An advantage of using PWM is that you can also made smoother movement for your robot when it is crossing or finding its way.
I also recommend using two sensors (I suppose you're using IR), so if you want to track the black surface and there is a turn, one of the sensors will be detecting the line, and the other one wont. That way you can assume which way should the robot turn, making it more efficient.

Thanks for the comment, I am currently using 2 line tracking sensors which are working fine. My code is also finished but the problem with the laggy steppers persists. I am going to try using two arduinos.

Well, using two arduinos would be a waste if you plan to do a simple function as a line tracker with two microcontrollers like the ATmega328P. Since the driver use MOSFETs to control your robot, you will be saving a redundancy in your circuit. Just a recommendation. If you don't have any problem with it, just go ahead.

Also, buying a driver should be cheaper than other Arduino link

I am using a drivers, It is the polulu drv8825

But the problem still persists, Am I doing something wrong in the coding?

@Jordakoes please can you update the new code? If you haven't you should be using analogWrite() for PWM control.

Sorry for the very late response, I had a long christmas holiday. Anyways, I was wondering how do I implement PWM in my current code? (I have updated my code in the post above.)

is there a way to program the line tracker without having it interfere on my stepper motors?

you are simply generating a pwm signal to drive your steppers. So make that generation in the background, through a timer isr for example.
Thus your main loop() will just be doing the low priority stuff.