text:
Problems With Fading Through Neopixel Colors
I have a 20x20 matrix of neopixel LED's. I have a certain set of LED's on in different places at different times. Each one is set to mainColor. Right now mainColor is just set to strip.Color(r, g, b) but I would like to have those color fade through the spectrum. I decided the easiest way would just be to do something like this, and simply return strip.Color(r, g, b) to mainColor, then calling it to turn change the colors like so:
strip.setPixelColor(pixelNumber, mainColor(5));

Here is the code for mainColor:
    int r;
    int g;
    int b = 255;
    int _r;
    int _g;
    int _b = 255;
void Color (int FADESPEED)
{
    // fade from blue to violet
    for (_r = 0; _r < 256; _r++) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from violet to red
    for (_b = 255; _b > 0; _b--) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from red to yellow
    for (_g = 0; _g < 256; _g++) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from yellow to green
    for (_r = 255; _r > 0; _r--) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from green to teal
    for (_b = 0; _b < 256; _b++) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from teal to blue
    for (_g = 255; _g > 0; _g--) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
}

This was good but it would only return r, g, b as it was on the last iteration of the last for loop, which obviously isn't what I want. But when I un-comment the Serial.print's the values were perfect. So then I put return strip.Color(r, g, b) into each for loop, however this only returns the first iteration of the first loop, which is also not what I want. Does anyone know how in the world I can return strip.Color(r, g, b) for every iteration of every for loop? Or if not, any alternatives that would work in this situation.
Thanks, Matthew

If you return something, the loop ends. I don't know why you would return something in every iteration. That doesn't make sense. they don't do anything until the for loops are done, which takes forever - well, get rid of the delay calls. In fact, a rewrite is called for. Step back from your code, think of what you want to do, write some pseudo-code on paper, and then code when you are happy you have got a good plan.

@NickGammon That is a good idea, but I need the delay because I want the colors to fade slowly, but I will try some pseudo code...In the mean time, any ideas?

Yes, but you don't have to use delays. See How to do multiple things at once ... like cook bacon and eggs for some ideas.

Thanks @NickGammon, that site is pretty useful, I will see what I can do with that.

There appears to be a number of problems with this code.
The variables only have scope with in this function and are not static.  So they will not survive from call to call.  Every time you call this function it will be like starting over.
Putting returns in the middle of code is not good coding practice.  It is very difficult to follow and hard to debug.  It would be best to arrange your code so that there is only 1 return at the end of the function.
This code (from Adafruit) only controls 1 RGB LED.  If you are to control 40 RGB LEDs all at different stages of color changing you would need 40 copies of this function.  This is not very efficient. Instead use this function to populate one lookup table with R G B data.  Then track 40 variables, one for each RGB LED.  Use the 40 variables to lookup a specific color combination in the lookup table for each of the 40 RGB LEDs.

I have updated the code so the scope is more suitable, though it was designed to not actually matter because the last iteration of the last loop is technically the same as the first iteration of the first loop. I have also removed the extra returns, however it still only is returning the last iteration of the last loop...so back to square one with that. As for the LED's, they are all to be colored the same so it shouldn't really matter, right?

All your LEDs are to be the same color?  I didn't realize that.  So, in the original Adafruit code, a call was made to the function analogWrite() inside each of the different color changing loops.  You are trying, instead, to return that value each time you call your function mainColor().  This is very difficult to do!  I would do what the code on Adafruit's web site does.  Or, as you have already found out, if you print out the values they look correct.  So why not call the function analogWrite() from the same locations as your commented out print statements?

I am building a word clock, so they cannot all be on at the same time, if they were I would just use the rainbow cycle provided with neo pixels code library, that's why I would rather have the one color that I can call for each set of LEDs.

So, some LEDs are on and some are off.   The ones which are on all change their color in unison.  So, continuously call  the change color function.  But from that function call a function that choses which LED to light.  Only from that function make the call to strip.setPixelColor() for the LEDs which are to be lit.

Yes, I'm not home at the moment but I may have an idea. I have a for loop void that takes in an array of pixel id's, the length of that array, and also the color, I do that rather than doing a for loop every time just to make it easier for me. So every group of LEDs call that for loop void, including the color. But I just thought, seeing as though every group uses the same color, I might as well make put that color just in the for loop void, as well as the mainColor loops. I'll give that a go once I'm home, do you think that would make a difference?

Just tried that, no luck...

Changed it back now, still only returning the last value of the last for loop. Is there any alternatives I could try, do you know?

Start over using the Adafruit example code you pointed to.  Instead of calling analogWrite() with the color information like Adafruit did, you call matthewsClock() with the color information created using strip.Color().  In matthewsClock() you pick which world-clock LEDs are to be lit and which to turn off.  Then you send the color information to the ones to be lit and the color black to the ones to be off.

Still nothing, I tried it as a void and as the uint32_t, both are still only coloring the LED's as the last iteration of the last for loop (blue), and when I try to turn on 1 individual LED with strip.setPixelColor(number, r,g,b) it doesn't even turn on until it gets to that last iteration...

Another problem I just noticed is that the for loops are taking forever to iterate through...I have 3 buttons that are meant to change the time (it's a word clock) but they don't do anything until the for loops are done, which takes forever...

Since Stack Exchange Qs & As are supposed to be search-able by others, we shouldn't have long conversations here.  Never the less my advice is to start simple.  Get one feature working.  Do not add anything else until what you have works.  For example, forget about the buttons & the clock for now.  Adapt the Adafruit code to cycle one of your strip LEDs through multiple colors.  Note the Adafruit code "is" this loop() function.  It is not a function you call from a line in the loop() function.  After you get that working do what I outlined in my previous comment.


text:
How to use a digital RGB LED Strip?
I know this is probably a little bit basic but I need SERIOUS help with using my new led strip. You can see here the type of strip I have, and the packet.

It's difficult because it looks slightly different to all the other ones I've seen in tutorials so I don't really know where to start now...All I've done is cut off the ends of the wires already on there and replace them with the regular pins that I can use on the Arduino and breadboards too. Where do I have to go from here? Are there any code libraries I need to use?

My bet would be that these are WS2812B LED strips. They should be compatible with Adafruit Neopixels.

As far as I understand the DAT (Green wire) is a digital data wire. Try the following:
1. VCC to +5V pin
2. GND to GND pin
3. DAT to 2 Digital pin.
Then try to change the state of the 2 digital pin from high to low and see if anything happens... That's what I would start out with.

Interesting result, about 3 of the lights came on, and were all different colors, then I adjusted the wires and they went off, and still are off...

Worst case scenario- the board did not have resistors and you just burned them down. Do you have schematic of your led strip?

No I don't think so, I could find some but who knows if it would be the right one. Would a close up photo do?

I added one anyway, there is a tiny piece in the centre wire or the strip right next to the LED, is that a resistor?

If by that you mean the element that has letter C near it, it should be capacitor because C stands for capacitance. But it also could be resistor because they look pretty much the same. Try to find a schematic, it's pretty hard to help when I don't even know what's on the board.

@L2PA these LED strips have "constant current" drivers built in. My bet would be them being these https://www.adafruit.com/datasheets/WS2812B.pdf or https://www.adafruit.com/images/product-files/1138/SK6812%20LED%20datasheet%20.pdf

@L2PA Plus, they are "Digital LED strips" so changing the state of digital pin 2 isn't going to do a lot, unless you time it exactly right. I also wouldn't recommend driving an analog LED strip directly from Arduino..

Ok, I think I found them on aliexpress, they look exactly the same as mine so I'll try look for the schematics now, heres the link if you want to take a look, not sure if theres anything useful...http://www.aliexpress.com/item/1M-WS2812B-Full-Color-LED-strip-light-Built-in-WS2811-30-LED-30-pixels-Raspberry-Pi/32601142057.html?spm=2114.01010208.3.112.jf2vIu&ws_ab_test=searchweb201556_6,searchweb201602_3_10017_10005_10006_10034_10021_507_10022_508_10020_9912_10018_10019,searchweb201603_7&btsid=c6194586-8b45-4a24-ac33-795408b73bc3

Right, I found it, @Paul you were right, it was these: https://www.adafruit.com/datasheets/WS2812B.pdf

You're somewhat in luck, Adafruit has an "Neopixel uberguide" which is an extensive document on how to use these type of strips. They also have a library which should make programming easier.

@Paul Is this it? https://learn.adafruit.com/downloads/pdf/adafruit-neopixel-uberguide.pdf

All working now, thanks @paul for that uberguide!

I had the same issue, in every example you see wiring diagrams with 3 wires, and my ledstrip had 5 wires, but it seems the two red wires (5v) are connected and the two white wires (gnd) are connected to eachother, so basicly you have 3 wires like in every wiring diagrams  what's out there

source: Stack Exchange

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

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

sort: votes


text:
Arduino Due Port Not Found
I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:
    Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.Sketch.upload(Sketch.java:1178)
    at processing.app.Sketch.exportApplet(Sketch.java:1152)
    at processing.app.Sketch.exportApplet(Sketch.java:1124)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
    at processing.app.Serial.touchForCDCReset(Serial.java:87)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
    ... 6 more
Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
    at jssc.SerialPort.openPort(SerialPort.java:167)
    at processing.app.Serial.touchForCDCReset(Serial.java:81)
    ... 7 more
Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

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

Not sure what all that was but a simple restart of my computer seemed to fix it.

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


text:
Is my Arduino Micro bricked?
A few weeks ago I built my own Arduino Micro. Everything worked fine and it connects every time. I have built a second one, with the exact same processor schematic as the first one. It turns on, and I was able to bootload it with an Arduino Uno, just like the first one. But it will not connect to my computer.
When I plug it into my PC, the lights flash on but I get nothing. It does not show up in device manager anywhere, and its like I plugged nothing in, in the first place.
When I plug in my other Arduino Micro it works fine. But this one does not. I have tried switch PCB's (maybe the first one was bad) but nothing seems to work. I have even switched the ATMega32U4, but I still get the same issue.
When I connect my multimeter to the USB port and the corresponding D+ and D- pins on the processor, I get that there is resistance and there are no crossed connections.
I feel that at least the computer should say "Device not recognized," but I just get nothing. Is my Arduino bricked? Has anyone else had a similar problem?

I was able to bootload it ... are you really sure?

Yes I am really sure, the bootloader said done in Arduino and the Blink Sketch started running. Even if it wasn't bootloaded the ATMega32U4 should still show up in device manager.

have you tried another usb cable? ....... unplug all arduinos from the computer. remove the arduino micro driver by using the windows device manager, then plug in the bad arduino, to see if it may enumerate correctly. it is possible that windows will not talk to the second arduino because it is detecting something that does not match the first arduino (windows is pretty weird when it comes to USB devices)

Be sure to check out the answers on a very similar question: Have I bricked my Arduino Uno Problems with uploading to board


text:
Use an L293D with Arduino
I am making a 2-wheeled Arduino car controlled by T.V. remote for a science fair tomorrow. I have found a tutorial for the IR part. I brought this  L293D motor driver to control a 2-wheeled car. I am facing a problem. I know where to connect the motors (because there are indications stating M1 and M2) but I don't know where to connect the motor driver to the Arduino and to the batteries.
I checked over the net but couldn't find any tutorial for this kind of board. Also I have no experience in all this so I don't want to risk it. I don't want any code or anything, just where to connect what.
Any help is appreciated.

I searched all over the net for any documentation but i didn't find any. That's why i turned here

@LookAlterno I connected the 2 wires of motor 1 to the two headers stating M1 and connected the 2 wires of motor 2 to the two headers stating M2. I found the hex values of the Buttons of the I.R. remote and have connected the I.R.(TSOP 1738) receiver to the Arduino. I also found a tutorial but am yet to program the chip cause i want to finish the joining of the components first.

All the inputs are clearly marked.
The battery connects to +12V and GND
The Arduino's 5V and GND connect to 5V and GND.
The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.
The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.

Thanks a lot. Now I have a question. Can I power the Arduino with a 1.5 volt and the motor driver with two 9 volts battery.

No, and maybe. If the motor is 18V then yes. The Arduino can never run from 1.5V. It needs 5V minimum.


text:
How to read data from client ESP8266-01?
I need help: my Arduino is not receiving or reading from an ESP8266-01 as a client.
Actually, the ESP01-server and ESP01-client are successfully talking each other but if I attach the Arduino Uno to read the data from the server, nothing happens. It's not receiving at all.
Any help is very much appreciated.

Lua server:
-- GMKSoft
--*************************
--    ESP8266 Server
--*************************

--*************************
--  Static Configuration
--*************************
cfg =
{
    ip="192.168.255.101",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
}
wifi.ap.setip(cfg)

wifi.setmode(wifi.STATIONAP);
wifi.ap.config({ssid="GMKSoft",pwd="GMKSoftESP"});
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(8080, function(conn)
    conn:on("receive", function(conn, receivedData)
        print("Received Data: " .. receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

Client lua:
-- GMKSoft
--*************************
--    ESP8266 Client
--*************************

--*************************
--  Static Configuration
--*************************
client_ip="192.168.255.102"
client_netmask="255.255.255.0"
client_gateway="192.168.0.1"

wifi.setmode(wifi.STATION)
wifi.setphymode(wifi.PHYMODE_N)
wifi.sta.config("GMKSoft","GMKSoftESP") -- connecting to server
wifi.sta.connect()
if client_ip ~= "" then
    wifi.sta.setip({ip=client_ip,netmask=client_netmask,gateway=client_gateway})
end

tmr.alarm(1, 2000, 1, function()

     if(wifi.sta.getip()~=nil) then
          tmr.stop(1)
          print("Connected!")
          print("Client IP Address:",wifi.sta.getip())
          cl=net.createConnection(net.TCP, 0)
          cl:connect(8080,"192.168.255.101")

          tmr.alarm(2, 5000, 1, function()
            cl:send("Hello World!")
          end)

         tmr.stop(2)
         print("Going to sleep")
         wifi.sta.sleeptype(wifi.MODEM_SLEEP)
      else
         print("Connecting...")
      end
end)

Arduino Code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

I would lower the baud rate on the software serial port to 9600.  Other posts on this site suggest ESP to SoftwareSerial works better at that speed.  (You obviously need to lower ESP serial speed too)

Thank you dda for your comment, I try to lowering the bauad to 9600 of the softwareserial and hopefully I get a reading of data from ESP8266-01.

I successfully communicate with two esp01 module as a AP and STATION.
The esp01 as a server, please flash it using NodeMCU-PyFlasher-2.1, and used this bin file nodemcu-master-7-modules-2017-11-23-15-58-17-integer.bin
I build it from  here
Here is the code of the server, I'm using ESPPlorer IDE lua script:
cfg={}
cfg.ssid="GMKWiFi"
cfg.pwd="GMKSoft2627"

dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

print("ESP8266 Server")
wifi.setmode(wifi.STATIONAP);
wifi.ap.config(cfg);
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(80, function(conn)
    conn:on("receive", function(conn, receivedData)
        print(receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

Here is the Client Code, Im using Arduino IDE
#include <ESP8266WiFi.h>
const char* ssid     = "yourSSID";         // SSID
const char* password = "yourpassword";     // Password
const char* host = "192.168.4.1";         // Server IP
const int   port = 80;                    // Server Port
const int   watchdog = 5000;              // Watchdog frequency
unsigned long previousMillis = millis();

void setup() {
  Serial.begin(115200);
  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 loop() {
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;
    WiFiClient client;

    if (!client.connect(host, port)) {
      Serial.println("connection failed");
      return;
    }

    String url;
    url += "R1";

    client.print(url);
  }
}


text:
Use Arduino Uno to program the on-board Atmega328 in C
I have an Arduino Uno board.  I have seen how it is possible to program external AVR's through the Arduino Uno board, for instance an ATtiny. But I'm starting with c for atmel µc and I just want to program Atmel328's through the Arduino hardware, and being able to use the arduino pins for outputs etc.
So my question is, can I use the Arduino Uno board together with avrdude and avr-gcc to program the on-board atmel328 in C? And thus being able to use the Arduino pins for output and input?

You're question is not so clear.
But from what I understood you are asking if you can program the Atmega328 with c using low level instruction and by setting manually all the registers in order to use IO ports of atmega. If that's what you're asking I will suggest you to use you're arduino ide to program the Atmega using register names as shown on the official datasheet. Doing so you can start learn the internal parts of the micro and at the same time you can avoid buying an external programmer. But if really want to load you're program or hex file you have to buy an external programmer.
I hope that helped
PS if you are using the arduino ide and writing manually the registers remember not to set incorrectly the configuration registers because that will make you're Atmega useless and you will need to buy an external programmer.
Edit:
For better understanding you can refer to this link.
Programming arduino in c

So I can use it as any other programmer together with avrdude and avr-gcc! I don't want to use Arduino IDE, but random C libraries I may have for the ATmega328.  thanks a lot.

Yes, the Uno is designed to be very simple to program. The only extra hardware you need is a USB cable to connect it to your computer.
If you're completely new to this then the simplest way to start is by following the official "Getting Started" guide. Note that the section on drivers is particularly important.
The guide explains how to use the official Arduino IDE for programming the microcontroller. It automatically handles compiling and uploading your code via gcc and avrdude. It's technically configured to compile as C++ code, but plain C code should be fine too.
I don't recommend that IDE for long-term use though as it's really only aimed at beginners (it has a number of limitations and other problems). Using the command-line tools directly is certainly possible if you'd prefer that. However, you may also like to consider alternative IDEs which have support for Arduino plug-ins.


text:
How do I count time in seconds?
I have a statement:

if(control > 100 && control < 130)
{

  //count time 30 seconds and open pin1 for 3 seconds.

}

How can I count 30 seconds and open a pin for 3 seconds?

Arduino measures time in millis() and delay() and in milliseconds, so to convert counts of time in seconds to milliseconds would be 1000x.

A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.
The Timemark library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.
#include <Timemark.h>

Timemark turnOnWait(30000L);
Timemark turnOffWait(3000L);

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      turnOnWait.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (turnOnWait.expired()) {
      digitalWrite(pin, HIGH);
      turnOffWait.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (turnOffWait.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.
#include <Timemark.h>

const uint32_t TURN_ON_TIMEOUT = 30000L;
const uint32_t TURN_OFF_TIMEOUT = 3000L;

Timemark timemark;

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      timemark.limitMillis(TURN_ON_TIMEOUT);
      timemark.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, HIGH);
      timemark.limitMillis(TURN_OFF_TIMEOUT);
      timemark.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

The Scheduler library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:
#include <Scheduler.h>

const int pin = 4;
int control = 0;

void setup()
{
  ...
  Scheduler.start(setupController, loopController);
}

void loop()
{
  ...
  delay(1000);
}

void setupController()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loopController()
{
  ...
  if ((control > 100) && (control < 130)) {
    delay(30000L);
    digitalWrite(pin, HIGH);
    delay(3000L);
    digitalWrite(pin, LOW);
  }
  else {
    delay(100);
  }
}

Cheers!

What you can also use is non-blocking code, where delay() would block for the 30s. My suggesting makes use of millis(), one could say similar to blink without delay code example.
Here is an example of what you could place in the loop:
//declared variable stuff here

if(control > 100 && control < 130 && !toggled_bit){

    toggled_bit = true;     //to control the timing section
    start_time = millis();
}
else if (!(control > 100 && control < 130)){
    toggled_bit = false;
}

if (toggled_bit){
        test1 = millis()
    if(test1 - start_time > 30000){

        digitalWrite(1, HIGH);
            short_wait = millis();
            // wait for 3s after fist time
                if(short_wait - start_time > 33000)
                    digitalWrite(1, LOW);
                    toggled_bit = false;
                }
        }
}

// other code here

The code sets a 'flag', toggled_bit, which is checked by the if() later on in the loop, also it sets start_time. It then checks if 30s has passed and then waits an extra 3s to turn the output off after being turned on. It then resets the toggled_bit.
This will also allow you to check or do other things while waiting.

Rearrange the Blink example:
if(control>100 && control<130)
{
  //**count time 30 seconds and open pin1 for 3 seconds.**
  delay(30000);             // wait for 30 seconds
  digitalWrite(1, HIGH);    // turn the LED on (HIGH is the voltage level)
  delay(3000);              // wait for 3 seconds
  digitalWrite(1, LOW);     // turn the LED off by making the voltage LOW
}

Well 30s equals 30,000ms and the arduino comes with a native function that counts in Milliseconds so the following code should work:
Time = millis();  //time passed before entering loop…
If((control > 100) && (control < 130))
{
While (millis() < Time + 30000) //counts to Thirty seconds
{
While (millis() < Time + 3000) // counts to three seconds
{
DigitalWrite(1,HIGH);
};};};

This way you can add some code in the while loops if u want to multitask.

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


text:
DC Motor speed control by using pwm
I am using Arduino Uno, and MPU6050(3 axis imu sensors), not gate,  and L298 dc motor drive.
My algorithm is very easy.
Receive an angle how the balancing robot is tilt.
Decision speed of motors by using the angle.
For example, when robot is tilt n degrees forth or back, robot will go forth or back with speed proportional n.
My code is similar to the following code.
Sorry, it is difficult to type on my phone. TT

Angle = getComplementaryAngle();

Speed = pidCompute(abs(Angle));
// Speed range: 0 to 255

if (Angle > 0.4) {

  DigitalWrite(dirA, HIGH);

  DigitalWrite(dirB, HIGH);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else if (Angle < -0.4) {

  DigitalWrite(dirA, LOW);

  DigitalWrite(dirB, LOW);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

}

I don't know why left motor's speed is different from right motor's one.
I checked the voltage of motor pin.
Both pins' voltage are same as 11V.
I think pwm is wrong.
When Arduino makes two pwm output, it causes some problems?

You haven't told us what is going wrong. Are enA and enB both pwm pins?

As Gerben notes - not all pins are able to provide analog output. Have you chosen pins that do? Try outputting PWM to a resistor load - say 10K Ohms, observing PWM outputs and tilting the robot by hand across its range. Do the PWM output vary as expected? You have not provided a circuit diagram , model of motors, voltages used, which pins are doing what and more. You do not say what dira, dirb  do or how or even why. We can guess but may guess wrong. There is MUCH room for things to be wrong in the areas you have not told us about.

ah... sorry. I will change my question and ask again.

Your code is "similar" to that or that is your code?  why don't you post the actual code?  What a waste of everyone's time it would be if your error is something that is different in your "real" code.


text:
undefined reference to `PPMintIn::PPMintIn(int)'
I am making a new library that will utilize PinChangeInt's library.
My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.)
Since i understand OOP i knew that i could go the route of make my own library.
The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

C:...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0':
  C:...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'
  C:...\RCRoomba_TestPulseV2.cpp.o: In function 'setup':
  C:...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'
  Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.
Here is the .ino code.
for some reason UECIDE can't see the Pinchange and PPMint libraries
#include "arduino.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

PPMintIn CH1(A0);

void setup(){
    Serial.begin(115200);
    CH1.begin();
}

void loop(){
}

Here is the .cpp code
#include "arduino.h"
#include "ppmintin.h"
#include "PinChangeInt.h"
//defined these
volatile int pwm_value = 0;
volatile int prev_time = 0;
uint8_t latest_interrupted_pin = 0;

PPMintIn::PPMintIn(int pin){
    pinMode(pin, INPUT);\
    digitalWrite(pin, HIGH);
    _pin = pin;
}

void PPMintIn::rising(){
    PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::falling(){
    PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::begin(){
    PCintPort::attachInterrupt(_pin, &rising, RISING);
}

void PPMintIn::getSignal(){
    return(PPMintIn::pwm_value);
}

Here is the .h code
#ifndef PPMINTIN_H
#define PPMINTIN_H

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
  #else
  #include "WProgram.h"
#endif
#include "PinChangeInt.h"

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

#endif // PPMINTIN_H

here is the full thing in github in case I didn't supply it here.
https://github.com/tisaconundrum2/PPMintIn

The IDE probably can't parse those full paths. Why are you using them instead of trusting that the IDE knows where the headers are?

because when i use the debug console included with IDE it can't find the files. It's only when i do the full paths, does it know what i want

Looking for header file C:\Users\User\Documents\Arduino\RCRoomba_TestPulseV2\libraries\PinChangeInt\PinChangeInt.h
Library.java 98 ():
Looking for header file :\Users\User\Documents\Arduino\RCRoomba_TestPulseV2\libraries\PPMintIn\PPMintIn.h
it just scrolls through this forever

http://i.imgur.com/awwtHKj.png

No, the compiler knows what you want. The IDE has no clue, so it doesn't include the libraries for compilation and linking.

the compiler does link to the library, however these libraries that it linked to are empty and have nothing in it.

I'm not sure that you understand what "linking" is. Especially given that the errors posted towards the top of this question are link errors.

Well alright, i did what you suggested, This is the outcome
http://i.imgur.com/W1gpqIh.png
And when i export both the libraries to see what's inside, they are basically empty new libraries

Now the IDE is doing the right thing. However, your "PPMintIn" library itself has errors that need to be fixed.

why is my library sitting with my INO file, i thought it should be going into the libraries folder.

You need to watch your capitalization as well - the Arduino header file is Arduino.h not arduino.h and your main header file (ppmintin.h) must have the same capitalization as your library folder (PPMintIn.h).  On operating systems with case sensitive filesystems it will completely break otherwise.

Which version of the IDE are you using, and how did you create the library in the first place?

It should be, right up until the IDE builds it. Then it copies everything into a single directory and builds it there.

http://i.imgur.com/r0BSQD5.png

Also you should take a look at this, it will tell you why you are getting some of your errors: http://arduino.stackexchange.com/questions/14480/pass-a-member-function-pointer-to-a-method-of-a-foreign-class-edb-lib

I redid all of my code, and deleted a bunch of copies of the same library. Anyways, I'm getting less errors now. That should be a good thing but i'm getting this one error
http://i.imgur.com/ZIhuule.png

which doesn't make sense to me because the function allows for ints
PPMintIn::PPMintIn(int pin){
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
_pin = pin;
}

As both Majenko and I tried to explain in Pass a member function pointer to a method of a foreign class (EDB Lib) you can't pass a class member function where a static function is expected.

Your error is on:
PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

Error:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

PCintPort::attachInterrupt expects a PCIntvoidFuncPtr variable:
int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

That is:
typedef void (*PCIntvoidFuncPtr)(void);

That is a static function (not a class function).
However you have it as a class function:
class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

Now you can make rising and falling static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).
The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

Regarding one of the comments:

Unless your class implements operator() this line doesn't make sense:
chan1(15);

Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.


text:
Is it possible to have two serialEvent() in Arduino code?
I am developing a code on Arduino and need to implement a condition that if data is available form "serial2" then only get the input for "Serial" terminal of Arduino.
I have tried with below code, but its behavior is when I am sending something from "serial" terminal of arduino, control goes into the loop "serialEvent()" otherwise even if I am sending the data over "serial2" it is not entering in that loop.
Below is my code snippet:
void serialEvent()
{
  int DATAaddressMSb, DATAaddressLSb;
  digitalWrite(DIR485, LOW);
  delay(100);
  delay(10);
  while (Serial2.available()>0)
  {
    Serial.println("serial2 data available");
    int i = 0;
    int bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
    bufferIn1[i] = Serial2.read();
    Serial.print(bufferIn1[i], DEC);
    Serial.print(" ");
    if(i == 0){Serial.print("BUFFER VAL 0");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 1){Serial.print("BUFFER VAL 1");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 2){Serial.print("BUFFER VAL 2");
    Serial.print( bufferIn1[i], DEC);}
    i++;
  }

  while (Serial.available()&& pos < sizeof my_str - 1) {
    char c = Serial.read();
    if (c == '\n') {            // \n means "end of message"
            my_str[pos] = '\0';     // terminate the buffer
            pos = 0;                // reset to start of buffer
            String str((char*)my_str);    // converte char array in string
            if (str == "PCB-CODE") { Serial.println(SN_CODE); }
            if (str == "FW-VERSION") { Serial.println(FW_ver); }
            if (str == "STOP" ) { TESTcode = 0; IDcode = 999; }
            if (str == "TEST1") { TESTcode = 1; delay(6000); Serial.println("Enter ID "); }
            if (str == "TEST2") { Serial.println("Initialising Board ");  delay(6000); TESTcode = 2; }           // For all tests

            if (str == "ID0") { IDcode = 999; }
            if (str == "ID1") { delay(60); IDcode = 1; }       // Test for FW version
            if (str == "ID2") { IDcode = 2; }       // Test for 3.3V
            if (str == "ID3") { IDcode = 3; }       // Test for Main power
            if (str == "ID4") { delay(50); IDcode = 4; }       // Test for +15V
            if (str == "ID5") { IDcode = 5; }       // Test for +10V
            if (str == "ID6") { IDcode = 6; }       // Test for +8V
            if (str == "ID7") { IDcode = 7; }       // Test for +5.5V
            if (str == "ID8") { IDcode = 8; }       // Test for +1.2V
            if (str == "ID9") { IDcode = 9; }       // Test for +2.5V
            if (str == "ID10") { IDcode = 10; }     // Test for -15V
            if (str == "ID11") { IDcode = 11; }     // Test for POW_LIGHT
            if (str == "ID12") { IDcode = 12; }     // Test for +s_stab
            if (str == "ID13") {delay(50); IDcode = 13; }     // Test for +CELLA
            if (str == "ID14") { IDcode = 14; }     // Test for FPGA_GPIO
            if (str == "ID15") { IDcode = 15; }     // Test for DAC_OUT
            if (str == "ID16") { IDcode = 16; }     // Test for CURRENT_LOOP
            if (str == "ID17") {delay(50); IDcode = 17; }     // Test for Torque signal
            if (str == "ID18") { IDcode = 18; }     // Test for EXT_TRIGGER
            if (str == "ID19") { IDcode = 19; }     // Test for Encoder
            if (str == "ID20") { IDcode = 20; }     // Test for RAM
            if (str == "ID21") { IDcode = 21; }     // Test for SD Card
            if (str == "ID22") { IDcode = 22; }     // Test for Ethernet
            if (str == "ID23") { IDcode = 23; }     // Test for CAN
            if (str == "ID24") { IDcode = 24; }     // Test for I2C
     for( int i = 0; i < sizeof(my_str);  ++i )    // resetta la stringa ricevuta         // reset the received string
          my_str[i] = (char)0;
        }
        else {my_str[pos++] = c;}
  }
 }

Please guide. Thank you........

ignore the SerialEvent and put this code in loop(). it is nothing more then if (Serial.available()) called after the loop() function

Relevant Arduino source code: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/HardwareSerial.cpp#L64-L85

According to https://www.arduino.cc/en/Reference/SerialEvent
Arduino Mega handles:
void serialEvent1(){
//statements
}

void serialEvent2(){
//statements
}

void serialEvent3(){
//statements
}

Every other Arduino has only single:
void serialEvent(){
//statements
}


text:
Arduino help adding a second mpu 6050 sensor my working code
Background information: I currently have this arduino code that uses one mpu 6050 sensor to get angles in the x, y, and z directions and then display them to the user nicely. Code can be found here basic MPU 6050 code
The problem: I would like to add a second mpu 6050 to my project and average the values from the two mpu 6050s.
I know how to physically wire the second sensor into the project but don't know how to do the coding side of things. The code I have is below. Any help is greatly appreciated. This is a very fun tool.
#include<Wire.h>
const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;
int minVal=265;
int maxVal=402;
double x;
double y;
double z;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);
       x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
       y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
       z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
     Serial.print("Angle of inclination in X axis = ");
     Serial.print(x);
     Serial.println((char)176);
     Serial.print("Angle of inclination in Y axis= ");
     Serial.print(y);
     Serial.println((char)176);
     Serial.print("Angle of inclination in Z axis= ");
     Serial.print(z);
     Serial.println((char)176);
     Serial.println("-------------------------------------------");
     delay(1000);
}

Run a i2c scanner and tell us if two sensors are found. Why do you request 14 bytes and then use only 6 bytes? You could try a utf-8 character ° instead of (char)176.

Ok first did YOU wiring theme correctly? Because the mpu use i2c BUS .
Second this code from gitlab it may help you .
https://gitlab.com/shuvashish/batikkrom.com/blob/master/MuttipleMPU/MuttipleMPU.ino
Check it . And use it

Did you write that code? The lines with the while statement should be remove and 0x00000000 is not a byte.


text:
How to Connect TFT LCD display with NodeMCU?
I am doing this project wherein I want to display some image on the LCD screen. I am having a problem with the connecting nodemcu with my TFT LCD screen. I cannot find any references. Does a TFT screen go well with a NodeMCU? if yes, please help
I tried taking refrence from this website but i ended up damaging my nodeMCU
http://nobrok.com/connecting-tft-lcd-touch-screen-with-nodemcu-esp8266/
Also attaching images of TFT display and my NodeMCU.

It would be great if you can help. Thanks :)

please provide a link to the display datasheet ...... from the picture, it looks like the display has SPI interface  ( the four SD_ pins )

it's of some chinese vendor i looked up on their website:   http://www.mcufriend.com/main.html But can't find datasheet for this specific device. But i think it's a modified version of the ILI9341 as mentioned on their website.

According to its web site, the TFT module does have SPI interface. https://www.jixin.pro/product/717.html
The site is in Chinese though.

That kind of TFT doesn't work well with the NodeMCU (or the ESP8266 in general).
Simply put: that TFT requires a lot of GPIO pins - 10 at an absolute bare minimum, but better if you have more available.  The ESP8266 doesn't have many IO pins - and some of them are very sensitive about what they can be connected to without affecting the boot process.
It is better to choose a TFT screen with an SPI interface, which uses far fewer pins - although is slower to refresh the screen data.
If you are careful with your GPIO selection it may be possible to work with that screen. There are no specific requirements for what pins need to be connected to where (as far as hardware functionality goes), so it's up to you to find the right combination that doesn't cripple the boot process (stay away from GPIOs 0, 2 and 15 if you can).

Thanks for the reply! I tried the connections given on this link   https://forum.arduino.cc/index.php?topic=500773.0  but could not get it to work. If you find something or do have knowledge about it please share. Thanks again!


text:
How can I send AT commands to HM-10 module from my android phone?
Earlier today, I was able to connect flawlessly to my HM-10 module via the Arduino serial monitor. I think I then changed some settings without thinking and now I can no longer connect to it. No errors, nothing. I have tried every baud setting but to no avail. I am able to connect to it through my Android phone but is there an app where I can send AT commands just like the Arduino serial monitor. I'm thinking I could do this to run the at+reset command to factory reset it? Are there any other ways of resetting the module?

what does this mean? changed some settings

No. You are the wrong end of the connection. Like trying to turn a light on by squeezing the bulb (sorry, I'm usually the king of analogies, but I have come down with a cold and I can't come up with anything even remotely realistic...)

@jsotola Through the arduino serial monitor, I was playing with at+type, at+baud and at+mode.

@Majenko So is there a way of hard resetting the board then?


text:
16x2 lcd lighting up blue but not showing any text
i should probably start off by saying i am really new to this stuff and have barely any idea what i'm doing. i am triyng to use a DHT22 and a 16x2 LCD to show the temperature and humidity. here is the code i'm using:
#include <DHT.h>
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//Constants
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
  lcd.begin(16,2);
}

void loop()
{

  delay(2000);
  //Read data and store it to variables hum and temp
  hum = dht.readHumidity();
  temp = dht.readTemperature();
  //Print temp and humidity values to serial monitor
  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.println(" Celsius");

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(temp);
  lcd.print(" ");
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Hum:  ");
  lcd.print(hum);
  lcd.print(" %");

  delay(2000); //Delay 2 sec.

}`

is it an issue with my code or my hardware? thanks

start by running an LCD example sketch with only the LCD connected

You must use D0-D3 as data lines as you are using 8-bit LCD in 4-bit format

You need to set the correct contrast on these displays. Try turning the potentiometer (connected to pin 3 / VE)  till you see text/blocks appear.

You haven't told us what did you obtained? Anything on LCD? Can you make a clear photo of your hardware setup?


text:
Print out times tables from 1 to 10 with array
I would like to Serial.print(); the multiplication tables, 1 - 10. This is my work so far. Is there an easier way to do this with array? Thanks
// "MultiTable"

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//Define variable
int prod;

void setup() {
  // Open serial connection at 9600Bd
  Serial.begin(9600);
}

void loop() {
  //Print the times table for 1

  for(int i = 0; i <=9; i=i+1) {
   prod = i*1+1;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 2

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*2+2;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 3

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*3+3;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();
}

why do you try it on arduino? learn codding on a computer. it is easier

Welcome to Arduino:SE.  I'm not sure how this relates to the Arduino though.  Perhaps it's a question better suited to Stack Overflow?  You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

Thanks for helping!
I have the Arduino connected to my pc and would like to use it both in theory(programming) and practically.

So is arduino programed in c or c++? I have a textbook with the kit i got and the code in there is pretty different to what I get when i search for help.

why would you want to store the values?

note: in your existing code, change the loop to count from 1 to 10 instead of 0 to 9 .... for(int i = 1; i <= 10 ; i=i+1) { ..... that way you do not have to do the add in the next line

Okay, I thought that the first value were supposed to be at "place 0", but maybe that is not the case?

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This is not needed, you can use a for lop from 1 to 10.
The void loop will look like this (not checked, no IDE nearby):
void loop()
{
  for (int multiplier = 1; multiplier <= 3; multiplier++)
  {
      for(int i = 0; i <= 9; i++)
      {
         prod = i * multiplier + multiplier;
         // or: prod = (i + 1) * multiplier;
         Serial.print(prod);
         Serial.print(",  ");
      }

      Serial.println();
      Serial.println();
      delay(3000);
  }
}

Some remarks:

To go to the main for loop (with multiplier):

Identify the similar parts
Check the differences within each similar part (only the multiplier value, 1, 2 or 3)
Make this a for loop and instead of 1, 2, 3 use the multiplier variable
Instead if i = i + 1 you can use i++. It means exactly the same.
For clearity I put the Serial.println() together. You also can use Serial.print('\r\n\r\n') or Serial.println('\r\n') to achieve the same

For the record, the line terminator used by Serial is CRLF. Thus, a pair of Serial.println() is equivalent to Serial.print("\r\n\r\n") or Serial.println("\r\n").

@EdgarBonet Thank you for the remark, I updated the answer accordingly.

What's with the prod = i * multiplier + 1;...? Don't you just want to loop from 1 to 10, not 0 to 9, and not add 1 (which should be i anyway...)?

@Majenko I assume that is a question for the OP? I did not make any functional change. Although I would expect prod = (i + 1) * multiplier, but maybe he wants to start from 0.

But you have prod = i * multiplier + 1 whereas the OP had, in effect, i * multiplier + multiplier (i * 1 + 1, i * 2 + 2, etc...)

@Majenko: yes I copied it wrongly; I updated the answer, thanks for mentioning.

@AndreasH If it helps / if it is the correct answer, please press upvote and press the accept answer button.


text:
How do I make a toggleable Infrared motion detection module
I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?
(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)
int Sensor = 4;
int led = 13;
bool bool1 = false;

void setup() {
pinMode(Sensor, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}

void loop() {
int SensorValue = digitalRead(Sensor);

if(SensorValue == 1){
  bool1 = !bool1;
  }

if(bool1 == true){
  digitalWrite(led, HIGH);
  }
if(bool1 == false){
  digitalWrite(led, LOW);
  }
}

what to change about my code to make it work  .... what is wrong with the way the code behaves right now?

Consider using a state machine with 4 states.  Currently you only have 2 states.  One where "bool1" is TRUE and another when "bool1" is FALSE.  The 4 states needed are:

When the LED is OFF & the PIR is NOT-ACTIVE.
When the LED is OFF & the PIR is ACTIVE.
When the LED is ON and the PIR is ACTIVE.
When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3.  And you will only want to turn the LED OFF when traveling between states 4 & 1.


text:
Question about RGB LEDs
I think many people know about the staircase lights, which will get triggered by 2 PIR-sensors (1x upstairs and 1x downstairs).
Here is my code - which works well.  It's not cleaned up - as i don't know how i can simplify it. I think there'll be a much nicer way of getting the same output. :)
#include "FastLED.h"
#define NUM_LEDS 300
CRGB leds[NUM_LEDS];
#define PIN 3
int sensorUP = 5;
int sensorDOWN = 7;
int state = LOW;
int valUP = 0;
int valDOWN = 0;

void setup()
{
  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(20);
  pinMode(2, INPUT_PULLUP); // internal pull-up resistor
  pinMode(sensorUP, INPUT);
  pinMode(sensorDOWN, INPUT);
  Serial.begin(9600);
}

void loop() {
  valUP = digitalRead(sensorUP);
  valDOWN = digitalRead(sensorDOWN);

  if (valUP == HIGH) {
    colorWipeUP(0x55, 0xFF, 0x00, 2);
    delay(600);
    colorWipeUP(0x00, 0x00, 0x00, 2);
    delay(100);
  }
  if (valDOWN == HIGH) {
    colorWipeDOWN(0x55, 0xFF, 0x00, 2);
    delay(6000);
    colorWipeDOWN(0x00, 0x00, 0x00, 2);
    delay(100);
  }
}

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}
void colorWipeDOWN(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 299; i < NUM_LEDS; i--) {
    setPixel(i, red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for (int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

At the moment the LEDs just go on and after a delay off again (one-by-one).
QUESTION: I wish for a little smoother effect by fading them on and off.
So i reached the actual output by using different snippets and trying to understand. What i don't understand atm is how to add fading.

look up analogWrite and pulsed width modulation, or PWM, for how to fade LEDs.

Your code is currently written as blocking, so we can leave it that way and add another blocking nested loop. Let's take the colorWipeUP() function as example:
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}

You go through all leds, lighting them up one after another with the provided color, delaying between the LEDs. The brightness of an LED is controlled by the overall RGB value. If you just multiply the RGB components red, green and blue with a number between 0 and 1, you (mostly) keep the color and only control the brightness. For example like this:
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    for(uint8_t brightness = 0; brightness <= 100; brightness++){
      setPixel(i, red*brightness/100, green*brightness/100, blue*brightness/100);
      FastLED.show();
      delay(fadeDelay);
    }
    delay(SpeedDelay);
  }
}

For every LED we are now going from zero brightness to 100% brightness in a loop, showing each individual step on the LED strip.  fadeDelay determines, how fast this fade in should be. You will have to tune both delays to fit your expectations. You can use the same principle for the wipe down.
You may be asking yourself, why I count from 0 to 100 and then dividing by 100 instead of directly counting from 0 to 1 in steps of 0.01. I've done this, because on AVR based microcontrollers you don't have native floating point calculations. This means, that every floating point calculation needs many instructions to execute (because the floating point math is implemented in software instead of hardware). Here I'm counting with integers and when calculating the brightness also only integer math is involved (dividing by 100 is an integer division, which will automatically cut all digits after the decimal point. We don't need them).
Note: With 300 LEDs, the call to FastLED.show() will take some time. I haven't tested the code, but depending on your needs the fading might be too slow, even when you remove the delay call. Then you can simply increase the increment of the for loop, for example to use 10 steps instead of 100:
for(uint8_t brightness=0; brightness<100; brightness+=10)

something like a fade over 10 LEDs

For this I would use a totally different approach. If you view it mathematically, the brightness of each LED is a function of position and time. So we can implement a function much like a mathematical function, that returns the brightness for a given position and a given time. As I understood, you want the a function, that is first constantly zero, then it grows linearly with time and position and then it is constantly full brighntess. We can count the time from the moment, that the sensor is triggered, where we then start with zero brightness and let it rise linearly. Something like this:
int fadeBrightness(int position, unsigned long time){
    int brightness = m_p*position+m_t*time;
    if(brightness > 100) return 100;
    if(brightness < 0) return 0;
    return brightness;
}

m_p and m_t are constants, that you would need to define and fine tune. For fading over 10 LEDs, m_p has to be -10. time is provided as milliseconds. I'm currently not sure about the value of m_t, but you can simply try some values and use one that's fitting.
Then in your colorWipeUP() function you can loop through all LEDs and set their pixel just like in the code above, but this time you use the newly created function.
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  unsigned long timestamp = millis();
  while(millis()-timestamp < duration){
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
      setPixel(i, red*fadeBrightness(i, millis()-timestamp)/100, green*fadeBrightness(i, millis()-timestamp)/100, blue*fadeBrightness(i, millis()-timestamp)/100);
    }
    FastLED.show();
  }
}

You need to define the duration according to how long the fading will take with your m_t. If you set it longer, the loop will just loop longer, holding the brightness at 100%.
In the function we first create a timestamp from the millis() function. Then we loop, while the duration of the effect hasn't passed. In each while loop iteration, we set the color components of each LED pixel with the brightness according to our fadeBrightness() function. Then we show this on the LED strip. The function is constantly updating the strip at max speed. The actual speed of the animation is determined by the fadeBrightness() function.
This version is also blocking code, but it can easily be transformed to non-blocking code, that you would call repeatedly until the animation is done.

Hey chrisl, thank you very much for this detailed explanation. As im trying to get something out of it, i started to struggle with "fadeDelay" and it seems like still one by one LED will be turned off - but with a slightly fade this time. :)
What i try to accomplish is something like a fade over 10 LEDs. Don't know how to explain it better - but i found a video which will explain it maybe better. [link]https://www.tweaking4all.com/wp-content/uploads/2015/11/LEDEffect-Fire.mp4?_=1[link]

@AxelKummerlöwe I added this to my answer, keeping the old answer intact, since it might be useful for someone.

Hey Chrisl,
thank you very much for your feedback - AGAIN! :)
As i becoming a dad today, maybe tomorrow - i'll be back to this post asap. But i think i'm able to work with your help.
Thanks again and a happy new year <3

You could do something like this. (not tested)
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (int i = -5; i < NUM_LEDS + 5; i++) {
    setPixel(i    ,      red, green, blue);   // example only
    setPixel(i + 1, .8 * red, green, blue);   // change the green and blue also
    setPixel(i + 2, .6 * red, green, blue);
    setPixel(i + 3, .4 * red, green, blue);   // successive pixels have lower brightness
    setPixel(i + 4, .2 * red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {

  if (Pixel < 0 || Pixel >= NUM_LEDS) return;        // do not set color of non-existent pixels

  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}


text:
esp8266 advertising AP even when flashed with custom firmware
I bought several ESP8266 boards from an Amazon seller, and I have flashed them with custom firmware.  This firmware basically sends telemetry to an MQTT server, and has some OTA functionality to self-update from a web server I run.
I flashed them from the Arduino IDE initially, although have also since updated them OTA.
These devices properly connect to the AP I have defined, get an address, and send their mqtt messages.  However, they ALSO advertise an SSID that is FaryLink_XXXXXX where the XXXXXX relates to the MAC.
How is this possible, and how should I wipe their little brains fully?

WiFi.mode(WIFI_STA);

Ahh.  So obvious when you know what it is.  Of course, one wonders why it chooses that SSID when I can't find it in the source, or binary, anywhere...

please read the answer. setting mode only turns off the AP in setup(). it will start at boot

The Espressif ESP8266 SDK is part of every Arduino sketch for the ESP8266. The SDK handles the WiFi and other basic functions of the chip.
If enabled, the SDK remembers WiFi STA and SoftAP settings and start to connect right after boot. At default it is enabled. In Arduino sketch this is controlled by WiFi.persistent(bool) and of course this setting is stored too.
To clear SoftAP settings, call WiFi.softAPdisconnect(). To only turn off SoftAP, use WiFi.setMode(WIFI_STA).


text:
How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino
I am trying to divide a incoming high frequency signal 600kHz by 4 and output wave at arduino MEGA2560 digital pin.

The input to arduino comes from incremental Encoder which is connected to motor that runs at 9000 rpm and the generates 1024 pulses per rotation.
I am trying to downsample the frequency I am getting from arduino to 250kHz or less.
I tried following approaches :
a. I counted the rising edge of the incoming wave and a interrupt is triggered as number of rising edge reaches certain value and ISR toggle an output pin.
b. I tried to get hardware counter work at T0 pin but I was not able to hit ISR when the count has reached specific value.

The problem with approach 1 is: As my frequency of incoming wave increases the output wave starts missing some pulses and generates one half cycle for 6/8/10 pulses of incoming wave. It should actually generate one half cycle for 4 pulses.
Here is approach 2 code:
#define outPin1 10
volatile short encoder = 4;

void setup ()
{
   pinMode (outPin1, OUTPUT);
   Serial.begin(9600);
   cli();
   // reset Timer 0
   TCCR0A = 0;
   TCCR0B = 0;

 }  // end of setup

 ISR(TIMER0_COMPA_vect)
 {
     digitalWrite(outPin1, !digitalRead(outPin1));

 }

 void loop ()
 {
    TCNT0 = 0;      //counter to zero

    // set compare match register to desired timer count:
   OCR0A = encoder;
    // turn on CTC mode:

   bitSet(TCCR0A, WGM01);
   // Timer 0 - counts events on pin D4

  bitSet(TIMSK0, OCIE0A);    // interrupt on Timer 0 CTC
   // start Timer 0
  // External clock source on T0 pin (D4). Clock on rising edge.

   bitSet(TCCR0B, CS02);
   bitSet(TCCR0B, CS01);
   bitSet(TCCR0B, CS00);
}

Please someone help me out with this issue

Why would you waste an Arduino on this when you can use a single 10¢ chip? http://www.ti.com/product/SN74HC163

I think the code you put the loop should be in setup. Otherwise you loop code is constantly resetting the counter, back to zero (TCNT0 = 0;)

Couldn't you just attach an interrupt to the input pin, have if count up every time it's called, and set the output to low when the count is equal to 4. 600kHz is probably slow enough to have enough time for the ISR to run it's code.

This is probably too fast to have have software involved in the loop.
You should try to use a hardware-only solution. Note the Arduino timers
should be usable as hardware frequency dividers:

configure a timer to be clocked off the input signal, so that it
behaves like a counter.
configure it for delivering a PWM output with a period of 4 timer
clock cycles and a duty cycle of 50%.

You may try this, but beware I have not tested it:
void setup()
{
    // Configure Timer 5 as a frequency divider:
    //   input: digital pin 47 = PL2 = T5
    //   ouput: digital pin 46 = PL3 = OC5A
    DDRL  |= _BV(PL3);    // set pin PL3 as output
    TCCR5A = 0;           // undo the Arduino core's configuration
    TCCR5B = 0;
    ICR5   = 4 - 1;       // period = 4 timer clock cycles
    OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
    TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
           | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
    TCCR5B = _BV(WGM52)
           | _BV(WGM53)
           | _BV(CS50)    // clock on rising edges of T5
           | _BV(CS51)
           | _BV(CS52);
}

void loop(){}

It worked for one output of encoder but i also have another output from encoder for which i have no input pin to give on mega2560 since on T5 can be used and T0 has not Input capture functionality.   I have one idea whether i can use on one input of encoder and generate two wave at output pin with phase shift of 90 degress. Depending on a flag it must be possible for me to change which wave is leading or lagging

@Vishal777: Re “T0 has not Input capture functionality”: you don't need input capture. You can use T0 if you don't mind loosing the Arduino timing functions (millis() and co.) which depend on Timer 0. Or you could use T1 if you can solder a header onto the unpopulated footprint JP5. Re generating two waves at 90° from a single timer: I do not think this is possible.

I am trying to use timer 0 in CTC mode and triggering an ISR which toggles the pin when TCNT0 reaches 4. But without the valid input I am getting a wave at digital output pin 10. I think it is taking internal clock as reference instead of external clock. I have made all CS bits high to select clock from T0 PIN This is strange behavior

@Vishal777: Let me insist: “This is probably too fast to have have software involved in the loop.” An ISR is a piece of software, so forget about it.

I could successfully divide by 4 using 2 timers T0 and T5. As per my existing setup I get input wave of less than 200kHz. I have not tested for 600kHz input wave

@ EdgarBonet here is link for the code    http://collabedit.com/e3xth

I am writing another answer because what I propose here is radically
different from the previous answer. In that answer I wrote that this is
too fast for being done in software, and here I am going to contradict
myself. :-/
At 600 kHz, the input stays low for roughly 13 CPU cycles,
then high for another 13 cycles. You cannot do much in 13 cycles.
Notably, the prologue of an ISR can quite often take more than this.
Also, whenever the Timer 0 overflow ISR from the Arduino core fires, it
can delay your own ISR for way more than 13 cycles. That's why it
is usually illusory to expect any job to be reliably done in this time
frame. Especially if interrupts are involved.
That being said, if the CPU has absolutely nothing else to do. And
specifically if it is never interrupted, Then it can keep up with that
pace. Here is a program that should do what you expect. I initially
thought about writing it in assembly, but it can also be written in C,
as the compiler translates it in a quite straightforward way. If in
doubt, however, check the generated assembly:
/*
 * From one square wave generate two waves in quadrature at 1/4 of the
 * original frequency.
 *
 * https://arduino.stackexchange.com/questions/63202
 *                               _   _   _   _   _   _
 *  input:  digital 13 = PB7    / \_/ \_/ \_/ \_/ \_/ \_/
 *                               _______         _______
 *  output: digital 10 = PB4    /       \_______/       \
 *                                   _______         ____
 *  output: digital 11 = PB5    ____/       \_______/
 */

int main(void)
{
    DDRB = _BV(PB4) | _BV(PB5);  // PB4 and PB5 as outputs
    for (;;) {
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                   // rise PB4
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB5);                   // rise PB5
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                  // fall PB4
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB5);                  // fall PB5
    }
}

Note that, since this is not using the Arduino core, I wrote main()
rather than setup() and loop(). This overrides the main() provided
by the core, thus you don't have the initializations that come with it
and, in particular, you don't have the Timer 0 interrupt.


text:
Wire with MCP23008 I/O expander with I2C
I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.
So I set it up for read as follows:
#define MCP23008_DEVICE_I2C_ADDRESS 0x20
#define MCP23008_SLAVE_I2C_ADDRESS  0x04

#define MCP23008_REGISTER_IODIR     0x00
#define MCP23008_REGISTER_GPIO      0x09

#define IO_ALL_PINS_INPUT           0xFF

inline void eeprog::_read_enable()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
        Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
    }
    Wire.endTransmission();
}

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:
inline uint8_t eeprog::_read()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
    }
    Wire.endTransmission();

    Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

    return Wire.read();
}

Looking at my logic analyzer this is what I get:

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?
Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?

Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.
The NACK at the end is not an error, it is a way to communicate between the Master and Slave.
When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.
Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.
The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.

Thank you. I just assumed that the NACK condition indicated an error since I previously had written my "write" code wrong and got NACK on the bus.


text:
Problems burning bootloader on custom ATMEGA2560 board for High-powered model rocketry
I've designed a custom board meant for high-powered model rocket telemetry & duel-deployment.  (More info upon request)
To do this, I've soldered a ATMEGA2560 (yes, overkill, but I needed multiple hardware serials), with the plan on using the ICSP programming header I designed on the board to burn the Arduino bootloader, and then use the super-easy ftdi-compatible serial connector to program the board....
Problem is, I have thus far been completely unable to burn the bootloader.  I've double-checked the wiring ten times, checked the labeling on my board, checked my board's schematic twice, and re-checked the chip's datasheet to make sure I didn't screw up the pinout, even held a jumper past my fancy reset circuitry that I largely copied from the official Uno schematic.
I've largely been using Nick Gammon's excellent "bootloader programmer" sketch Link on a Clone Arduino Mega.  But I've tested the connections and sketch by using it to program the bootloader on a Arduino Pro Mini successfully with no hitch at all.  :(
Attempting to enter ICSP programming mode..........................................
Failed to enter programming mode. Double-check wiring!
Here's a Board and (Schematic I can't post because I'[m new to the Arduino side of stack overflow...  so replace the URL with schematic.png) of my board, and I'll upload a picture of my soldered board soon, but I'm actually quite confident of my soldering job...
Really just completely out of ideas, and very demoralized because the project I've been working on for months isn't working, and I have nothing specific to even point at...

I have thus far been completely unable to burn the bootloader.

In what sense? What (error) messages did you get?
In your shoes I would be seeing if I can "talk" to the chip. My chip detector sketch will help you to see if the chip is "alive" or not. See my post about Have I bricked my Arduino Uno? Problems with uploading to board
You may possibly have inappropriate fuse settings for your clock source. If you get some sort of response from the chip using the chip detector sketch please post what it is.

Also to note is that this is a completely virgin chip from the manufacturer, so I'm not sure what the clock settings come as in that case

According to the datasheet, 8 MHz internal oscillator with CKDIV8 fuse set. That should work.
However you need to resolve that before going any further. I would be taking voltage readings at various points.

Make sure you have Vcc at all the appropriate places, and Gnd.
Note that there are multiple Gnd and Vcc pins. You should also have 5V at AVcc.
Check that /RESET is normally high (5V) and check that it drops to 0V during the programming attempt (and stays there).
Check you have decoupling capacitors between Vcc and Gnd where necessary.
Assuming you have the TQFP-pinout chip, make sure that you have your SPI connections at pins 19, 20, 21 and 22.
If you have a scope or logic analyser make sure that there is some "action" on SCK, MOSI pins during attempts to program it. There should also be a response on MISO.
There should not be a capacitor in series with /RESET as I have occasionally seen people do. The programmer has to hold /RESET low during the entire programming sequence.

Sadly, both the chip detector sketch & the board programmer sketch give up at the same point-
Attempting to enter ICSP programming mode ...................................................... Failed to enter programming mode. Double-check wiring!  So I'm assuming there's no response at all, which is a bit worrisome.  Also to note is that this is a completely virgin chip from the manufacturer, so I'm not sure what the clock settings come as in that case...

See amended answer.

Also make sure your circuit ground is connected to the PC/programmer ground; I went through almost all the troubleshooting listed in this answer when an ATMEGA 328p of mine suddenly couldn't be programmed, only to find i missed the connection between my PC ground and the circuit ground!

@Nick Gammon Thanks, this is helpful!  I think I'm good on all of these points except for 2:  Yes, it's TQFP, but do you need pin 19?  (/SS) I foolishly left it floating, which I suppose could cause some issues?  Also, I made the /Reset capacitor mistake.  (Different kind of reset, apparently)  but I've since connected a wire to the /RESET side of the capacitor, to pin 10 on the programming mega, with no difference.

@esoterik Yeah, the ground from the SPI is connected to the ground for everything else as well, and each of the 5 gnd's on the chip as well.  I only have one ground net.  :P   Good idea, though.

It probably won't hurt that /SS is floating, however that would have been a handy pin to have available. As for the ongoing problem, now is the time to hook up a scope and see if signals are getting where you think they are.


text:
Arduino: command not found
After installing the Arduino IDE on MacOS (1.8.5), I am trying to run some commands in the terminal to flash the firmware on an Uno R3.
I have successfully connected and uploaded through the GUI, but would like to use the command line for the johnny-five API (https://github.com/rwaldron/johnny-five/wiki/Getting-Started).
However, when running
arduino --install-library "Firmata,Servo"

I get the following error:

-bash: command not found

How do I install the command line interface?

simple google search gives this https://playground.arduino.cc/Learning/CommandLine

I was on that page earlier today. It says the CLI has been available since 1.5, but it isn't bound to anything on the command line on my machine after installing 1.8.5.

Not really an arduino question, more of a linux one.    Command not found means there is no program "arduino" in your path

Yes... I thought this community would likely have better knowledge as to what the actual path is...

Depends on where you installed it...   have you done something like sudo apt-get install arduino

I ran sudo npm i arduino --unsafe-perm on MacOS.

npm is the Node.JS package manager. It has nothing to do with the Arduino IDE, it just installs a Node package with the name 'arduino'.

the arduino builder is installed with IDE. you must only ensure that it can be found. try full path for execution. I can't give you details for Mac.

I can successfully upload with the builder...  What is the Linux path?

the installation folder of the IDE. it is the 'arduino' file. it starts the IDE if invoked without parameters

Arduino has a new CLI https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

Instructions to installing and binding the Arduino CLI can be found at
https://github.com/arduino/arduino-cli#getting-started
Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as /usr/local/bin/).
Note: You may have to rename the binary to arduino-cli.


text:
Reset Arduino Uno R3
I have an Arduino Uno R3 board and I compiled a test code. But now I'm trying to delete it. There are many tutorials with the same way, that is rewrite BLANK CODE. But it's not the genuine way. I want to delete all code that I manually compiled. Because the previous code will also take space in memory and after some time memory will be full. Is there anyone who has the right solution for this problem? Thanks in advance.

Every time you rewrite an Arduino, the previous code is completely wiped out (except for the bootloader, which doesn't change).
You will not fill up your arduino -- it is not like a filesystem where you are continually adding new files. Each new programming/upload overwrites all the existing code.
Uploading a blank sketch is the genuine way to "erase" an unwanted program from an arduino.

When you upload a new sketch the flash memory (Arduino hard disk) is deleted completely and the new sketch is loaded.
If you want a blank code, just upload:
void setup() {
}

void loop() {
}


text:
How to write Arduino API code in VL53L1X?
I'm trying write code for the VL53L1X on Arduino,  but I didn't get the VL53L1X registers. How to access them and how to measure the data in VL53L1X? Can anyone help me?

And the datasheet says what?

what model of arduino is the VL53L1X Arduino?  ... which manufacturer makes it?

He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.
ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.
Sparkfun have just released a library. It's much smaller but, like the Polulu library for the  VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.
https://github.com/sparkfun/SparkFun_VL53L1X_Arduino_Library/blob/master/src/SparkFun_VL53L1X_Arduino_Library.cpp
There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.
It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).

Majenko, there is no proper data sheet. The programming details are described in the code. Partially.


text:
Will a genuine Arduino board have the same issues with High Sierra as other non genuine ones?
I think my question is quite specific to High Sierra. I am very new and have bought a starter Elegoo kit to learn the basics. I did not realise that their boards are not the real thing.
I have an iMac running High Sierra and although the Mac recognises the board (I checked this through the apple menu) every time i try to upload code i get the error message:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
I have watched several videos on line that have taken me through installing drivers including one specific to High Sierra. However the problem continues.
Does anyone know if i buy a genuine Arduino board, will i have the issues? Will Arduino just not work with High Sierra.
Any help or advice would be so appreciated by someone very new and trying to learn!
Thank you
Paddy

Does the board use the CH340G USB chip?

By looking. Read the chip numbers.

The one that isn't the ATMega328p.

This is a Mega2560 R3. Sorry am probably seeming very stupid, i do appreciate your help, im just not sure what im looking for

In that case it's the one that isn't the ATMega2560.

The only sequence of numbers i can see written on it is CS4725V

Do you even know what a chip is? You're looking at capacitors there. Chips. They're black, either square or rectangular, sometimes with metal pins sticking out the sides.

If it's the same as the image I am looking at it should be an ATMega16U2. If it is, and it's been programmed correctly, then it should be no different to a genuine one.

Im so sorry no i did not, but now that you explain i can see the big chip is ATMEGA2560 and then a smaller one Mega16U2 1734. Thank you

Ah i see i have just seen your previous comment, it seems it is the same chip. Maybe they will just not work with High Sierra?

The 1734 is the date code from when the chip was made. It's quite new - August 21-27 2017. So it should function the same as a genuine Arduino. If it's all been programmed right.

Does anything work with High Sierra? With all the bad press it's been getting recently I am surprised they haven't pulled it ;)

Ah okay, brilliant thank you that is great to know. In your opinion would it be worth sending it back for a new one or maybe there are just too many problems working on Mac and High Sierra?

Your very right about High Sierra!! :)

I would suggest getting hold of a genuine Arduino and trying it (maybe borrow one from someone else). If it works and yours doesn't there's an issue with yours. If neither work then there's an issue with (maybe only your installation of) OS X.

I will do that, thank you so much. I will get a new one anyway as maybe i have to find an old PC to work on. Could i ask you for some quick advice about learning? I really struggle with the Elegoo instructions, they are badly translated and so for a novice it is very confusing. Is there another platform you would recommend at all?

You need to learn two separate spheres of knowledge - electronics and programming. Start by learning about simple circuits and how electronics function - separate to Arduino. Then learn basic programming techniques (again not necessarily related to Arduino) and then fit the two together.

Okay thank you, i so appreciate your help! :)

From reading both your questions, I'm not sure whether you've gotten your board to upload yet.
But here's another data point: I just tried an Arduino Mega r2 and iMac with High Sierra - worked perfectly, first try. Arduino IDE 1.6.12.
In your other question, you said you were getting a solid green LED and a blinking yellow one. The green LED is the power LED. The yellow one is programmable so it sounds like the Blink sketch is already loaded and running.
If you're still getting upload errors, check the Arduino IDE Tools menu and check you hardware selections in the Arduino IDE Tools menu. Here are mine; your /dev/cu.usbmodemxxx number might be different but there should only be one of those if you only have one Arduino plugged in:

that was it, i think it is probably my fault for religiously following the instructions sent me by Elegoo that told me to select the Arduino Genuino and i did not see the option to select the board as Mega 2560! I guess you live and learn... thank you so much for your advice. I feel a bit stupid no that it was such a simple solution! Thank you again

I use High Sierra on my ageing 2011 MacBook and it works with reputable Arduino clones (it is difficult to get a genuine Arduino in Australia, although compatible Freetronics boards are available from a major retailer).
There were some problems with ARDUINO 1.8.4 but the latest works flawlessly.
Anything with a CH340G chip is out, but then the CH340G don't seem to last anyway.

thank you. I realised i was being very stupid and had not selected the right board. I feel and idiot but hopefully have learnt not to follow instructions too carefully in future. Thank you so much for you help

As long as the firmware on the ATMega16U2 chip is the same as on a Genuine Arduino and the bootloader on the ATMega2560 chip is the same as on a Genuine Arduino then your boards should function exactly the same as a Genuine Arduino.
If you find a Genuine Arduino works but your boards don't then there must be a difference, and that can really only be in the software on the chips - so reprogramming the chips to match a Genuine Arduino would probably help.
I haven't heard reports of High Sierra not working with Genuine Arduino boards, but given the severity of some of the bugs that have crept in recently, it seems likely that more problems are hidden away under the hood that no one really knows about yet.


text:
Use ESP32 as a secure socket
I have a board without network connection, then I bought an SP-WROOM-32 dev kit because it has network connection ability.
Is there any way that I use esp32 as a secure socket (just like calling socket_connect() and the ESP will be used?)
I know that my board can control the ESP with AT commands but I want a native way.
Thank and have a nice day.

Here is a possible starting point: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino

I am sorry but I want my board use esp32 not esp32 using itself.

for esp8266 I use WiFi Link, but I do not know if it is portable for ESP32. the WiFi Link firmware is a sketch, so perhaps changing the includes would be all for porting. https://github.com/jandrassy/arduino-library-wifilink/blob/master/README.md

If programming the ESP32 itself is not "a native way", what is it?

I want something like calling API of ESP from another board. But it is impossible based on my research.On the other hand, AT commands don't have some features that I need so I will implement another protocol to communicate with ESP. By the way, thank you so much for your time to answering me.

you can't directly mount the capabilities of an attached device in the main code. you build an API yourself using simple sketches that export the capabilities you need, typically reading requests from serial and writing responses to serial. or you can invert the control and use the ESP to run more of the core logic, to reduce the amount of back-and-forth.


text:
Multiple delays
I have a sketch with multiple functions in it. The 2 main functions in that sketch are get_data and post_data.
Now these functions are called from loop(). The thing is I want these functions to run at different times. Basically I want the get_data function to run once every 4 minutes and the post_data function to run once every hour. How can I achieve that?
As far as I know, you can't run multiple programs together on an Arduino Mega.
P.S: I'm new to Arduino programming.

in loop function ... check time ... if 4 minutes then call get_data ... check time ... if 1 hour then call post_data  .... that's it, the whole loop..... you could also check time for the 1 hour at the end of get_data and call post_data from there

can u tell how can i check time in arduino mega with wiznet w5100 ethernet shield .. I dont know much about arduino since am new to it

google arduino time    .... also this  .... https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

Look at the “Blink Without Delay” Arduino tutorial.

I imagine that you tried to figure out how to do it whit the delay() function (if it's not your case, it is for most Arduino beginners). Well... you can't use delay() in this case (and in most other cases) because it completely blocks the program for a given time (1) (except for interrupts, but i won't treat interrupts here). In general it is better not to use delays, except for very simple programs or in initialisation routines (i.e. in stuff you usually put in setup()).

Since your delays are quite long I imagine that you don't need much precision (i.e. you don't need to be more precise than a millisecond). So you could do like that:
void setup() {}

// Times at which we last called the functions
// (These are global variables, which are in general best avoided)
unsigned long lastGetData = 0;
unsigned long lastPostData = 0;

void loop() {

    //                           min.  sec.  milliseconds
    if(millis() - lastGetData >= 4   * 60  * 1000) {

        lastGetData = millis();
        get_Data();
    }

    //                            min.  sec.  milliseconds
    if(millis() - lastPostData >= 60  * 60  * 1000) {

        lastPostData = millis();
        post_Data();
    }
}

void get_Data() {
    // ...
}

void post_Data() {
    // ...
}

Notes:

millis() returns the time since the startup of the Arduino in millisecond. To get more precision you could also use micros() which returns the same but in microseconds (then you would need to multiply the number in the if condition by 1000).
you can add as much functions as you want whit different execution delays. But you must keep every function as short as possible, i.e. you must not use delay()s, because while executing a function if the time to execute another function comes that function will only be called after the end of the current one.
I used the => sign, and not ==, so that even if the loop doesn't evaluates one if condition in the very milliseconds in which it becomes true it can positively evaluate it some milliseconds later (e.g. after the end of another running function).

I took the liberty to fix a few bugs: the time comparison was backwards, the test was not rollover-safe, and get/post were mixed up.

@EdgarBonet, changed your code so that the run time of get_Data() does not affect the 4 second period (same for post_Data())

@jsotola: 1) If you want the average period to not be affected by the time taken by the code to run, you should just replace lastGetData = millis(); by lastGetData += GET_DATA_PERIOD;. Your proposed edit does not achieve the promised constant period: think for example about the interaction between the getData() code and the postData() timing. 2) When you propose such sort of edit, there is no reason to also change the naming style of the functions.

@EdgarBonet Firs of all, thank you for the first edit!! ;)  ---  About your last comment, wouldn't that interaction also affect a lastGetData += GET_DATA_PERIOD; implementation? In any case I edited according to jsotola's comment because I think it's slightly more consistent and easier for a vary beginner to understand (it's time? first reset timer, then perform action, like you would do with a real life timer) and it increases the precision of the period if getData() and postData() take a variable amount of time to execute.

@EdgarBonet, no offence intended. ... 1) you are absolutely correct. i only changed it to point out that it is something to think about.  ....  2) the OP used that naming style in the question. ...

@jsotola --- 1) I see your point and just accepted your edit (removing some comments which only had sense in the context of your previous comment) --- 2) You'r right, I didn't pay attention to the OP's naming conventions, I just read his question twice before writing my answer... but I'll leave it as it is and I hope we'll not speak about naming conventions again in those comments. ;) --- And thanks for your comment/edit!

With lastGetData += GET_DATA_PERIOD;, you may still have a scheduled action delayed by some other running code, but those delays don't add up. Thus, you get jitter, but no drift.

Well Thank You everyone for the input. I tired the millis() and it worked like a charm

If you don't need absolute precision, I've written a timer class that doesn't use an interrupt: TimerAction. Usage to simply subclass the base object, define an action() method in the subclass, construct your subclass defining the time interval to run, and place a call to the object's loop() method in your main loop() function in every sketch.
In your case, you'd create a subclass for each of your get_data and post_data actions. This would require two objects to be constructed, and both of them having their loop() method called in the main loop() function.

If it works in your situation:
void loop() {
  static int n;

  delay(4 * 60000);
  get_data();

  if (n-- == 0) {
    post_data();
    n = 14;
  }
}

You may need to adjust the 14 and post-decrement to fit your needs.