text:
How to communicate between a webcam and an Arduino UNO and get the live feed on mobile using ESP8266?
I am working on a project of making a Smart Robot Car using Arduino UNO, L298N Motor Driver Module, ESP8266 Esp-01 WiFi module and RemoteXY app for controlling via smartphone over WiFi.
My question is: If I want to get the live feed of the view that my robot is seeing, using a webcam (say Logitech HD Webcam C270) using a USB to serial converter module or whatsoever, how can I make it possible?
Please let me know if there is any special shield or any processing board needed. Help with coding and the conversion of Video data into the transmittable Data for Arduino and help in making that kind of data which can be read by the Device (e.g. Smartphone) is also needed and will be appreciable.
It may be mentioned here that I am a beginner and I am currently learning through YouTube and Blog Tutorials. I am totally dependent on StackExchange like forums for the help in my projects either whenever I am making a mistake or when I want to try and learn something new or both. Please Help me while keeping these things in your mind also.
Please suggest me some good books on this branch of the subject that could make me able to do these kinds of things on my own.
Thank You So Much in advance!
(P.S.: If you feel this question should be downvoted then, please firstly let me know in the comments section why do you feel like this before downvoting, I may delete my question earlier, cause I am concerned about my reputation here.)

I've seen some products that working similarly, on Banggood. For example see this one . In this product, a Camera is attached to the robot, which gives the live feed to the user or controller on his smart device. I am also willing to make something similar but I don't know how to communicate between Arduino and a WebCam Live. Thanks in advance!

The UNO can't handle that kind of bandwidth. Unless you are okay with 1 frame per 10 seconds. USB would also be problematic. I think you'd be better of with something like a Raspberry Pi for the USB Webcam. Or the ESP with some specific camera module . Only use the UNO to drive the motors.

@Gerben have you gone through the link I had commented? If yes then, could you please tell me how is it working? If No, then please check it once and then make me understand that phenomenon. Thanks!

The link shows a robot with an independent wifi enabled webcam. There is no interaction with the Arduino there, other that the cam sits on the robot

@chrisl please go to this link and see how is he connecting his computer only from one wireless network and running both (the camera and the robot) together. Then, explain me what's going on there. Thanks in advance!

In the description of the robot used it mentions the raspberry pi 3B. On the website there are similar robots sold without the webcam and with just an Arduino with a Bluetooth controller. My guess is that they interface the raspberry pi with WiFi and the webcam and an Arduino that does the motor driving. This would require custom software on both the pi, Arduino and host computer. Potentially it is all done with a Pi but the listing also mentions an Arduino.

@C.W.G         So is it completely impossible to do such things with an Arduino Uno?

Yes, directly anyway. I'd recommend either using a raspberry pi for the project or using a WiFi enabled webcam that can connect directly to your computer

The Uno is a very limited platform, perhaps surprisingly, given its wide range of abilities and built-in hardware features. The two most glaring limitations for you application are its 16MHz clock speed (relative to modern desktop processors) and thus its bandwidth, and it's non-expandable 2KBytes of RAM.
Image processing would be right out the window, and even merely transmitting a raw image would be pushing its bandwidth limits, for any reasonable frame-size with even a very modest frame-rate.
Example: For a 100x100 8-bit frame at 15 frames/sec, a 16MHz processor (16M instructions per sec) would have (16000000 / (100x100x15)) = ~107 clocks (instructions) available to process each byte. You'd need some of those to either poll for next-byte-ready or to enter and exit an Interrupt Service Routine to process the byte. You're probably up to around 20 clocks (at a wild guess), to do nothing more than a bit of wire can do! Maybe you could do some trivial manipulation of each byte on the way through (say, brightness manipulation) with a few more clocks and you're already using a significant fraction of the processor just for that. And there isn't enough memory to be able to process a region of the image. And if you could, you run out of processor time before you could do much .... The problem just cascades as you approach the limits of speed and memory-space.

As rightly pointed out by others and @JRobert, its very difficult or nearly impossible to live stream a video/audio through Arduino Uno which uses Atmega328 micro-controller which is mostly used for simple embedded processing such as sensor reading, serial tr/rx, i2c like operations.
But there are some workarounds which can make it possible by using some SPI camera and some Bluetooth shield or ESP8266 together.
Take a look at this project which can be helpful to you.
https://github.com/ArduCAM/Arduino
But remember, don't expect a very good quality or higher frame-rate video stream. Also it might only send video, i.e. picture frames and not audio.
Second solutions is:
If you just want your robot to get equipped with a camera which need to be live streamed back to your android/ios phone with good quality AV then the best way to do this is by a standard method used by most RC toys, UAV or robots.
What you need is:
1) 5.8Ghz AV transmitter

A Mini FPV Camera NTSC/PAL with inbuilt transmitter or
FPV camera and a 5.8G 600mW Wireless Audio/Video Transmitter for FPV

with above options you can get a possible range of 1 Km to 5Km or more.
2) second thing you need is receiver section

OTG 5.8G 150CH Full Channel FPV Receiver For Android and iOS is best for this.
This above module will help you to receive AV from FPV camera/module to your android.

I'll not give you direct link to the products as that wont be a good idea here on SE. instead you can search for them on google and choose as per your requirement. most of these modules will be less than 2000 INR or 30$


text:
Is there a schematic for the ESP32S Dev Kit C V4 NodeMCU WLAN Development Board?
Recently I bought a ESP32S Dev Kit C V4 NodeMCU WLAN Development Board. I got it from azdelivery.de in Germany.
Now I am interested in the schematic for this board to learn more about it. Not Google, nor the support team at azdelivery.de could help me, but since the board is a Chinese mass product, I hope to find an answer here, where I could get the schematic.
Thank you!

Apparently az-delivery have a free e-book available for download on this ESP32 board. Have you looked at that? There's also a generic ESP32 Devkit C V4 schematic available.

Yes, I also have the e-book. It contains a general description of the board, the pinout, many technical details and some example sketches, but unfortunately no schematic of the board. The link with the schematic is new to me! Thank you so much!!!

Here is a webpage that provides ESP32 Devkit C schematic and pin definition. It may help you. But not sure if the dev board you got is same as the web provides. ESP32 Devkit C schematic

Thanks for the link! I’ll check that, when I’m back home again.

Espressif has schematics and more on their website. EZ-Delivery sells two different versions: One has a CP2101 USB-Interface, the other one uses a CH340 instead. If you have the CP2101 variant, this should match the one at Espressif's Website:
https://dl.espressif.com/dl/schematics/esp32_devkitc_v4-sch.pdf
More related docs are linked on their Website (scroll down to "Related Documents" here:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html#get-started-esp32-devkitc-board-front

Here is a webpage that provides ESP32 Devkit C schematic and pin definition.

ESP32 Devkit C schematic

OP's board is definitely not having a xQFN28 CP2102N USB chip.

source: Stack Exchange

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

sort: votes


text:
Is is possible to install a bootloader to an Arduino clone without a physical programmer?
I got an Arduino UNO clone, connected it to my PC via USB. I can't upload any sketches.
Correct board and port are selected in the IDE.
Windows recognizes it as a device, even though it has a CH340 (known issue with Chinese clones), so drivers don't seem to be the issue.
All physical connections and wiring on the board seem good.
So I am led to believe that the bootloader is the issue.
After a bit of digging around, I didn't find a way to install an Arduino bootloader that didn't require a programmer device or an extra original Arduino board in hand.
Here is the console output after trying to upload a sketch.
avrdude: Version 6.3-20190619
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\lhyse\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xaa
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xaa

     avrdude done.  Thank you.

     Failed uploading: uploading error: exit status 1

For devices with an Atmega MCU and no pre-installed bootloader, the answer is NO - it is not possible to install a bootloader without a physical programmer.
If there is a working bootloader, but not the one you need, it might be possible under some circumstances.

Lets assume an Atmega328p has a current bootloader that is only 512 bytes large (4 pages) and resides at 0x3F00-0x3FF and BOOTSZ=11.
One might use the current bootloader to program the new bootloader (also 512 bytes) into the application area just below the current bootloader to address 0x3E00-0x3EFF. Now, if the current bootloader is capable of changing fuses BOOTSZ=10, the next time a reset occurs, at least I think so, the new bootloader at 0x3E00 will be startet. The bootloaders should not overlap each other for this to work.

on ATmega 328p only a bootloader can write into the flash so it is not possible to replace the bootloader from application, unless the bootloader supports it

Using Programmer              : arduino

Try using urclock programmer instead of arduino. Seems like it's a common problem to Arduino clones. My problem was almost same, and it helped me.
I described the problem and solution here: I can't upload my sketch to Arduino Uno using avrdude

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


text:
Digital Input using a button doesn't work properly when using it to control a relay
I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows:

Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 0; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 if (state == '0'&& valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 else
 if (state == '1' || valor== HIGH) {
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
 }

}

New code:
//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 1; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);
 //si el modulo ha mandado dato, guardarlo en estado.

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 // si el estado es 0 ese sería Apagado “OFF”
 if (valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 // de lo contrario si el estado es 1 ese sería Encendido “ON”
 else
 if (valor== HIGH) {
     if (state== 1){
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
     }
     else if (state== 0){
     digitalWrite(ledPin, LOW);
     Serial1.println("LED: off");

     }
 }

}

The circuit is working properly when using bluetooth commands, in case that helps.

Should the switch work independently from the bluetooth command on the relay? Currently you can only turn it on with state='1' AND switch on, and you can only turn it off with state='0' AND switch off. It is not completely clear, what the desired behavior is. Please explain further, what the code should do.

@chrisl: No you can turn it on with state='1' OR switch is closed. That's why he can switch the LED on with the switch but not off.

Okay, I modified my code so I can only control via bluetooth when the switch is ON, however it is still not working...

You might be better off with boolean state = true, then using state = (bool)Serial1.read() and 'if (state)...' There's nothing shown here that guarantees Serial1.read()` will return a value of 1

The question lack critical information. What kind of data do you send over serial? Text or binary? First version of code works with characters '0' and '1'. Second version suddenly uses integer values 0 and 1. What gives? You have to make up your mind about what you want to send. Currently the question simply makes no sense.

"I'm trying to control a relay both via Bluetooth and using a switch."   You should explain this further.  How do you want it to act?  Does one override the other?

Well, there are a couple of problems.
In the original SW, you are checking for state = '0' and state = '1', but the initial value of state is 0 (not '0'). For this reason both tests always return false.
In addition, avoid setting conditions when not necessary. else already mean "all the other options", so if you have one variable that can be only A or B, don't write if A ... else if B ...; the second condition is necessary (and meaningful) only if the condition is actually something you care of (so you want to exclude condition C).
I started modifying your sketch from the new version, and here are the things I modified:

Variables were set to type uint8_t; int is not efficient on 8-bit platforms, so use 8-bit variables whenever you can
Instead of using multiple triggers, I used a single variable (ledState) to calculate the state in each loop. This way it is much easier to track the modifications
simplified the input management: now it turns on the led when the input is high, and does nothing (leaves it off) when it is low
simplified the bluetooth management. With a '1' it turns on the led, and all the other chars set it off; if you need only a '0' to turn it off you can easily modify the parentheses to ignore other chars

This is the code I wrote. NOTE: I did not test it, so there may be residual bugs. Let me know if it works as you expect or want some additional clarifications:
uint8_t ledPin = 2;
uint8_t interruptor = 3;
uint8_t bluetoothState = '0';

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW);
    Serial1.begin(9600);
}

void loop() {
    uint8_t ledState = LOW;

    if (digitalRead(interruptor)) {
        ledState = HIGH;
        Serial1.println("LED: on (switch)");
    }

    if(Serial1.available() > 0){
        bluetoothState = Serial1.read();
    }

    if (bluetoothState == '1') {
        ledState = HIGH;
        Serial1.println("LED: on (BT)");
    }

    digitalWrite(ledPin, ledState);
    if (ledState == LOW) {
        Serial1.println("LED: off");
    }
}

Things still to do (IMHO):

make a robust button handler (for instance using the debounce library)
get rid of the serial debug outputs
make a better serial protocol

Hopefully the problem was resolved in the intervening 2.5 yrs ;)

O_O why was it in the homepage then? I assumed it was something like 10 minutes old LOL.. sorry for the necroposting

:shrug: It's a low-traffic site so stuff gets bumped for visibility ;) And it's fine anyway--it'll help somebody, if not the OP :)

3.5 years now. :)

I assumed it was something like 10 minutes old ... yes, SE does do odd things like making posts look relevant when they are not.

You have to invalidate the state variable when Serial is not available, otherwise you will produce strange behaviours.
if (Serial1.available() > 0) {
    state = Serial1.read();
} else {
    state = -1; // not valid
}

Also, serial values will be characters, not integers, so compare with character values, e.g.,
if (state == '1')


text:
Sketch starts and keeps counting on external power supply but not usb
Thank you for the add, total newbie here (electronics and arduino) on his first project.
Trying to make a counter for a hay baler with two HAL effect sensors, (pin 5 & 6) and outputting to an I2C display.
One counts the amount of flakes per bale and the other the amount of bales (resetting the flakes on each bale and displaying an average)
I works perfectly whilst powered through USB, plug the 12v in and the counter just goes nuts and keeps counting without the magnet passing by the sensor.

I have checked if there is 5v at the 5v pin.
As soon as you take the trigger out of pin 5 or 6 the corresponding counter stops, put anything in the pin (even a bit of wire or a diode) and the counter starts taking off again.

//Bale and flake Counter
//Lourens Houttuin
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//i2c pins
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //
// set up a constant for the tilt switchPin
const int flakePin = 6;
const int balePin = 7;

int bales = 0;
int flakes = 0;
int avflakes = 0;

// variable to hold the value of the flakePin & bale pin
int switchState = 0;
int baleswitchState = 0;

// variable to hold previous value of the flakepin
int prevSwitchState = 0;
int prevBaleswitchstate = 0;

void setup() {
  // set up the number of columns and rows on the LCD
  lcd.begin(16, 2);

  // set up the switch pin as an input
  pinMode(flakePin,INPUT);
  pinMode(balePin,INPUT);

 lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes: 0");
}

void loop() {
  // check the status of the switch
  switchState = digitalRead(flakePin);
  baleswitchState = digitalRead(balePin);

  // compare the switchState to its previous state
  if (baleswitchState != prevBaleswitchstate){
    if (baleswitchState == LOW) {
      bales = bales + 1;
      flakes = 0;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print(flakes);
      lcd.print("/");
      lcd.print(avflakes/bales);
      lcd.setCursor (0,1);
      lcd.print("Bales:");
      lcd.setCursor (8,1);
      lcd.print(bales);
    }
  }
  if (switchState != prevSwitchState) {
    if (flakes>13){
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print("Speed UP");
    }
    if (switchState == LOW) {
      flakes = flakes + 1;
      avflakes=avflakes+1;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print(flakes);
      lcd.print("/");
      lcd.print(avflakes/bales);
      lcd.setCursor (0,1);
      lcd.print("Bales:");
      lcd.setCursor (8,1);
      lcd.print(bales);
    }
  }
  // save the current switch state as the last state
  prevSwitchState = switchState;
  prevBaleswitchstate = baleswitchState;
}

Edit your code to post properly - indent the lines with 4 spaces I think will do it. Is it 12V DC, not AC? The regulator and caps aren't really set up for heavy duty AC/DC conversion.

Can you show your wiring? What sort of 12V supply is it? Perhaps the supply is outputting noise which is triggering the Hall effect sensors.

Are your Hall Effect sensors logic output or analog?I have seen both types -- logic output will have HIGH or LOW only, but analog will vary the output voltage in accordance with the strength and polarity of the magnetic field. If a logic output, then is it open-collector and thus needs a pull-down or pull-up?

I'll try fix the code and upload schematic when I get to my computer.
I have 12v dc 1.25A
I believe The HAL Sensors are analog ( correct me if iam wrong) because I was told I had to put a 10 k resistor in to stop the fluctuations in voltage as the magnet approaches. But it doesn't matter if it's the sensor plugged in or a bit of wire as soon as either pin has anything in it the sketch starts running and continues to count until that wire is pulled out of the pin

Hope the schematic is right, I used fritzing  as I don't know yet how to do them any other way.
I have put a 9V battery instead of the 12v power supply, it seems to be working ok, so next try it out on vehicle 12v.

Is the 12v supply from a running vehicle? And the USB is from a computer? Is the Arduino in the same location for both tests or is it on your desk with the USB and on the vehicle for the 12v test?
Vehicle power is notoriously noisy - varying voltages, voltage spikes. I have run an Arduino successfully in my car supplied from a 5v USB charger in the cigarette lighter socket. Even with a thermo-sensor on a piece of Cat-5 cable coming out of the hood and through the driver's window (don't ask! :) I had quite steady readings and my display (I2C OLED) was solid. But do expect most external wiring to act like an antenna and pick up some of that noise. You might have to do some data smoothing or averaging to clean it up.
Update:

The eventual finished unit will be mounted in a tractor with the sensors about 4 meters back

See if a car-USB charger fixes the problem on the bench. Does the tractor have a "cigarette lighter socket" power-point as a car does? If not, they are available as a standalone part.
Is it ignition-suppressed to not interfere with a radio, the way a car is? Or does the baler have its own engine (which is most probably not suppressed)? If no suppression, you may need to put the Arduino in a metal box, grounded to the tractor frame, and use a shielded cable between the box and the sensors. And if it's still noisy, possibly even locate the box closer to the sensors - that cable will be like an antenna for noise; you'll need to minimize it.

At the moment a fixed power supply in same location.

The eventual finished unit will be mounted in a tractor with the sensors about 4 meters back on a baler to count the plunger strokes and bale numbers, so as long as the power is filtered iam hoping it all be good (dont know about the cheapy light bar but)


text:
4-digit 7-segment display resets when common pin set to HIGH
I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.
After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.
Code for my basic program, which should display "0123" on my display.
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);
  delay(5);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);
  delay(5);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

}

void loop() {
}

But all the display shows is a 3 on the rightmost digit. I followed the video in this guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?

These 4-digit LED displays use multiplexing which means that (to keep the pin count down) you only display each digit for a brief time. Because of the eye's persistence of vision, if you repeatedly display the 4 digits they all appear to be lit up.
I have a video that illustrates this effect with a LED sign. There are a lot more than 4 digits, but the video gradually shows what happens if the delay between each digit is reduced. Watch it through to the end or you won't get the effect. It is about 45 seconds long.
In your case, as jsotola suggested in their answer, if you move the code which displays the digits out of setup and into loop then the code is done repeatedly, which means that the digits are now displayed repeatedly, and you should see all of them.
Since, in your original code, you had the display code in setup then it was done once, and the final digit was the only one you saw.

This should work (sort of). It will be flickery, but it should give you a starting place to work from.
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {

  // put your setup code here, to run once:
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

}

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

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);
}

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


text:
Why does void loop() stop after some samples?
I am not getting any compile time error. After some samples of data void loop() stops executing. Please let know what the problem is. Below is my code.
Thanks and regards
Thippeswamy
#include<SPI.h>
float amplitude=1.5;
int freq1=20; int freq2=12;
int k=20;float A= amplitude*k;
int Fs=10550; float sine[5000]; float Fs1=3000;
int i=0;int reg1=1; int reg2=0;
int sample1=Fs/freq1; float sample2=Fs1/freq2;

void setup() {
  int SS=10;
  pinMode(SS, OUTPUT);
  SPI.begin();
}

void data(int reg, int data) {
  digitalWrite(SS,LOW);
  SPI.transfer(reg);
  SPI.transfer(data);
  digitalWrite(SS,HIGH);
}

void loop() {
  for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
    float s=A*sin((2*3.14*freq1*j)/Fs);
    sine[j]=s+190;
    data(reg1,sine[j]);
    if(i<=sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    } else if(i>sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    }
  }
}

please format your code properly (indent at least 4 spaces)

how do you know that the code stops?

I find it hard to believe you are not getting a compiler error because this line for(int j=0;j<sample1||i<sample2||i>=sample2);j++) has a bracket too many.

Also I really don't like the conditions used in that if... It looks like it's likely to end up with j being more than the size of your sine[] array since you have no absolute bounds checking...

Your huge sine[] array serves no useful purpose. Get rid of it and just data(reg2, s + 190);.

float sine[5000]
...
sine[j]=s+190;

A float takes 4 bytes. You are allocating 5000 of them which is 20000 bytes. The Uno has 2048 bytes of RAM. Thus you are running out of RAM and overwriting something you shouldn't be.

As pointed out on the Arduino forum, your for loop which tests for:
i < sample2 || i >= sample2

will always be true. Of course i will be either less than or greater than or equal to sample2.

Hi, Now i have chanced the data type to int and reduced the value to 1000, even now also same thing is happened

1000 x 5 = 5000 which is still more than 2048.

On arduino.cc forum OP has the same question, only there he mentions Arduino Due http://forum.arduino.cc/index.php?topic=520194

See amended answer. Your for loop will never end.

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


text:
Is there any way to check with Arduino UNO if a sensor is connected and ready to be read?
I would like to check the status of the sensors with Arduino UNO. For example, when I turn on the robot, I would like to check if all the sensors are connected and ready to be read or not. Maybe one sensor is unplugged and I want to detect this situation.
I read something about pull up resistors, but I didn't find any clear example of my problem. Also, I don't have any idea how to connect the resistor, how to calculate the resistor needed, as well as how to use the pull up resistor for digital and analog sensors.
Any schema, explanations and example would be very helpful!

Depends what kind of sensor. There is a a plain analogue pin connection, digital connection via spi or i2c....
Be a bit more specific.

the i2c scan sketch comes to mind, at least for that bus. you don't have to run it as a whole sketch; the code within shows how to iterate the devices on the bus, which can be called from a startup routine or whatnot...

Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.
So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.


text:
Save Data before Shutdown
I am building a positioner and I store the current position to EEPROM when the move is complete. On start up, I want the positioner to return to the HOME position. I am running an UNO powered from the USB.
My problem is that if the Arduino is turned off, I would like to stop the move and store the current position before the Arduino dies.
Note that this would also be relevant to devices like thermostats which remember the set point through a power outage.
POSSIBLE SOLUTIONS

Store position in EEPROM at each step. No, that will wear out the EEPROM.
Connect a large capacitor from +5V to Gnd. When this falls below a set level, trigger an interrupt (ISR) that stops motion and stores current position in EEPROM.

QUESTIONS

Will #2 work, and how could I program it?
Any other ideas I am missing?

Option 3: only store the position after 10 seconds of no change. Option 4: have a way of measuring the absolute position of the thing that is rotation, so there is no need to remember it's previous position. Option 5: Since you want to HOME it when power is reapplied, you could add a sensor that detects when it is in the HOME position. This is what some 3D printers do with limit-switches. They rotate the motor till the limit switch is triggered.

Why not just store the commanded position? If power should be lost, you can have it go to where it was last commanded.

@CrossRoads, that is option 6? Then option 7 is: use fram https://www.adafruit.com/product/1895 and store as often as you want.

Yes, FRAM would be great too, practically infinite # of stores (Trillions).  Store a hundred thousand a day for 100 million years.

Thermostats would save the set point to eeprom once when the set point it set by the user. On startup it would just read the set point.
The analogue pins measure relative to VCC. So if you short the analogue pint to VCC the result will remain at max even as the voltage drops.
Instead use a diode to separate the measurement point from the power supply.

simulate this circuit – Schematic created using CircuitLab
As long as power is supplied the gpio input will be high. As soon as the power is removed the gpio pin will be low and the capacitor will need hold enough charge to save the position.
However what would happen if the positioner is manipulated when the arduino is off? Most devices have a callibration routine using end-of-travel detection or something similar they run on startup to find the home position.

Thanks for all the suggestions. At first I wanted a circuit like @ratchet freaks. I wanted to keep the mechanics and circuits very simple since the positioner is 3D printed and uses a standard M3 screw to move, so that rules out limit switches and encoders.
I also realized the typical move only takes a max of 10 seconds, so I could just store the commanded position like @CrossRoads suggested. When the HOME command is given it steps back to 0.
Here is my Answer:

Store the EEPROM address of the persistent information at EEPROM[0].
At that Address store the persistent information:
Item 1: EEPROM[EEPROM[0]] The number of writes to this address block as a two byte unsigned int.
Item 2: EEPROM[EEPROM[0]+2] The commanded position as a two byte signed int.
When the number of writes gets to about 5000, increment the address of the data in EEPROM[0].

Working this way I'll gradually burn out the Arduino EEPROM, but it will take many years!

@JRobert: With that scheme, EEPROM[0] gets written every 5000 cycles.

The address is updated every 5000 cycles of 5000 writes, so about 25 million position updates. Plenty for my use!


text:
Sampling and serial transfer
I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.
int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

P.S I am new to arduino.
--edit1>>
I am using Arduino Mega 2560.

You don't state what Arduino board you are using. Perhaps you should look for a board with native USB, such as a Arduino Zero, Teensy 3.2 or the like.

Don't post two questions in quick succession about the same topic. It just annoys people, and doesn't increase your chance of a good answer.

Probably the serial port is too slow:
Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.
So you have to increase the speed for the serial port.

Thanks for the reply.
I have a doubt. One symbol in my case is two bytes per sample, with header bits giving 22 bits per sample. Since I have an additional 'x', that amounts to 33 bits in all. I want to send some 10k such samples or 330kbits per sec(> 250kbits per sec, hence the issue?). So merely increasing the serial.begin parameter should show an improvement?

You mean that one symbol is 2 bytes (digits?) Since it is sent as ASCII. You can check easily by REDUCING the speed and see if you have less speed, than you know that (at least) the serial port is the bottleneck. But increasing takes just a few seconds to try either.

Well, I increased the rate to 1000k and I am still at 6k samples.

Than the only reason I can think of is that either the procesing of getting the sensor values, or the processing of the print (some kind of overhead) takes too long ...you can try timing measurements to see what takes up most time

Read this http://yaab-arduino.blogspot.se/2015/02/fast-sampling-from-analog-input.html


text:
Cannot connect to database Ethernet Shield
I am using an LDR sensor to store its readings into the database. My code is as follows:
  #include <SPI.h>
  #include <Ethernet.h>

  const int ledPin = 13;   //the number of the LED pin
  const int ldrPin = A0;  //the number of the LDR pin

  byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

  IPAddress ip(192, 168, 1, 177); // ip of arduino

  char server[] = "192.168.1.105"; // IMPORTANT: If you are using XAMPP you
  will have to find out the IP address of your computer

   // Initialize the Ethernet server library
   EthernetClient client;

   void setup() {

   // Serial.begin starts the serial connection between computer and Arduino
   Serial.begin(9600);
   pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
   pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
   // start the Ethernet connection
   Ethernet.begin(mac, ip);

 }

Next, I wrote the setup code:
 void loop() {

  int ldrStatus = analogRead(ldrPin);   //read the status of the LDR value

  //check if the LDR status is <= 300
  //if it is, the LED is HIGH

  if (ldrStatus <=300) {

   digitalWrite(ledPin, HIGH);               //turn LED on

   }
 else {

digitalWrite(ledPin, LOW);          //turn LED off

}

// Connect to the server (your computer or web page)
if (client.connect(server, 80)) {
client.print("GET /info.php?"); // This
client.print("value="); // This
client.print(ldrStatus);
client.println(" HTTP/1.1"); // Part of the GET request
client.println("Host: 192.168.1.105");
client.println("Connection: close"); // Part of the GET request telling the
server that we are over transmitting the message
client.println(); // Empty line
client.println(); // Empty line
client.stop();    // Closing connection to server

}

else {
// If Arduino can't connect to the server (your computer or web page)
Serial.println("--> connection failed\n");
}

// Give the server some time to recieve the data and store it. I used 10
seconds here. Be advised when delaying. If u use a short delay, the server
might not capture data because of Arduino transmitting new data too soon.
delay(1000);
}

The problem is that when I try connecting to database, it gives a database connection failed. I have crosschecked the ip address of my computer and have even logged into it using xampp to check if it is working.
However, the problem is still persistent.

Which shield are you using?

The problem is in your info.php script. It has nothing to do with the Arduino.

you get "--> connection failed" in Serial Monitor?


text:
Wemos d1 mini code not uploading
I have a wemos d1 mini. I uploaded a code in wemos d1 mini and after that my wemos mini not working. I tried to upload another code in it even the led blink sketch and even a blank sketch but whenever I tried to do that it just shows connecting but never connects to Arduino ide.
First of all, whenever I tried to connect it to the computer or power it up, its built-in light stays bright and in the serial monitor, it shows garbage characters continuously. But when I connect GPIO 0(d3) of wemos mini to the ground and press the reset button it starts the boot mode and when I upload any code it shows connecting but never upload any code here's the code which uploaded first in it.
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

//Pin assignments
#define switch_1 3 // D5 Pin of NodeMcu
#define switch_2 14 // D6 Pin of NodeMcu
#define switch_3 12 // D7 Pin of NodeMcu
#define switch_4 13
// D0 Pin of NodeMcu
#define button 2
#define relay_1 4 //D1 Pin of NodeMcu
#define relay_2 5 //D2 Pin of NodeMcu
#define relay_3 16 //RX Pin of NodeMcu
#define relay_4 15 //D4 Pin of NodeMcu

#define LED1 1 //D0 Pin of NodeMcu

int MODE = 0;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Android-AP960A";
char pass[] = "talal123";

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "3ueT9aVLvkL60q8piJ6p5Kxx31zZ5xEC";

int switch_1_ON = 1;
int switch_2_ON = 1;
int switch_3_ON = 1;
int switch_4_ON = 1;

BLYNK_WRITE(V1)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
digitalWrite(relay_1, pinValue); // process received value
}

BLYNK_WRITE(V2)
{
int pinValue = param.asInt(); // assigning incoming value from pin V2 to a variable
digitalWrite(relay_2, pinValue); // process received value
}
BLYNK_WRITE(V3)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
digitalWrite(relay_3, pinValue); // process received value
}

BLYNK_WRITE(V4)
{
int pinValue = param.asInt(); // assigning incoming value from pin V2 to a variable
digitalWrite(relay_4, pinValue); // process received value
}

void internet() //When this device connects with internet
{
//**************************************
//Switch 1 configuration
//**************************************
if (digitalRead(switch_1) == HIGH)
{
if (switch_1_ON == 0 )
{
digitalWrite(relay_1, LOW);
Blynk.virtualWrite(V1, 0);
switch_1_ON = 1;
}
}

if (digitalRead(switch_1) == LOW )
{
if (switch_1_ON == 1)
{
digitalWrite(relay_1, HIGH);
Blynk.virtualWrite(V1, 1);
switch_1_ON = 0;
}
}
//**************************************
//Switch 2 configuration
//**************************************
if (digitalRead(switch_2) == HIGH)
{
if (switch_2_ON == 0 )
{
digitalWrite(relay_2, LOW);
Blynk.virtualWrite(V2, 0);
switch_2_ON = 1;
}
}

if (digitalRead(switch_2) == LOW )
{
if (switch_2_ON == 1)
{
digitalWrite(relay_2, HIGH);
Blynk.virtualWrite(V2, 1);
switch_2_ON = 0;
}
}
//**************************************
//Switch 3 configuration
//**************************************
if (digitalRead(switch_3) == HIGH)
{
if (switch_3_ON == 0 )
{
digitalWrite(relay_1, LOW);
Blynk.virtualWrite(V3, 0);
switch_3_ON = 1;
}
}

if (digitalRead(switch_3) == LOW )
{
if (switch_3_ON == 1)
{
digitalWrite(relay_3, HIGH);
Blynk.virtualWrite(V3, 1);
switch_3_ON = 0;
}
}
//**************************************
//Switch 4 configuration
//**************************************
if (digitalRead(switch_4) == HIGH)
{
if (switch_4_ON == 0 )
{
digitalWrite(relay_4, LOW);
Blynk.virtualWrite(V4, 0);
switch_4_ON = 1;
}
}

if (digitalRead(switch_4) == LOW )
{
if (switch_4_ON == 1)
{
digitalWrite(relay_4, HIGH);
Blynk.virtualWrite(V4, 1);
switch_4_ON = 0;
}
}
}
//********************************************

void no_internet() //When this device doesn't gets internet
{
//**************************************
//Switch 1 configuration
//**************************************
if (digitalRead(switch_1) == HIGH)
{
if (switch_1_ON == 0 )
{
digitalWrite(relay_1, LOW);
switch_1_ON = 1;
}
}

if (digitalRead(switch_1) == LOW )
{
if (switch_1_ON == 1)
{
digitalWrite(relay_1, HIGH);
switch_1_ON = 0;
}
}
//**************************************
//Switch 2 configuration
//**************************************
if (digitalRead(switch_2) == HIGH)
{
if (switch_2_ON == 0 )
{
digitalWrite(relay_2, LOW);
switch_2_ON = 1;
}
}

if (digitalRead(switch_2) == LOW )
{
if (switch_2_ON == 1)
{
digitalWrite(relay_2, HIGH);
switch_2_ON = 0;
}
}
//**************************************
//Switch 3 configuration
//**************************************
if (digitalRead(switch_3) == HIGH)
{
if (switch_3_ON == 0 )
{
digitalWrite(relay_1, LOW);
switch_3_ON = 1;
}
}

if (digitalRead(switch_3) == LOW )
{
if (switch_3_ON == 1)
{
digitalWrite(relay_3, HIGH);
switch_3_ON = 0;
}
}
//**************************************
//Switch 4 configuration
//**************************************
if (digitalRead(switch_4) == HIGH)
{
if (switch_4_ON == 0 )
{
digitalWrite(relay_4, LOW);
switch_4_ON = 1;
}
}

if (digitalRead(switch_4) == LOW )
{
if (switch_4_ON == 1)
{
digitalWrite(relay_4, HIGH);
switch_4_ON = 0;
}
}
}

void Blynk_status() // called every 3 seconds by SimpleTimer
{
bool isconnected = Blynk.connected();
if (isconnected == false)
{
MODE = 1;
digitalWrite(LED1, LOW);
}
if (isconnected == true)
{
MODE = 0;
digitalWrite(LED1, HIGH);
Blynk.syncAll();
}
}

void setup()
{
Serial.begin(115200);
Serial.println("n Starting");
pinMode(button, INPUT);
pinMode(switch_1, INPUT);
pinMode(relay_1, OUTPUT);

pinMode(switch_2, INPUT);
pinMode(relay_2, OUTPUT);
pinMode(switch_3, INPUT);
pinMode(relay_3, OUTPUT);

pinMode(switch_4, INPUT);
pinMode(relay_4, OUTPUT);

pinMode(LED1, OUTPUT);

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

digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
WiFi.begin(ssid, pass);
timer.setInterval(3000L, Blynk_status); // check if connected to Blynk server every 3 seconds
Blynk.config(auth);
}

void loop()
{
if ( digitalRead(button) == LOW ) {
WiFiManager wifiManager;
if (!wifiManager.startConfigPortal("Home Automator","1234")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
ESP.reset();
delay(3000);
}
Serial.println("connected...:)");
}
if (WiFi.status() == WL_CONNECTED)
{
Blynk.run();
}

timer.run(); // Initiates SimpleTimer
if (MODE == 0)
internet();
else
no_internet();
}

Please help me. I tried a lot to fix it but nothing happens. I checked the Com port in device manager and all the other necessary settings all were right here are the settings in Arduino ide. Please help me Thanks in advance.

what is wired to the pins of the Wemos?

Do you have the serial monitor open while you're trying to upload?

yes I also tried to upload code by closing the serial monitor

no wires are attached to wemos d1 mini

shorts on headers soldering?

no shorts on headers I double-checked all connections with multimeter

You must not have the serial monitor open while uploading. It interferes with the communication and the response from the board goes to the serial monitor not to esptool.py.


text:
Thought Dropbox was gone, but Arduino IDE kept it running. Search led to Temboo & Arduino Yun. Will it cripple my IDE to cut it out?
Just discovered that long after uninstalling Dropbox the service was still running.  I disabled it in the normal Services control panel.  It turned out to be hiding in /winndows/system32 as dbxsvc.exe
Then went a step further and did this in an Administrator CMD window:
cd /windows/system32
attrib -h -s dbxsv*.*
del dbxsvc.exe
copy con dbxsvc.exe
Nyah^Z
attrib +r dbxsvc.exe

So that should take care of that.
Upon further system searching (using Everything) discovered that Dropbox is used by software called Temboo, which is some kind of cloud-share package for coordinating Arduino Yun applications.
It turned out that it was the Arduino IDE that kept it running.
More searching led me here:
Arduino & Temboo: How It Works
Excerpt:

ON YOUR YÚN Your Arduino Yún includes two lightweight software
  components that make it easy to connect with hundreds of APIs and
  cloud services from any sketch.
First, there's a small C++ library called Temboo.cpp that comes
  bundled with the Arduino IDE. When you include this library in a
  sketch, it provides a streamlined syntax for configuring and invoking
  calls to run Temboo Choreos.
Behind the scenes, calls to Temboo are routed to a client program that
  comes packaged with your Linino base image. This client is a Python
  program that formats the Choreo execution request and uses HTTPS to
  forward the request to Temboo via the cURL utility.
THE TEMBOO PLATFORM Temboo is a scalable, fault-tolerant environment
  for running and managing smart code snippets that we call Choreos.
  Choreos can call APIs, simplify the OAuth process, send email
  messages, perform encoding, update databases, and lots more. You can
  even create your own custom Choreos. Temboo automatically generates
  the sketch code you needed to call these processes, making it simple
  to get up and running with any service from your Yún.
The request from the Yún's temboo client causes the Choreo specified
  in your sketch code to be executed on the Temboo platform. In many
  cases, this means assembling your inputs into the format expected by a
  third-party API, performing the API interaction, handling errors, and
  dispatching filtered results back to the Yún via HTTPS. The results
  are made available to your Arduino sketch by way of Process’s Stream
  methods.

I only use the standard Arduino IDE and regular Arduino Unos and Nanos.  Sure some are Chinese-made, and some use the CH340 connection type.
I do not want my system reaching out through the firewall to any cloud-based services, nor do I appreciate that the Arduino IDE thwarted my earlier effort to disable and remove Dropbox.
I get that it came bundled with the standard Arduino IDE.
So my question is whether anyone knows if it will damage anything if I remove this junkware?
--ADDENDUM - Why to dump Dropbox:
The Dropbox hack is real
Excerpt:

Motherboard reported on what had been rumoured for some time, namely
  that Dropbox had been hacked.
Not just a little bit hacked and not in
  that "someone has cobbled together a list of credentials that work on
  Dropbox" hacked either, but proper hacked to the tune of 68 million
  records.
Very shortly after, a supporter of Have I been pwned (HIBP)
  sent over the data which once unzipped, looked like this:
(The Dropbox data across 4 text files)
What we've got here is two files with email address and bcrypt hashes
  then another two with email addresses and SHA1 hashes. It's a
  relatively even distribution of the two which appears to represent a
  transition from the weaker SHA variant to bcrypt's adaptive workload
  approach at some point in time. Only half the accounts get the "good"
  algorithm but here's the rub: the bcrypt accounts include the salt
  whilst the SHA1 accounts don't. It's just as well because it would be
  a far more trivial exercise to crack the older algorithm but without
  the salts, it's near impossible.
At first glance the data looks legit and indeed the Motherboard
  article above quotes a Dropbox employee as confirming it.

To me it looks like the Temboo website is a gateway to Dropbox. The Yun (and the IDE) have nothing at all to do with communication with Dropbox, nor have any software that can do it. The Yun talks to Temboo. Temboo talks to Dropbox.

And if you're scared someone may have your password from some arbitrary point in the past, then change your password, as well as on any other sites you used the same password.

There is no Dropbox software included with ANY version of the Arduino IDE, nor installed on any Linux based Arduino board.
That is not how Temboo and Dropbox work.
You have Temboo as a (source code) library which you can compile into your sketch, and as a user-agent that runs on the Linux portion of the Yùn. That then forwards a request to the Temboo web servers detailing what operations you want to perform on what services.
It is then the Temboo web servers that connect to Dropbox (or whatever service you want to use) and perform operations on your behalf.
If you have Dropbox software installed on your computer it is not the fault of the Arduino IDE.

Dropbox was removed months ago.  That's why I was so surprised to see the service running.


text:
I was working on ESP module and got some errors. Can anyone please help to resolve those errors?
Code;
#include <Keypad.h>
#include <Servo.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>

const char* ssid = "";//put your wifi network name here
const char* password = "";//put your wifi password here
const char* mqtt_server = "broker.hivemq.com";

WiFiClient espClient;
PubSubClient client(espClient);

const byte n_rows = 4;
const byte n_cols = 4;

char keys[n_rows][n_cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte colPins[n_rows] = {D3, D2, D1, D0};
byte rowPins[n_cols] = {D7, D6, D5, D4};

Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);
Servo myservo;
String passcode="";
String myPasscode="5432"; //predefined passcode, change as per your desire

void setup(){
  Serial.begin(115200);
  myservo.attach(15); //attach the servo on pin D8)
  myservo.write(150);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {
    delay(100);
  // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
      delay(500);
      Serial.print(".");
    }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  String message;

  for (int i = 0; i < length; i++) {
    //Serial.print((char)payload[i]);
    message+=(char)payload[i];
  }
  if(message==myPasscode){
    publish("Approved");
    dispatchMoney();
  }else{
    publish("Denied");
  }
  Serial.println();
  Serial.println("-----------------------");

}

void publish(String msg){

     char message[100];
     msg.toCharArray(message,100);
    client.publish("/ABC/ATM/ACK", message);
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client.subscribe("/ABC/ATM/RCV");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()

void loop(){

  if (!client.connected()) {
      reconnect();
    }
    client.loop();

  char myKey = myKeypad.getKey();

  if (myKey != NULL){
    if(myKey =='#'){
      Serial.print("You entered: ");
      Serial.println(passcode);
      if(passcode == myPasscode){
        Serial.println("Your are welcome");

        dispatchMoney();

      }else{
        Serial.println("Password did not match");

      }
      passcode="";
    }else{

      passcode+=myKey;

    }
    delay(200);
  }
}

void dispatchMoney() {
  Serial.println("Dispatching money...");
  myservo.write(90); //rotates the motor counterclockwise at slow speed
  delay(5000);
  myservo.write(150); //rotates the motor counterclockwise at slow speed

}

ERROR:
sketch_apr28a.b:24:25: error: 'D3' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                         ^
sketch_apr28a.b:24:29: error: 'D2' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                             ^
sketch_apr28a.b:24:33: error: 'D1' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                                 ^
sketch_apr28a.b:24:37: error: 'D0' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                                     ^
sketch_apr28a.b:25:25: error: 'D7' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                         ^
sketch_apr28a.b:25:29: error: 'D6' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                             ^
sketch_apr28a.b:25:33: error: 'D5' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                                 ^
sketch_apr28a.b:25:37: error: 'D4' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                                     ^
sketch_apr28a.b:27:1: error: 'Keypad' does not name a type
 Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);
 ^
C:\Users\Malini\Documents\Arduino\sketch_apr28a.b\sketch_apr28a.b.ino: In function 'void loop()':
sketch_apr28a.b:124:16: error: 'myKeypad' was not declared in this scope
   char myKey = myKeypad.getKey();
                ^
Multiple libraries were found for "Servo.h"
 Used: C:\Users\Malini\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\Servo
 Not used: C:\Users\Malini\Documents\Arduino\libraries\ServoESP32
 Not used: C:\Users\Malini\Downloads\Arduino\libraries\Servo
exit status 1
'D3' was not declared in this scope

select a Lolin (Wemos) or NodeMcu board in Tools menu


text:
Can a push button be used for TFT LCD screens?
I am trying to link my TFT LCD touch screen to a few push buttons. May I enquire why my code is not working? I'm trying to link the screen and the button so I'm trying to make the image display a flower if the button is not pushed and the tiger only if pushed.
At the moment this code ends up displaying both images at once and the button whether or not the button is pushed.
My components include a 2.8" TFT LCD screen and an Arduino Mega

#include <SD.h>
#include <SPI.h>
#include <LCD_GUI.h> //Core graphics library
#include <LCD_KBV.h> //Hardware-specific library

LCD_KBV mylcd(ILI9341,A3,A2,A1,A0,A4); //model,cs,cd,wr,rd,reset

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

#define PIXEL_NUMBER  (mylcd.Get_Display_Width()/4)
#define FILE_NUMBER 4
#define FILE_NAME_SIZE_MAX 20

const int buttonPin = 41;
int buttonState = 0;

uint32_t bmp_offset = 0;
uint16_t s_width = mylcd.Get_Display_Width();
uint16_t s_heigh = mylcd.Get_Display_Height();
//int16_t PIXEL_NUMBER;

char file_name[FILE_NUMBER][FILE_NAME_SIZE_MAX];

uint16_t read_16(File fp)
{
    uint8_t low;
    uint16_t high;
    low = fp.read();
    high = fp.read();
    return (high<<8)|low;
}

uint32_t read_32(File fp)
{
    uint16_t low;
    uint32_t high;
    low = read_16(fp);
    high = read_16(fp);
    return (high<<8)|low;
 }

bool analysis_bpm_header(File fp)
{
    if(read_16(fp) != 0x4D42)
    {
      return false;
    }
    //get bpm size
    read_32(fp);
    //get creator information
    read_32(fp);
    //get offset information
    bmp_offset = read_32(fp);
    //get DIB infomation
    read_32(fp);
    //get width and heigh information
    uint32_t bpm_width = read_32(fp);
    uint32_t bpm_heigh = read_32(fp);
    if((bpm_width != s_width) || (bpm_heigh != s_heigh))
    {
      return false;
    }
    if(read_16(fp) != 1)
    {
        return false;
    }
    read_16(fp);
    if(read_32(fp) != 0)
    {
      return false;
     }
     return true;
}

void draw_bmp_picture(File fp)
{
  uint16_t i,j,k,l,m=0;
  uint8_t bpm_data[PIXEL_NUMBER*3] = {0};
  uint16_t bpm_color[PIXEL_NUMBER];
  fp.seek(bmp_offset);
  for(i = 0;i < s_heigh;i++)
  {
    for(j = 0;j<s_width/PIXEL_NUMBER;j++)
    {
      m = 0;
      fp.read(bpm_data,PIXEL_NUMBER*3);
      for(k = 0;k<PIXEL_NUMBER;k++)
      {
        bpm_color[k]= mylcd.Color_To_565(bpm_data[m+2], bpm_data[m+1], bpm_data[m+0]);
        m +=3;
      }
      for(l = 0;l<PIXEL_NUMBER;l++)
      {
        mylcd.Set_Draw_color(bpm_color[l]);
        mylcd.Draw_Pixel(j*PIXEL_NUMBER+l,i);
      }
     }
   }
}

void setup()
{

    Serial.begin(9600);
    pinMode(buttonPin, INPUT);
   mylcd.Init_LCD();
   mylcd.Fill_Screen(BLUE);
   //s_width = mylcd.Get_Display_Width();
   //s_heigh = mylcd.Get_Display_Height();
   //PIXEL_NUMBER = mylcd.Get_Display_Width()/4;
   if(PIXEL_NUMBER == 60)
   {
       strcpy(file_name[0],"flower.bmp");
       strcpy(file_name[1],"tiger.bmp");
       strcpy(file_name[2],"tree.bmp");
       strcpy(file_name[3],"RedRose.bmp");
   }
   else
   {
       strcpy(file_name[0],"01.bmp");
       strcpy(file_name[1],"02.bmp");
       strcpy(file_name[2],"03.bmp");
       strcpy(file_name[3],"04.bmp");
   }
  //Init SD_Card
   pinMode(10, OUTPUT);

    if (!SD.begin(10))
    {
      mylcd.Set_Text_Back_colour(BLUE);
      mylcd.Set_Text_colour(WHITE);
      mylcd.Set_Text_Size(1);
      mylcd.Print_String("SD Card Init fail!",0,0);
    }
}

void loop()
{

 buttonState = digitalRead(buttonPin);

    File bmp_file;
    if (buttonState == HIGH)
    {bmp_file = SD.open(file_name[0]);
      } else {bmp_file = SD.open(file_name[1]);
      }

       if(!bmp_file)
       {
          mylcd.Set_Text_Back_colour(BLUE);
         mylcd.Set_Text_colour(WHITE);
         mylcd.Set_Text_Size(1);
         mylcd.Print_String("didnt find BMPimage!",0,10);
         while(1);
        }

          draw_bmp_picture(bmp_file);
         bmp_file.close();
         delay(2000);
     }

First of all, I suggest you to keep your source code tidy, this makes a lot easier to follow the flow.
As I don't know the library you are using, I'm assuming you have tested loading one single image works as expected in which case you probably need to wipe the screen before drawing a new image: I can't tell for sure because you didn't mention which library you are using (a link would have helped).
If there's a function named clear, emptyBuffer or similar, then you should call it before drawing the image, otherwise, you probably have to draw a filled rectangle in the same area where you are going to put your image.


text:
Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client
I am running into an issue with a loop call on an Arduino MKR1000. I have tried the solutions suggested in this question and it usually works for 5 minutes and then collapses.  I am trying to make two calls to different APIs every 10 seconds and update something on the Arduino accordingly, but the loops seem to be getting out of sync after a few minutes. Here is the code - I tried to shorten it...

#include <Time.h>
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"

// put your local wifi info here
const char* ssid     = SECRET_SSID;
const char* password = SECRET_PASS;

const char* host = "bustime.mta.info";

void setup() {
  Serial.begin(9600);
  delay(10);
 // connecting to a WiFi network
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(". ");
  }
}

void loop() {
  Serial.println("START THE LOOP");
  // Use WiFiclient class to create TCP connections
  WiFiClient client;
  WiFiClient client2;
  char * serviceDeliveryString = new char[40]();
  strcpy(serviceDeliveryString, "/ServiceDelivery");
  char * responseTimestampString = new char[40]();
  strcpy(responseTimestampString, "<ResponseTimestamp>");
  char * TString = new char[40]();
  strcpy(TString, "T");

  if (!client.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  //connect to schedule data
  if (!client2.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  char * req1full = new char [100]();
  strcat(req1full, "GET /api/siri/stop-monitoring.xml?key=KEY&OperatorRef=MTA");
  strcat(req1full, " HTTP/1.1");
  client.println(req1full);
  client.println("Host: bustime.mta.info");
  client.println("Connection: close\r\n");

  char * req2full = new char [100]();
  strcat(req2full, "GET /api/where/schedule-for-stop/MTA_");
  strcat(req2full, stopNum);
  strcat(req2full, ".xml?");
  strcat(req2full, "key=KEY HTTP/1.1");
  Serial.println(req2full);
  client2.println(req2full);
  client2.println("Host: bustime.mta.info");
  client2.println("Connection: close\r\n");

  //Pause long enough for the connection to happen. Make this longer if you have issues.
  delay(1000);

  while(client.available()){
    if (client.findUntil(responseTimestampString, serviceDeliveryString)){
      Serial.println("inside client...");
      client.findUntil(TString, serviceDeliveryString);
      String mtaTime = client.readStringUntil('.');
      Serial.println(mtaTime);
    }
    delay(10);
  }

  while(client2.available()){
    if (client2.findUntil("<currentTime>", "/data")){
      Serial.println("inside client2...");
      String mtaTime2 = client2.readStringUntil('<');
      Serial.println(mtaTime2);
    }
    delay(10);
  }

  client.stop();
  client2.stop();
  delay(9000);

}

The output starts out looking good:
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:38
inside client...
22:13:38
inside client2...
1541211218146
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:51
inside client...
22:13:51
inside client2...
1541211231815
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:14:04
inside client...
22:14:04
inside client2...
1541211244465

But eventually something seems to happen with the loops and this is the final output, when it should keep running:
inside client...
22:19:02
inside client...
22:19:02
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP

Any suggestions for how to fix this?

is there a restriction on the frequency or the number of API calls to bustime.mta.info?

No, I don't believe so.

Hint: Possible memory leak. A lot of "new" but few "delete" (malloc/free).

thanks @MikaelPatel, I have cut out the 'new' and it seems to be working okay.

You keep calling new to allocate memory but you never free it.  This is a memory leak and eventually you run out.  Instead of constantly creating new arrays, why don't you make those global or static.  Or even just local arrays if you don't need them to be persistent.  On a microcontroller you really don't want to be using new unless absolutely necessary.

I used "new" so that all the entries would be initialized as missing. I could move all the array declarations to before loop() though. Or maybe in setup()? THANK YOU for responding!

What do you mean by "initialized as missing".  That phrase doesn't make any sense to me.

If you put the array definitions in setup then they'll be local to setup and you can't use them in loop.

If you want to use "dynamic" allocation like that, consider using alloca(), since it allocates the space on the stack and it's automatically freed when the function finishes.


text:
Arduino Uno will not connect to MAC computer running Sierra
I purchased an Arduino Uno. I am trying to set it up, but when I got to the "port" on my MAC, there is no option to select anything related to my board. The only connections the port tab allows me to connect to is the bluetooth incoming port, which is not correct because it gives me errors when I try to set up the UNO to block on and off for 1 second. I know this is the legit Arduino Uno, so why is the bluetooth not connecting?

Your board is plugged into a the Mac via a USB cable, and the boards power LED is lit? There should be an entry in the Tools | Ports menu that doesn't appear when the board is not plugged in. And you have to close and reopen the menu each time you plug/unplug a board; the menu only updates each time you open it. Are you sure the USB cable is a full cable - data wires as well as power? Not all of them are. Then try another cable, another port, another Arduino, another Mac, until you've eliminated the faulty component.

I assume you have installed Arduino IDE on your mac and connecting board to mac using USB cable. Many time it happens due to driver or OS reason. Just plug the Arduino to another USB port and it should work.


text:
Arduino Program Memory Ran Out
I have a Arduino sketch I made and I have run out of dynamic memory on my Arduino  Nano. How could I possibly reduce the amount of memory the program takes? (I'm not that good at this stuff)
P.S: The code is here:

#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const int chipSelect = 4;

#define OLED_RESET 5
Adafruit_SSD1306 display(OLED_RESET);

#if (SSD1306_LCDHEIGHT != 64)
#error("Fix Height");
#endif

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

#define CHARWIDTH           5
#define CHARHEIGHT          8
#define AXISWIDTH           (2 + 1)
#define VISIBLEVALUEPIXELS  (128 - AXISWIDTH)
#define NUMVALUES           (2 * VISIBLEVALUEPIXELS)

#define TRIGGER_ENABLE_PIN       2
#define SCREEN_UPDATE_ENABLE_PIN 3

byte values[NUMVALUES];
int pos = 0;
int count = 0;
unsigned long readStartTime = 0;
int sampleRate = 1;

void displayln(const char* format, ...)
{
  char buffer[32];

  va_list args;
  va_start(args, format);
  vsprintf(buffer, format, args);
  va_end(args);

  int len = strlen(buffer);
  for (uint8_t i = 0; i < len; i++) {
    display.write(buffer[i]);
  }
}

// Draws the graph ticks for the vertical axis
void drawAxis()
{
  // graph ticks
  for (int x = 0; x < 2; x++) {
    display.drawPixel(x,  0, WHITE);
    display.drawPixel(x, 13, WHITE);
    display.drawPixel(x, 26, WHITE);
    display.drawPixel(x, 38, WHITE);
    display.drawPixel(x, 50, WHITE);
    display.drawPixel(x, 63, WHITE);
  }
}

// Draws the sampled values
void drawValues()
{
  int start = 0;

  if ( digitalRead(TRIGGER_ENABLE_PIN) ) {
    // Find the first occurence of zero
    for (int i = 0; i < NUMVALUES; i++) {
      if ( values[i] == 0 ) {
        // Now find the next value that is not zero
        for (; i < NUMVALUES; i++) {
          if ( values[i] != 0 ) {
            start = i;
            break;
          }
        }
        break;
      }
    }
    // If the trigger point is not within half of our values, we will
    // not have enough sample points to show the wave correctly
    if ( start >= VISIBLEVALUEPIXELS )
      return;
  }

  for (int i = 0; i < VISIBLEVALUEPIXELS; i++) {
    display.drawPixel(i + AXISWIDTH, 63 - (values[i + start]), WHITE);
  }
}

// Shows the time taken to sample the values shown on screen
void drawFrameTime(unsigned long us)
{
  display.setCursor(9 * CHARWIDTH, 7 * CHARHEIGHT - 2); // almost at bottom, approximately centered
  displayln("%ld us", us);
}

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

void setup() {

  // Set up the display
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize with the I2C addr 0x3D (for the 128x64)
  display.setTextColor(WHITE);

  pinMode(TRIGGER_ENABLE_PIN, INPUT);
  pinMode(SCREEN_UPDATE_ENABLE_PIN, INPUT);
    // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("init start");

  if (!SD.begin(chipSelect)) {
    Serial.println("fail");
    // don't do anything more:
    while (1);
  }
  Serial.println("init ok");
}

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

void loop() {

  // If a sampling run is about to start, record the start time
  if ( pos == 0 )
    readStartTime = micros();

  // If this iteration is one we want a sample for, take the sample
  if ( (++count) % sampleRate == 0 )
    values[pos++] = analogRead(0) >> 4; // shifting right by 4 efficiently maps 0-1023 range to 0-63

  // If we have filled the sample buffer, display the results on screen
  if ( pos >= NUMVALUES ) {
    // Measure how long the run took
    unsigned long totalSampleTime = (micros() - readStartTime) / 2;     // Divide by 2 because we are taking twice as many samples as are shown on the screen

    if ( !digitalRead(SCREEN_UPDATE_ENABLE_PIN) ) {
      // Display the data on screen
      display.clearDisplay();
      drawAxis();
      drawValues();
      drawFrameTime(totalSampleTime);
      display.display();
    }

    // Reset values for the next sampling run
    pos = 0;
    count = 0;
  }
  String dataString = "";

  // read three sensors and append to the string:
  for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
      dataString += ",";
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}

Don't use String. Put your string literals in flash with F(...).

Where is VISIBLEVALUEPIXELS defined? I get an 'undefined' error for it from the compiler when I try to compile your code. 2. Are you sure you're running out of program memory and not data memory? Please show the error message. Did it occur at compile time or at run time?

whoops. i accidentaly stuffed it up before and forgot to save

Done. Now use the code above and compile it. The reason it didn't work before is because I renamed VISIBLEVALUEPIXELS to visval

Just to reiterate JRobert's point; Why do you suspect the program memory has run out? could you please post the error message that you are getting. I also think you are running out of SRAM and not the program Flash.

It just says the dynamic memory has ran out

Hint: Did you do a memory budget? How much memory does each library take? The rough numbers are: Adafruit_SSD1306 1K, SD 0.5K and your sketch 0.25K+. That leave less than 250 bytes for other global variables, stack and heap. And the Arduino IDE will give a warning.

What are your options? Buy an Arduino with more SRAM (Arduino Mega). Reduce the memory usage by Adafruit_SSD1306 by implementing you own library that does not need the 1K buffer. Rewrite SD so that you only use the 512 K byte when needed, etc. The first step is to remove all unnecessary SRAM usage such as static string literals (e.g. use the F() macro).

Few things to consider :

Each variable in your program take memory, try to use the smallest datatype ( don't use a float if you need an int for example).
Eliminate strings
Reduce the usage of array
Reduce your code size by using function for redudant task
Avoid using digital and analog red/write. Use port manipulation instead (link here)
Modify library to remove unused code inside
Use ICSP programmer instead of serial bootloader
Simplify your code for reducing its size.

Or simply ...
Use another board such as STM32 ou bigger ATmega chip with more RAM and bigger ROM size ...


text:
Does NodeMCU have some protection against wrong connections that could kill a computer USB?
I know some computer USB could handle some bad connection (by blocking the port, which need to reboot the computer). But I wonder if a NodeMCU 8266 offers some protection.

Most USB ports are shut down when an over-current event is detected.
There is nothing in a NodeMCU that can prevent an over-current event in the case of things like short circuits. The 5V (or VIN on some versions) pin is directly (or sometimes via a single diode) connected to the 5V pin of the USB. Cause a short on the 5V pin and you cause a short on the USB.
Protection is designed to be at the port level not the device level so that devices don't have to be forced to comply to protection "standards" that would drive up costs and result in devices being non-compliant and risk damaging the computer.
If you find that you are often causing shorts on the 5V pin and killing (albeit temporarily) your USB ports you should change your working practices.
It can be good to always connect your devices to an external powered USB hub instead of directly to your computer. That way if you kill a port you can just unplug the hub and plug it back in again to reset all the ports. No need to reboot your computer.
Cheap hubs often just have a simple PTC fuse instead of proper over-current protection which can actually be more useful for device developers since the port won't be disabled, just the external power shut off.
Most Arduino boards do incorporate a PTC fuse in the USB power circuitry, but NodeMCU and similar boards don't.

Thanks! But instead of USB hub, shouldn't it instead be an "USB insulator?" such as this one https://www.ebay.com/itm/1500V-USB-to-USB-Isolator-Board-Protection-Isolation-ADUM4160-ADUM3160-Module/152382773951?hash=item237ab89abf:g:2d8AAOSwEzxYbQMG

You could use an isolator, but a hub is just as good in this situation and a whole lot more useful.

Would even the cheapest hub do it? (Not sure of the grammar of this one!)


text:
How do I make Arduino IDE use a specific version of GCC in Debian?
Using Raspbian Stretch.
I installed gcc-4.9 with specified version. Then I installed arduino (2.1.0.5) which in turn pulled gcc 4.6. When I try to compile Marlin in it, it says

Marlin requires C++11 support (gcc >= 4.7, Arduino IDE >= 1.6.8).
  Please upgrade your toolchain.

How do I make Arduino IDE use the correct version of GCC?

I think this is a question to ask on Debian forum and not here.

Why on earth did you install such an ancient version? Delete it and download the current (i.e., released this decade) version.

@Majenko, these are the newest versions. https://packages.debian.org/stretch/gcc https://packages.debian.org/stretch/arduino

No, those are versions that were submitted to Debian years ago. You don't install Arduino from the Debian repositories. You haven't done for many many years. Download the Arduino IDE from the Arduino website.

As Majenko pointed out, I should have used a tarball from the official site instead of the repositories. Which makes me wonder why that package wasn't deprecated or something...

Installing the Arduino package from the Debian repository (or the one for derived distros like Ubuntu) performs the useful purpose of setting up all the necessary permissions for the Arduino IDE to work. Those permissions are NOT automatically removed when you uninstall the package.
The simplest way to get a working Arduino install:
1. Install Arduino from the repo
2. Immediately uninstall it
3. Get a current version of Arduino from arduino.cc and install that


text:
can't return float value from function
I want to put a 2 seconds delay to temperature reading but the millis() delay is not applying.

#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

Time t;
LiquidCrystal_I2C lcd(0x27, 16, 2);
DS3231  rtc(SDA, SCL);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

const int OnHour = 23;
const int OnMin = 42;
const int checkTemp = 2000;
const int checkTempinterval = 0;

void setup() {
  Serial.begin(115200);
  pinMode(3, OUTPUT);
  lcd.begin();
  lcd.backlight();
  rtc.begin();
}
void loop() {
  t = rtc.getTime();
  float testTemp;
  testTemp = temperature();
  lcd.setCursor(0,0);
  lcd.print(testTemp);
  lcd.print("   ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print(rtc.getDOWStr());
  lcd.print("   ");
  lcd.print(rtc.getDateStr());
  if(testTemp >= 28){
    digitalWrite(3,HIGH);
  }else{
    digitalWrite(3,LOW);
  }
//  if(t.hour == OnHour && t.min == OnMin){
//    digitalWrite(3,HIGH);
//  }else{
//    digitalWrite(3,LOW);
//  }
}
float temperature(){
  unsigned long currenttime = millis();
  if(currenttime - checkTempinterval >= checkTemp){
  sensors.requestTemperatures();
  float testTemp = sensors.getTempCByIndex(0);
  currenttime = checkTempinterval;
  return testTemp;
  }
}

First of all, not all execution paths are returning the value, second of all, why are you doing: currenttime = checkTempinterval;, it's pointless as it won't exist anymore after the return.

There is nothing called "minis" in your code example.

@KIIV so i can't return value from sensors.getTempCByIndex(0);? it's reading the temp but the delay is not applying...

You can, but code is not doing it in case the if condition fails.

@KIIV so what's the solution?

Delete it all, and start from a scratch. Enable all warnings! Don't use any branches in temperature(), maybe even forget about functions, until you don't understand concept of local variables and it's scope and existence. Just use delay(2000), read rtc, request temperature, print results

that's a question and by kindly answering it you can help me to "understand the concept of local variables" and i don't want to use delay!

Also asked here: https://forum.arduino.cc/index.php?topic=621590.0

@Jot "Detective achievement unlocked"!

Moreover what is the question?  I don't see one.

I see 2 problems with your code:

Returning a value from a function: If you want to return a value from a function, you will have to make sure, that in any case the return x statement is executed inside the function in the temperature() function you currently have this if statement:
if(currenttime - checkTempinterval >= checkTemp){

Inside of it is the only return statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).
Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example -300; the error value should not be found inside valid data)? Then do so after the if statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the if statement.
If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.
Doing the millis() code correctly: What you are doing wrong here, it that you update the wrong variable inside the if statement. Currently you write the value of checkTempinterval (which is the time of the last measurement) to the variable currenttime. The variable currenttime was declared locally (meaning inside the function) by using
unsigned long currenttime = millis();

Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the return statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.
What you actually meant to do, was to do it vice versa:
checkTempinterval = currenttime;

checkTempinterval is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.
Very important: Currently checkTempinterval is defined as const int meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use int here, because it's value range goes only up to 32767, which is 32 seconds when used with millis(). After that, it will overflow to negative values. Better use the type of millis() return value: unsigned long. It has 4 byte (instead of ints 2 byte) and will only overflow after 49 days. If you only use this variable type for things with millis(), even this overflow will not be a problem.

You can use the millis() function to create a "timer" that will get the sensor reading every 2 seconds. The sketch BlinkWithoutDelay.ino, should come with the Arduino IDE, but if not, you can find it here: BlinkWithoutDelay.
I've used that exact sketch with some modifications to display the results on the Serial Monitor instead of blinking an LED. When you are creating something, using the Serial Monitor can help you to De-bug your sketch.
Please read the code comments in the following sketch. Once you have this working with your code, then you could decide if you need a function or not.
// Store the last time you checked the sensor.
unsigned long previousMillis = 0;

// interval at which to checked the sensor (milliseconds)
const long interval = 2000;

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

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check to see if it's time to check the sensor reading.
  if (currentMillis - previousMillis >= interval) {
    // save the last time you checked the sensor.
    previousMillis = currentMillis;

    // This is where you add the code that checks the sensor.

    // Test output.
    Serial.println("Checking Sensor");
  }
}


text:
Adafruit Micro-SD breakout not initializing on MEGA 2560
]
[I am having quite a bit of trouble trying to get my Arduino MEGA 2560 to read my micro-SD card. My wiring is as follows:
Breakout    Arduino
5v            5v
Gnd           Gnd
CLK           52
DO            50
DI            51
CS            53
CD            Was not connected and then connected to 47 (neither worked)

Here is my code:

#include <Wire.h> //library necessary to use I2C communications bus
#include <Adafruit_Sensor.h>
#include <Adafruit_BME680.h>
#include <SD.h>
#include <SPI.h>

const uint8_t chipSelect = 53; //chipSelect pin for the SD card Reader
const uint8_t cardDetect = 47;

File CO2Data; //Data object you will write your sensor data to

void setup() {
Serial.begin(115200);//"begins" the serial monitor so you can print stuff out when connected to the computer (set baud rate to 115200)
Wire.begin ();//begins the I2C communications bus so it can talk to the K33

Serial.print("Initializing SD car...");
pinMode(53, OUTPUT);

if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
File CO2data = SD.open("datalog.txt", FILE_WRITE);
if (! CO2data) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
 while (1) ;
}}

The SD card is formatted to FAT32.
Thank you for any help!

try the CardInfo example

I did try to cardinfo example and came up with the following message:Initializing SD card...initialization failed. Things to check:

is a card inserted?
is your wiring correct?
did you change the chipSelect pin to match your shield or module?

Update: I set chipselect  to 10 in the Cardinfo example and card is found and present. However, it still won't run in my sketch. I have gone through trying different pin combinations.

do you have some shield on the Mega or some other devices wired to it?

I do, I have a couple of things wired to the MEGA: Adafruit BME680 (temp pressure) using the I2C interface (SCL wired to 21 and SDA wired to 20) and a KC-30 CO2 sensor wired to pins 10 and 9.

SOLVED: The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved!  (Check your voltages)

what is a non-analog ground in this case?

From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.

did you try one of the ground pins between 5 V pin and Vin pin?

I tested the Vin on the micro-SD between the ground on my voltage regulator board (which drops battery incoming from 12 and outputs 5 to the MEGA), it read fine. But when measuring between the Vin pin on the Micro-Sd and the ground on the micro-Sd my voltage was only 1.5.  So I just reran that ground wire.

The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).
From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.

It's OK to accept your own answer as the solution to the problem.


text:
Is it possible to use an already working Barebones (328P) via FTDI to load a bootloader onto another 328P?
When testing / developing a proto type using a barebones board with 328P, I usually add a Serial to TTL adapter, which then allows me to modify and upload code as well as being able to the use Serial Monitor.
My question is, is it also possible to use the barebones via a Serial to TTL adapter to load a bootloader onto a blank 328P? I've tried once but it was unsuccessful. The setup was exactly the same as what I would normally do to load a bootloader onto blank chips using an UNO to barebones. The only difference was that I I replaced the UNO with an already working barebones and connected to the PC via FTDI.
I simply want to build a dedicated setup using ZIFF sockets to load a bootloader and code onto a blank 328P chips. If the answer is "yes" that's good enough for me to carry on again. I just don't want to waste valuable time when it is actually not possible at all. My ultimate is to get round to understanding all the options around  communications SPI etc etc.
All help will be greatly appreciated.

Yes, there is no reason why this should not work. With an 328p and a USB serial chip you already have much of what an Arduino Uno is. If you want more help, you should include more information about how exactly it didn't work for you.

Thanks, at this stage I don't understand the various comm protocols. So do I understand correctly that swopping from USB cable direct to the Arduino UNO will produce the same result as me using a barebones with a USB cable via  a Serial to TTL converter.... thanks again for helping. If above is true then previous effort may have failed because of some silly mistake I made. Again Thank You for helping. When I get it going I will share my experience.

The 328p on the Uno doesn't speak USB, so the Uno has its own USB Serial chip. If you use a 328p and a USB Serial board that is just the same.

Thanks, your input is so encouraging,  done some research on "Uno has its own USB Serial chip" and Arduino Docs revealed that UNO uses the atmega8U2 chip to achieve "USB to Serial" to communicate with the 328P. Also according to the same (Arduino DOCS) article,  "...some people  call the "USB to Serial"  a  "Serial to TTL" and that basically the FTDI module achieves the same result as the atmega8U2 does. So I shall rebuild the experiment and am expecting a positive result this time. Will build a single board, ZIFF sockets, to upload Bootloader and also capable of uploading sketches as well.

No, you can't upload  bootloader without bootloader via serial port. Bootloader is the "magic" that allows uploading the FLASH through the serial port. You have to upload the bootloader to the empty chip via the ISP.

My intention was to have the first Barebones already functioning complete with bootloader installed and communicating with the PC via Serial to TTL module. The second Barebones would have a Blank 328P plugged into a ZIFF socket which I would then load Bootloader onto via the first Barebones .... looks like i'm being sent back to the drawing board.

Yes, that is possible. The first board must contain the arduino ISP sketch. The second board must be connected via the RESET, MISO, MOSI, CLK signals. see  this

Thanks, have been doing a lot on the bread board without success.... going to have a good look at the link you provided.... then carry on with bread board. PS... I have been using an UNO successfully to load bootloaders for a while now, just for fun and learning curves decided to try and build a dedicated barebone station to do bootloader and also sketches. Thanks again

So after trying all of above and not (yet) winning , I have in the mean time, simply built a dedicated barebones with single ziff socket. Do load a  bootloader onto  blank 328P I have included and wired up a 6 pin female header to receive a removable cable that allows me to link up with the ISP pins on my UNO. Then also to upload a sketch and have Serial Monitor available, I've also wired up another 6 pin female header to receive the FTDI 232 Adapter. It all works very well....  this to just to preserve my UNO. PS ZIFF socket was just to big to replace the 328 on the UNO.  Thanks to all