text:
Play .Wav sound only once on switch change
I have a project where if you change the value of the spdt switch the colour of the LEDs change. As well as this a .wav file plays. The problem is I only want the .wav to play once. At the moment it constantly plays over and over as it's within the loop. I've tried using a mute or disabling the pin after the play through but I am unable to re-enable so I scrapped it. I deally I want to keep the SPDT switch due to asthetics instead of a push switch. This is my code:
#include <TMRpcm.h>
#include <SD.h>
#define SD_ChipSelectPin 10
#include <SPI.h>

TMRpcm tmrpcm;

void setup()
{
// put your setup code here, to run once:

tmrpcm.speakerPin=9;
Serial.begin(9600);
if(!SD.begin(SD_ChipSelectPin))
{
  Serial.println("SD fail");
  return;
}
     tmrpcm.setVolume(6);
     tmrpcm.play("1.wav");
     while (tmrpcm.isPlaying()) {
     delay(1);
}
     tmrpcm.setVolume(6);
     tmrpcm.play("3.wav");
//set the switch input, pin 8, as an
pinMode(8, INPUT);

//set both the LED pins, pin 5 and 6 as OUTPUTs
pinMode (5, OUTPUT);
pinMode (6, OUTPUT);
 delay(1000);
}

void loop()
{
 int switchValue = digitalRead(8);
 if (switchValue == 1)
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
  tmrpcm.setVolume(6);
  tmrpcm.play("4.wav");
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);

}
else
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
   digitalWrite(6,HIGH);
   digitalWrite(5,LOW);
   tmrpcm.setVolume(6);
   tmrpcm.play("5.wav");

}
}

how can I make the wav play once but when the switch changes?

Make a variable to hold the "last state" of the switch. Compare that last state to the current state as obtained by switchValue = digitalRead(8).
Only call the play function if the old value and the current value are different.

Hi I added this:  if (switchValue != lastButtonState)
{
tmrpcm.setVolume(6);
tmrpcm.play("4.wav");
                      while (tmrpcm.isPlaying()) {
                  delay(1);}
              }

              lastButtonState = switchValue;

I added it on both sides of my If Statement and It worked :-)


text:
Arduino controlled relay for certain duration of time
I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.
 unsigned int interval = ftime*1000; //ftime in ms
do
  {
  digitalWrite(Relay1, LOW);
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Also, if i try without:
digitalWrite(Relay1, HIGH);

relay is LOW (motor running) but it never returns to HIGH obviously.

You don't show us how timeElapsed is updated. But according to your functional description, why shouldn't it work to pull Relay1 low, wait for interval milliseconds, then pull it high again? Code is like digitalWrite(Relay1, LOW); delay(interval); digitalWrite(Relay1, HIGH);.

delay() is to be avoided because, while it is delaying, the Arduino cannot do any useful work (other than interrupts). In particular, if it has any kind of user interface, it will not respond to user input while delaying. However, if your Arduino really has nothing else to do, then delay() is fine, and it's the simplest solution.

you need to update the timeElapsed variable inside the while loop:
 unsigned int interval = ftime*1000; //ftime in ms
 unsigned long startTime = millis();
do
  {
      digitalWrite(Relay1, LOW);
      timeElapsed = millis() - startTime;
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Another way is to create a state machine make startTime a global and update the logical state (and the pin) when the time is elapsed.
unsigned long startTime;
bool relayLOW = false;

void loop(){

    if(relayLOW && millis() - startTime > interval){
        digitalWrite(Relay1, HIGH);
        relayLOW = false;
    }
    if(!relayLOW){
        bool closeRelay= //decide if relay needs to be triggered
        if(closeRelay){
            startTime = millis();
            digitalWrite(Relay1, LOW);
            relayLOW = true;
        }
    }
}

Made the changes but i get an error after the do/while:
Soft WDT reset
ctx: cont
sp: 3fff0850 end: 3fff0a50 offset: 01b0

stack>>>
3fff0a00:  3ffef964 3ffef458 3ffef964 40203807
3fff0a10:  0000078c 0000001c 3ffef6c0 40106bad
3fff0a20:  00000000 00000000 00000001 3ffefa24
3fff0a30:  3fffdad0 00000000 3ffefa1c 40205894
3fff0a40:  feefeffe feefeffe 3ffefa30 40100a28
<<<stack<<<
ΖεΦΤΖU)�ώ

I would be interested if it's not difficult to to show me a state machine example.

The problem with this code is that it does busy waiting without reseting the watchdog. It loops the entire time until the time has elapsed, but the Arduino watchdogs bites after 5 seconds without exiting the loop function or executing a delay() call (even with 0 as argument). The result is that your Arduino resets after a watchdog reset.

I believe i understand the situation. If i understand correctly, if the time was below 5 seconds, the error/reset would not occur. However, i cannot figure out how i will solve that? Any ideas?

As Maximillian Gerhardt suggested you could insert a delay(0); into your  while loop, which will reset the watchdog timer

@GalinhoSalonica I've updated the answer

@ratchet freak closeRelay should be global boolean, obviously?

@GalinhoSalonica ah no you can declare it inside the if where the comment is. It's only used inside that point.

Perfect answer and the second approach is working perfectly too. I can confirm after trying to make it work and succeeding in both ways. Thanks to all of you guys.

source: Stack Exchange

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

sort: votes


text:
Update button state in Blynk app through the code
I'm using Blynk along with a WeMos D1 R2 and i can change modes through an ON/OFF button.
I can succesfully change mode and make my application go from mode 1 (irrigation) to mode 2 (Fertilization), but through the code i manage to switch from mode 2 to mode 1(after my code does what it is meant to do).
However, i cannot make the button show up as being in mode 1 again, if the application is working properly in mode 1. Any ideas on how to update button condition?
My code follows(below the code you can see the app and the button Using the V1 virtual pin):
void setup()
{
  Serial.begin(9600);             // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT);        // Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT);        // Setup Relay pin as output pin
//pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
  digitalWrite(Relay1,HIGH);
  digitalWrite(Relay2,HIGH);

}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8,level);    // virtualpin 8 distance
}

BLYNK_WRITE(V1)
{
  pinValue = param.asInt();
}

BLYNK_READ(V5)
{
  Blynk.virtualWrite(5,RH);       // virtualpin 8 distance
}

BLYNK_READ(V6)
{
  Blynk.virtualWrite(6,temp);     // virtualpin 8 distance
}

void loop()
{
  Blynk.run();
  timer.run();
  if (pinValue==0)
  {
    // some code here
  }
  else //(digitalRead(sensor_pin) == 1)
  {
    // some other code
  }}

else {
  // a lot of code here
  pinValue=0;                     // here i set pinValue to 0 again in order to return to mode1
}
}
BLYNK_READ(V1)
{
  Blynk.virtualWrite(1,pinValue); // virtualpin 1 state
}

//End of program

BLYNK_READ() is documented as:

BLYNK_READ(vPIN)
BLYNK_READ defines a function that is called when device is requested to send it’s current value of Virtual Pin to the server.

That means it is called when the app or the Blynk server requests a state from the hardware/sketch, such as when the app first connects or reconnects to the Blynk server, or when the hardware reconnects to the Blynk server due to some network problem.
But if you just want to update the virtual pin V1 at an arbitrary time in your sketch, just call:
Blynk.virtualWrite(V1, pinValue);

at the point in your code where you want to "change" the button's current state. Not in the BLYNK_READ() function, but in your main code, such as:
[...]
else {
  // a lot of code here
  pinValue=0; //here i set pinValue to 0 again in order to return to mode1
  Blynk.virtualWrite(V1, pinMode);
}
[...]

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


text:
Does the Arduino Yun have to be powered exactly at 5V?
I'm working on a senior project and I am using a ATX PSU to supply power to the Arduino Yun and other components. If I'm not mistaken, its powered through the usb. I took a usb cord, strip the sheath and put the proper connections on the breadboard and connected the red wire from the PSU to the breadboard as well. When I measure it, the voltage is 5.1V max. I'm scared to hook it up to the Arduino since I read that if its above 5, it will fry it. Is this voltage fine? If not, will I have to put resistors on it to get it down?

The physicist in me has to mention that the words measure and exactly cannot be used together. Your measurement of 5.1V will have an uncertainty (unfortunately often mis-called "error") of +/- x%, so the real value is in a range. The x% is indicated on the measurement device and the range must be matched (worst case) with the data sheet of the component. As a further side note, the +/- x% may actually be +x%, -y% (the uncertainty is different depending on the direction) and can even be a function (in each case), where the uncertainty depends on the measured value.

It is fine. That is only 2% too high. The microcontroller is the ATmega32U4 and it can have 5.5V. The wifi module runs at 3.3V, and it has a voltage regulator. Some voltage is also lost in the cable. If the voltage is 6V, then you are in the danger zone, but not with 5.1V.
There are clones and shields of the Arduino Yún. Each has its own power supply demands. You should read what the specifications are for your board. The official Yún board requires 5V from the USB cable or 5V at the VIN pin.

The official USB voltage tolerance is 4.75-5.25, so 5.1 is within usb tolerance, thus I would expect a device that can be powered from USB to be just fine

You was right about the voltage being loss in the cable, once I hook it up to my arduino, the voltage dropped to 5.070V, which made me feel better.

I would avoid directly powering any micro without voltage regulation. Things like zener diodes and dedicated regulators adds complexity. But you can pretty much power it off any positive rail at or above 5v DC.(Use nothing greater than the specs) They can also be had and implemented for very little, that and they are used on the UNO board.

You said “you can pretty much power it of any positive rail at or above 5v DC.“ Power what? An Arduino? (NO!) A regulator? It depends on the type of regulator. Linear regulators need a higher input voltage than their output voltage. Buck/boost power supplies are a lot more flexible. I’d be careful about making unclear statements like that, lest a naive reader feed 12V into VIN on his Arduino and fry the board and everything connected to it.

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


text:
Constants within array of structs causes strange compiler errors?
In my sketch I have the following:
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       HU_ADDR, UNKNOWN_ADDR, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

When I compile this, for some reason the Arduino IDE points at the first line and says "expected '}' before ';' token". If I replace the text like so:
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      0x190, 0xFFF, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  0x190, 0xFFF, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       0x190, 0xFFF, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           0x190, 0xFFF, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         0x190, 0xFFF, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

Then it compiles with no complaints.
....what? Why? Aren't these functionally identical? Why does the compiler care if I use HU_ADDR instead of 0x190?

Don't put a semi-colon at the end of #define.
Whatever comes after #define NAME will be used to replace NAME across the source code.


text:
Decreasing Arduino pro micro power consumption
I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro?
Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)

how are you obtaining the GPS coordinates?

Most techniques apply to all Arduino boards. Remove the power led. Put the microcontroller in sleep-mode. Possibly remove/exchange the voltage regulator. Put attached devices to sleep, or remove power to them entirely.

Bringing Down power consumption by taking the LED out and lowering the
  clock ?

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...


text:
Increasing number of iterations not increasing time
I am using Arduino Uno with Atmel Atmega328. I am using micros() function in Arduino IDE to measure time taken for execution. Here is my code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
    delay(1000);
}

The output comes as 4. But if I increase the number of iterations in the for loop to say around 1000000000 it still shows that for loop takes same time of 4. Is there a function which I can use to measure time properly in arduino?

The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling micros will itself take time).
BTW, the granularity of micros is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.
You need to do something that the compiler thinks "does something", like this:
void setup() {
    Serial.begin(115200);
}

volatile byte b;

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j)
      b++;
    Serial.println ((micros() - a));
    delay(1000);
}

By making b volatile the compiler cannot decide that b isn't doing anything useful, so now the timings make sense.
I got 72 for 100 iterations and 144 for 200 iterations.

Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

You can see what the compiler did if you examine the generated code:
    unsigned long a = micros();
  d8:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  dc:   6b 01           movw    r12, r22
  de:   7c 01           movw    r14, r24
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
  e0:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  e4:   ab 01           movw    r20, r22
  e6:   bc 01           movw    r22, r24

As you can see, between the two calls to micros there isn't any sort of loop.
To find the assembled code you can follow the steps documented here.
Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:
avr-objdump -S xxx.elf

You may want to redirect the output to a file:
avr-objdump -S xxx.elf > myfile.txt

Depending on how the Arduino IDE was installed you may have to find the pull pathname of avr-objdump and use that instead of just the program name.

To force iterations I ususally use for(...) { asm volatile("nop"); }.

Good idea. In reality the OP probably wants something "real" timed eventually so the problem will just go away when the loop does something useful.


text:
Does the Arduino pro-micro 3.3v use an 8MHz crystal or a 16MHz crystal with a clock divisor of 2?
I am trying to convert some 5v Leonardo-compatible boards to run at a lower 3-3.7v voltage, so that I can power my project using LiPo batteries.
As far as I can tell, the default Leonardo settings (and pro-micro settings) will not run at this voltage. When I power the boards (which expect 5v) from a lithium battery, typically the system does not start at all. My two theories are that either the 16 Mhz xtal oscillator does not start resonating, or that the brown-out detection of the boards precludes booting at the lower voltage.
I would like to modify the boards to run on lower power. Since the pro-micro exists in a 3.3v variant, I presume there is some way to get the Atmega32u4 chip working at lower voltages. I have reviewed the Atmega32u4 datasheet and schematics from sparkfun, as well as examined the fuse bit differences between the 3.3v and 5v versions of the pro micro. As far as I can tell, the only difference in configuration is the brown-out detection. The clock source settings are configured for a crystal between 8Mhz and 16Mhz, so this could be the same for both boards.
I wasn't quite able to understand the build system for the Catarina bootloader, which might give hints as to how the clock is handled. It seems like both the 3.3v and 5v boards bootloaders are built from the same source, but with a different "CPU frequency" variable. However, there are quite substantial differences in the .hex file outputs and I wondering if there is something fancier going on.
As far as I can tell, it's possible to get an 8MHz clock on the Atmega32u4 either by using a 16MHz xtal with a clock divisor of 2, or using an 8MHz xtal with a clock divisor of 1.
Since the pro-micro 3.3v is the "mainstream" supported board using the Atmega32u4 at a lower voltage, I would like to configure my project to be compatible. Which means I need to build in a compatible clock source, if possible.
Does anyone know more details of the pro-micro 3.3v/8Mhz configuration that might help clarify how to set this up?

When a 16MHz xtal is used with a clock divisor, then the clock part of the atmega32u4 is still running at 16MHz. I doubt if it is documented what it will do with lower voltages. You need a 8MHz xtal (or the internal resonator) to run it at 8MHz. The bootloader is described in the file 'boards.txt'. Not every atmega32u4 bootloader at 8MHz needs to be the same. Adafruit has an atmega32u4 at 8MHz as well: https://www.adafruit.com/product/3675 Try to use the official arduino boards if possible for the best and long lasting support.

So the pro-micro 3.3v uses an 8MHz external crystal?

I'd assume Adafruit uses different crystals. Not doing so would be weird. When building the bootloader, the compiler knows the crystal's speed by the F_CPU constant. It uses this to set F_USB, and (make the leds blink in the same interval](https://github.com/adafruit/Caterina-Bootloader/blob/917e066d83eef0d56222b5e2b518db4805637ce5/Caterina.c#L216). I think, before building these, some Adafruit employee changes the makefile to have the correct F_CPU, PID, and fuses for either the 3V of 5V version.

I have a partial solution: one can simply overclock (i.e. allow the Leonardo to run at 16MHz despite the lower power). Presumably this is risky and could lead to bad things eventually. (I've bricked one board actually by not setting a slower baud rate for writing fuses). One must simply set the brown-out detector for the lower voltage. The fuse configuration for this is E:CE, H:D8, L:FF. This is the same fuse configuration used on the pro-micro 3.3v, with an 8MHz XTAL. It turns out that the same clock fuse settings work with both the 8MHz and 16MHz xtals.

On the schematic of the Sparkfun Pro Micro 3.3V/8 Mhz (here) a resonator of 16 MHz is drawn. But also is stated there: "Board is marked with combination of resonator frequency and regulator voltage". From this you can deduct that the 3.3V/8MHz and the 5V/16MHz versions don't have the same resonator and that the 3.3V/8MHz version most probably has a 8MHz resonator.


text:
Relay active low and ESP8266 GPIO pins
I am using a ESP8266, specifically the ESP-12-E :

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.
It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

In my arduino code when I issue:
  pinMode(4, OUTPUT);

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.
How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:
digitalWrite(4, LOW);

Before low is sent to activate my relay?
Hope this makes sense!

use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);

@Trevor_G Wait what. That's actually the answer. RenegadeAndy, have you tried anything at all?

@HarrySvensson no. I didnt expect the act of calling the pinMode() function to actually cause the pin to go to LOW.

@RenegadeAndy I do hope this is the last time you write "no" to that question. Why should we help you if you can't even try things on your own.

Sorry...without being informed how would I have known to try this? Researching GPIO and reading tutorials , which ALL say run pinMode before digitalWrite, how was I to know to try this? You have done little to nothing to help. @Trevor_G said all that was needed, you are not being helpful at all in your allegation.

FYI: Most of these devices have similar output stages where the latch that holds the output state is before the pin driver itself. If you write to it when the pin is input the state just sits there internal. BTW: some folks just toggle the pin direction with the internal state set rather than the pin state itself. Not a method I'm keen on though since they rely on the week pullup.

@HarrySvensson Yes, it never feels right adding one sentence answers...

GPIO4 is LOW during reset (and thus boot), so an active-low  relay will erroneously click on power-on if wired to GPIO4. use GPIO 3 or maybe 2 or 16. you also might want to set pinMode(n, INPUT_PULLUP) to lock it into floating until needed.

@danadavis how did you know this about which pins are low on boot etc? Whee is this docced?

RenegadeAndy, Thanks a lot, I could not find this solution anywhere, thank you so much, it solved my task, happiness to you,

The answer thanks to Trevor_G was:
use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);

Yes this really helped

authors: Никита Чаузов


text:
How to use the HC-05 properly?
It all started when I was working on my Arduino project, which involves an Arduino Nano, an HC05 module and a bunch of sensors (DHT 11, soil moisture and LDR) with Blynk App. Everything worked as it should (compiled properly) but there was no transfer of data (HC05 was paired).
At that time before pairing, the HC05 was blinking rapidly and after pairing it was blinking twice rapidly every 5 seconds. Note I connected everything as the example said... (You know HC05s TX RX to HW Serial Pins vice-versa).
So later I tried again with everything stripped out (took out all sensors and just the barebones sketch) and added the button widget in the app to control the Nano's onboard LED). Again everything worked as it should but there was no connection between the HW and the Blynk APP (it was not switching on the LED).
Then I tried with an another Bluetooth app and it didn't work as it should. Then I got to know something's wrong with the board itself. So I tried to boot it into AT command mode with this Guide. But it wasn't accepting any commands (NO replies).
So what do I do?
NOTE: I didn't get any relevant question so sorry for that. And do you need anything else?
Edit: It worked. I dont really know how. I think there was maybe a problem with the voltage divider but not sure. Thanks for your time and answers.

Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources (HC-05), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.

I tried 9600 also....

This worked perfect for me HC-05
Try it out.

Did it work out?

Try enetering AT mode and change the default baudrate for HC-05. Maybe use some higher baudrate, it improves communication. Also, check if you’re doing the serial reading properly.


text:
Can't display any number using 74HC595
I just started using elegoo UNO R3 and I have the problem displaying different numbers on the segment display using the 74Hc595. I have no problem with the uploads and the circuits are working fine. However, the segment  doesn't display any numbers besides 8. Is there a problem with the code or the wiring? any suggestion?
byte seven_seg_digits[10] = { B11111100,  // = 0
                          B01100000,  // = 1
                          B11011010,  // = 2
                          B11110010,  // = 3
                          B01100110,  // = 4
                          B10110110,  // = 5
                          B10111110,  // = 6
                          B11100000,  // = 7
                          B11111110,  // = 8
                          B11100110   // = 9
                         };
// connect to the ST_CP of 74HC595 (pin 3,latch pin)
int latchPin = 3;
// connect to the SH_CP of 74HC595 (pin 4, clock pin)
int clockPin = 4;
// connect to the DS of 74HC595 (pin 2)
int dataPin = 2;

 void setup() {
  // Set latchPin, clockPin, dataPin as output
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

// display a number on the digital segment display
void sevenSegWrite(byte digit) {
  // set the latchPin to low potential, before sending data
  digitalWrite(latchPin, LOW);

  // the original data (bit pattern)
  shiftOut(dataPin, clockPin, LSBFIRST, seven_seg_digits[digit]);

  // set the latchPin to high potential, after sending data
  digitalWrite(latchPin, HIGH);
}
   }

void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);
}

here is my circuit and the tutorial diagram:

I give you +1 for writing decent code.

Display get stuck at '8' or keep looping '9'-'8'? What if you count from 0 to 9?

display get stuck at 8

May be a silly comment, but you did change the argument in your two delay(0); calls to higher values, right? The display will seem to aggressively flicker while going through all digits, so it may just seem that it is "stuck" at lighting all LEDs.

You're not giving your eyes time to see the numbers change. If you were a pigeon you might just see some numbers flicker past very rapidly, but we mere humans don't have a hope of seeing them - not without introducing some delay.
void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);  // <--- Number of ms to wait between each digit
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);  // <--- Number of ms to wait between counts.
}


text:
Printing char array from array of structs in progmem to serial
(I apologize if this is a c++ question, I'm too green to know if this is unique to the Arduino IDE)
I've moved an array of structs into my PROGMEM because I was running into memory issues:
#define HU_ADDR                 0x190
#define ALL_AUDIO_ADDR          0x1FF
#define MY_ADDR                 0x360
#define UNKNOWN_ADDR            0xFFF

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEONRARE,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC,
  ACT_PRESSAM,
  ACT_CD,
  ACT_STATIONFOUND,
  ACT_ENABLECD,
  ACT_CD2
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  word Payload[24];
  char Description[20];
};

const MessageDef MessageTable[] PROGMEM = {
  {ACT_POWERON,           HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x00, 0x100, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                    "Tune Knob"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,    {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                       "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,     {0x46, 0x01, 0x11},                                                                                "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,     {0x60, 0x45, 0x01, 0x11},                                                                             "Passive: Strong"},
  {ACT_PASSIVEONRARE,     HU_ADDR, UNKNOWN_ADDR, 4,     {0x100, 0x20, 0x01, 0x11},                                                                            "Passive: Fierce"},
  {ACT_PASSIVEON_0,       HU_ADDR, ALL_AUDIO_ADDR, 16,  {0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x100, 0x80, 0xF1, 0x31, 0x74},    "Vol Knob"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,    {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                                   "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x00, 0x9F, 0x31, 0x62},                                                                             "No DISC available"},
  {ACT_PRESSAM,           HU_ADDR, ALL_AUDIO_ADDR, 24,  {0x00, 0x60, 0x31, 0xF3, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x30, 0x00, 0x58, 0x00, 0x6C, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AM/FM Switch"},
  {ACT_CD,                HU_ADDR, ALL_AUDIO_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x01, 0x30, 0x01, 0xFF, 0xFF, 0xFF, 0x00},                                   "CD switch?"},
  {ACT_STATIONFOUND,      HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                     "FM station found"},
  {ACT_ENABLECD,          HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x77, 0x00, 0x81, 0x00, 0x00, 0xF1, 0x31, 0x60},                       "Enter CD mode"},
  {ACT_CD2,               HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x62, 0x45, 0x01, 0x11},                                                                             "CD message 2?"}
};

const byte MessageTableSize = sizeof(MessageTable)/sizeof(MessageDef);

I've adjusted accordingly in my code segments that reference this data using pgm_read_byte_near() for example. However, I'm not really sure how to get the Description field anymore. When MessageTable was in dynamic memory I could just use:
Serial.println(pgm_read_word(MessageTable[msgid].Description))

But now that seems to be printing... maybe the addresses of the data? Instead of printing out the character array I need to see. How do I parse this more correctly?

You can use the strncpy_P(char* dest, const char* src, size_t maxLen); function which will copy a zero-terminated string of at max maxLen bytes from PROGMEM into RAM. Then print the string from RAM.
Example code:
//We have global buffer in RAM. +1 for 0 termination
char descBuf[20 + 1];

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

    //Copy the description string of the first message in the buffer
    strncpy_P(descBuf, MessageTable[0].Description, 20);
    //Print it
    Serial.print("Description: ");
    Serial.println(descBuf);
}

Together with your code above, that prints on my Arduino Nano as:
Description: Tune Knob

If you don't want to have a 21 byte big buffer in RAM (or there are larger strings you wish to print), you can also use the pgm_read_byte function to read and print the string characters byte-wise. Example:
Serial.print("Description: ");
char c = 0;
for(size_t i=0; i < strlen_P(MessageTable[0].Description); i++) {
    c = pgm_read_byte(MessageTable[0].Description + i);
    Serial.print(c);
}
Serial.println();

For further reference, see the Arduino documentation on PROGMEM: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


text:
Hooking up LCD screens reclaimed from old camcorders to Arduino
Has anyone had any luck using LCD screens reclaimed from old electronics with Arduino, such as camcorders etc?
My 8 yr old has an old sony handycam (dcr-trv103) in bits and now wants to use the LCD screen with the arduino. I'm not even sure how I would go about this. Any tips? How do I figure out 'what does what' in terms of the inputs? How would I drive this thing / what do I need to do to send visual images to it via an Arduino?
Here's the front and back panels of the LCD screen, and their hookups.
The Screen

Screen hookup

I'm assuming this is the backlight

backlight hookup

Note: someone identified this as a duplicate of another question about reusing a cellphone LCD screen. This question is specifically about reusing an older camcorder LCD screen. Also that other question has very little answers. I found the answers below useful and educational. Thanks all.

Not trivial to say. You need a driver board for this, the signals in the flex cable won't be of much use to you in your Arduino, I think. Might be some parallel interface instead of an easy SPI interface. I would start by identifying where the signals in the flex cable go to on the original board, then identify chips and datasheets for them, and from there find out what protocol the display speaks. Also you might find https://www.youtube.com/watch?v=6SOXMDb4cjI interesting. It's an interesting advanced project though, would like to see the results of that.

Possible duplicate of Can I control a cellphone's lcd (+touch screen)?

@gre_gor Not a cellphone lcd, it's from a camcorder. Different question.  Anyhow that previous questions answers were not helpful. the answers below are educational. Thanks.

I'm voting to close this question as off-topic because it is about undocumented and unidentified displays, and not at all about Arduino.  Only once you have full documentation of the display requirements could you possibly then have a valid Arduino question, but probably still not a practical one.

@AgentZebra doesn't matter what kind of unknown LCD it is. The answer is  still the same.

@ChrisStratton well I'll just save the answers before you do then :D  It was a valid arduino question as it involved arduino :) Anyhow, these are some useful answers for my son, so maybe they'll be useful for someone else too.  It literally asks the question "Is this worth trying  to do with an old LCD screen and an arduino?" The answer is no, which is a great answer, as it saves time :)

@gre_gor not according to Maximilian Gerhardt's answer above "Might be some parallel interface instead of an easy SPI interface", sounds like it does make a difference what kind it is.

@MaximilianGerhardt Thank you for your helpful answer.

@AgentZebra the same can also be said for that LCD. You can guess for both of them. That dupe gives you the same answer. And the answer would be the same, regardless if an Arduino is involved, so it is not about Arduino.

it's possible, just usually too complex. strip the case apart, google the inner part numbers. you might get lucky and it's a common interface, or one that someone else has made an arduino library for, or maybe an arduono lib for the base controller that will allow it to be mounted, even if the custom commands are unknown. if nothing, just buy a new LCD; they are under $10, and it could takes weeks to reverse-engineer an in-the-wild LCD

@gre_gor Either which way, we have been helped by these answers. So I appreciate that.

Question locked cant figure out if DMing is a thing here so adding this as a comment for future peeps linked here from a search. Ok, so, I recently broke down my 103, and if you have not acquired the service manual yet I HIGHLY suggest you do. The schematics sections make reverse engineering dang near trivial. From what I have gathered there is some sort of I2C/SPI bus for the back LCD and a "Y/U" video pair from the main board. Also a 15v rail but I dont know if its vital. Basically its easier to go back a step and interface with the pcd it was connected to. The LCD itself is 12bit ... 1/2

2/2 12bit color in 4:4:4 format, IIRC. The service manual schematics lay out the signal paths pretty well, but I wouldn't know where to begin trying to bit bang an image to it. I believe the LCD uses that signaling format that is across like 4 or 6 lines and the R G and B bytes are sort of jumbled across them.....like I said, itd be easier to just interface with the PCB in the flip out bit that has the signal conversion IC on it. Also, fun fact, the eyepiece CRT (bw version) only takes 5v and a standard composite signal like the one that the RPi puts out...(rca plug or 4th pin on new boards)

3/2 hit me up if you need more info or want the manual. How to hit me up through here.... I have no idea..... my desktop is off at the moment, but will edit/clarify those posts as needed when its back up. So.... Yeah.

This is likely a type of TTL LCD interface.  But it is nearly impossible to describe more as there are so many variations both in hardware and in timing.
Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image.  For the necessary processing power, you would have to utilize one of the top end Arduino boards.  Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS.  Which means hours spent on developing software for this LCD will likely only work for this LCD.
It would be far easier to just buy an LCD and interface board known to work together.  If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there".  Fortunately, there are such COTS parts available.  Here is a tutorial describing such a device connected to an Arduino Uno.


text:
Honeywell HPMA115S0, sensor not start again after stop
I use HPMA115S0 sensor with Arduino for Nodemcu, i can read it value but face one problem. The sensor not work after send stop measure command (fan not start too).
const int StartPmMeasure[4] = {0x68, 0x01, 0x01, 0x96};
const int StopPmMeasure[4] =  {0x68, 0x01, 0x02, 0x95};
...
void stopSensor() {
  if (isSensorStart) {
   Serial.println("INFO: Stop sensor");
   sendCommand(AutoSendOff);
   sendCommand(StopPmMeasure);
   isSensorStart = false;
 }
}

void startSensor() {
 if (!isSensorStart) {
  Serial.println("INFO: Start sensor");
  sendCommand(StartPmMeasure);
  sendCommand(AutoSendOn);
  isSensorStart = true;
 }
}

what do you do then? do you have to replace the sensor?

@jsotola i think it not the device fault, i ask Honeywell support but still not receive the answer. And i have only one, it take me 2 week to purchase.

Please explain a few things before the question becomes answerable.  (1) Source code for sendCommand(...).  (2) Meaning of the bytes (each byte) that you pass to sendCommand(...) as parameters.

Are you saying that after you stop it, and then call startSensor it won't start?

The sensor commands have acks, I'd check to see what it is responding with when trying to start it again.

@NickAlexeev i use source from https://github.com/jalmeroth/ESP8266-Honeywell/blob/master/ESP8266-Honeywell.ino Datasheet, Customer Use Protocol https://sensing.honeywell.com/honeywell-sensing-hpm-series-particle-sensors-datasheet-32322550-c-en.pdf

@DigitalNinja Yes, it stop and never respond with any command

I have the same problem here. I'm using a HPMA115S0 with an ESP8266 and found out that the sensor don't respond in general if you are doing a deep sleep with the ESP. If the ESP wakes up, the sensor does not respond on commands till you remove the 5 volts of the HPMA for a short time to make an "hard reset" of the sensor.
I think there is a problem with the ttl-level on the UART-RX-line of the HPMA. Because if you're pulling the rx-line of the sensor manually to ground (maby the ESP is doing this if he goes to deep sleep or wakes up), the sensor does not respond after that.
I spend very much time in this phenomenon. I used different pins on the ESP for software UART and used the hardware UART, problem still exists.
I assume that the ESP pulls all his pins on ground level for too long. That means that the stop bit (high-level), which the sensor wants after 8 bits are transmitted, is not present. This leads to strange behavior of the sensor.
I don't have a digital storage scope to see the level on rx-line, so this is only a presumption. But I don't have this problem, if the ESP idles with an sleep-command.
Maby you are also doing a deepsleep with your ESP which results in the same problem?
Best regards

Yes, that is my same setup, it can not work after send stop measure command. If you make esp deep sleep and not send stop command it still work with "continuous mode". Honeywell support service is very bad too, they ignore my email.  I end this buy use other sensor and find that this sensor HPMA115S0 very inaccurate, it give random result in 1 minute in stable environment. So Plantower PMS7003/PMS5003 is the solution and it is very accurate, stable and cheaper than Honeywell one.

Exactly.If you let the sensor push his measured results (autosend enable=default) you could let the ESP8266 sleep. But the problem in this case is the higher power consumption of the sensor which is not a solution for me, because this device should be battery powered. Thanks for the tip of the Plantower sensor! This sensor also has an reset pin to reset the sensor if something goes wrong.


text:
Send custom 802.11 data frame with ESP8266
I would like to send raw 802.11 data frames in order to transmit pictures with the ESP8266.
I have the Espressif SDK 1.3 and so far I have tried to construct a packet and send it with wifi_send_pkt_freedom, but it didn't work. I cannot pick it up with wireshark or airodump-ng on Kali.
here is the code:
wifi_set_channel(5);

uint8_t packetH[36]={
0x80, 0x00, //Frame Control
0x00, 0x00, //Duration
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, //Receiver Address= Destination Address
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, //Transmitter Address= Source Address
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, //BSSID
0x00, 0x00,                         //Sequence control
0x01, 0x02, 0x02, 0x03,0x03,0x03,0x04,0x04, //Body
0x05, 0x03, 0x02, 0x01 //FCS
};

wifi_send_pkt_freedom(packetH,sizeof(packetH),0);

For testing I just wanted to send some numbers in the Frame body, but later it should send pictures. The goal is to receive unidirectional video transmittion. One ESP8266 should send and the other one should receive. Both have their wireless card in monitor mode.
My guess is that the packet construction is complete wrong. Can someone help me understand how to "build" a proper packet?

For a bigger exposure on your good question I'd recommend you to post this question on Espressif's esp8266 forum at https://bbs.espressif.com/ instead. Also, maybe look at https://github.com/pulkin/esp8266-injection-example .

Thank you, thats a good idea. I have already looked at that example but I cannot find a way to insert data frames

Why do you think you want to craft custom frames to do this? What's wrong with a normal higher level protocol, like UDP?

I think this is what CNLohr did in his latest video. He's using this SDK

Wow CNLohr has really interesting projects. UDP is also a good option!


text:
Using an accelerometer with an Arduino as a shock sensor
I really need some help.  I have absolutely no experience with accelerometers and have a project that would work great if I could integrate one into it.  I am not hinting to have some write me a code, just get me looking in the right direction.
My code (below) was written to work with 2 buttons and an LED.  Basically, its nothing but a reaction timer using an RGB liquid crystal display.
Sequence of events...

power on
displays “push button to start”
when panel button is pushed, the loop begins by randomly selecting a
“FIRE” time when “fire” button is pressed, it echoes the time it
took
my FOR statement, allows it to loop three times before returning to
the begin.

This was all what I set out to accomplish, originally.  My sister has been using it at a retirement home for some of the patients to play with.  Lately she asked if instead of a “fire” button it could be programmed to simply, tap the whole unit, push the unit, or even use a tether of some sort.  I figured an accelerometer was the ticket.
I purchased an ADXL345, I tried playing with several sketches from GitHub.  What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.
How can I use my ADXL345 to be at  complete standstill, until it is “moved,” that it would activate a WHILE statement???
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SparkFun_ADXL345.h>

ADXL345 adxl = ADXL345();
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int lcdRedPWMPin = 17;
int lcdGreenPWMPin = 16;
int lcdBluePWMPin = 15;

void setDisplayRGB(int r, int g, int b)

{
  analogWrite(lcdRedPWMPin,   r);
  analogWrite(lcdGreenPWMPin, g);
  analogWrite(lcdBluePWMPin,  b);
}

void setup()
{
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(13, OUTPUT);
  Serial.begin(115200);
  adxl.powerOn();
  adxl.setRangeSetting(2);    // Accepted values are 2g, 4g, 8g or 16g
  //adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 1, 1);
  adxl.setActivityThreshold(70);
  adxl.ActivityINT(1);
  pinMode(13, INPUT);
  digitalWrite(13, LOW);

  pinMode(9, INPUT); //panel button
  digitalWrite(9, HIGH);

  pinMode(8, INPUT); //FIRE button
  digitalWrite(8, HIGH);

  pinMode(10, OUTPUT); //FIRE led
  digitalWrite(10, LOW);

  // int    fireButton = digitalRead(8);
  int    panelButton = digitalRead(9);
  lcd.clear();
  setDisplayRGB(100, 100, 75);
  lcd.setCursor(1, 0);
  lcd.print("Let's see what");
  lcd.setCursor(1, 1);
  lcd.print("what you got!");
  delay(2000);
}
double timeToFire = 0; //time it took to (fire-trigger)
double fireTimerStarts = millis(); //fire (timer starts)
double triggerTimerStops ; //trigger (timer stops)
int ran; //random

void loop()
{

  int x, y, z;
  adxl.readAccel(&x, &y, &z);
  // byte interrupts = adxl.getInterruptSource();
  int average = (x + y + z);

  while (digitalRead(9) == HIGH)
  {
    lcd.clear();
    setDisplayRGB(40, 200, 75); //purple 40,200,75
    lcd.setCursor(0, 0);
    lcd.print("Press Button");
    lcd.setCursor(0, 1);
    lcd.print("to Start ...");
    delay(50);
  }
  for (int panelButton = 0; panelButton < 3; panelButton++)

  {
    lcd.clear();
    lcd.setCursor(0, 0);
    setDisplayRGB(255, 255, 0); //blue
    lcd.print("  ---READY---");
    delay((int)random(1000, 5000));
    {
      ran = random(1, 3);
      Serial.println(ran);
      if ( ran == 1)
        lcd.clear();
      lcd.setCursor(0, 0);
      setDisplayRGB( 0, 155, 155 );  //red
      lcd.print("     <FIRE>   ");
      lcd.setCursor(0, 1);
      lcd.print(average);
      fireTimerStarts = millis();
      digitalWrite(10, HIGH);

      // if(adxl.triggered>activityThreshold)

      while (adxl.triggered(13, HIGH))

        //while (digitalRead(8) == HIGH)
      {
        triggerTimerStops = millis();
      }
      digitalWrite (13, LOW);
      digitalWrite(10, LOW);

      setDisplayRGB(100, 100, 225); //green
    }
    timeToFire = (triggerTimerStops - fireTimerStarts) / 1000;

    delay(500);
    {
      lcd.clear();
      setDisplayRGB(0, 255, 0);
      lcd.setCursor(0, 1);
      lcd.print(timeToFire);
      lcd.setCursor(11, 1);
      lcd.print("Sec's");
      lcd.setCursor(0, 0);
      lcd.print("Your time was ...");
      delay(1500);
    }
  }

}

An alternative to using an accelerometer is a simple Vibration Sensor Switch. Adafruit has a Fast Vibration Sensor Switch: https://www.adafruit.com/product/1766, Medium Vibration Sensor Switch: https://www.adafruit.com/product/2384 and a Slow Vibration Sensor Switch: https://www.adafruit.com/product/1767, each costing 1 USD.
Edit 1:
If you look for "ADXL345_ACTIVITY" in the SparkFun_ADXL345_Example.ino sketch, there is a comment that says "add code here to do when activity is sensed".
My suggestion is to get the ADXL345 working with this sketch first, then start removing the excess code from it that you don't need. Once you have the bare minimum code required to accomplish your goal, try to integrate that with you current sketch.
There are several "sensitivity adjustments" you can make under the "Configure ADXL345 Settings" section of the code.

Honestly VE7JRO, until you posted this response, I didn't know these things even existed.  Of course going to the Adafruit website, I didn't know lots of that stuff existed.  Your idea would work great, but I am at war with this accelerometer right now and not giving up quite yet.

I purchased an ADXL345, I tried playing with several sketches from GitHub. What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

The accelerometer reports its current acceleration on each axis at all times, whether that acceleration is changing or not. When at rest and upright, it will report close to 1.0 g on the Z axis; when rotated to some other direction and held steady, the vector magnitude of the accelerations on the three axes will be close to 1.0. The vector magnitude is computed as the square root of the sum of the squares of the elements, so rather than averaging, you'll want to do this:
int x, y, z;
adxl.readAccel(&x, &y, &z);

float mag = sqrt( x*x + y*y + z*z );

This mag value should change only slightly if you gently rotate the accelerometer. That baseline value represents 1.0g of acceleration from Earth's gravity.
A rapid motion of the accelerometer will produce some higher or lower value, briefly. Figure out what threshold makes sense for your application and do something like:
if (mag > (BASELINE_GRAVITY * 1.2f))
{
    lcd.setCursor(0, 0);
    lcd.print("You moved!");
}

Thank-you for your response Russell.  What would "BASELINE_GRAVITY" be defined as?

I wasn't able to determine that from a glance at the documentation -- it's unclear to me what units are returned by the adxl library.. It's whatever mag averages when the accelerometer is stationary.

According to the datasheet of adxl345, this chip (so the module) has single-tap, double-tap functionality. As described in the datasheet, you can configure the chip as you want it to operate. The chip has 2 interrupt pins. When it is configured to operate one of the tap modes and senses the tap, it gives an interrupt signal. You can check that signal and process the information.


text:
Soil moisture sensor problem
I'm having a problem trying to run a bunch of code, using an "if" state which uses a variable which should get a value from a soil moisture sensor.
I'm using the sensor digitally, so it should just sense a value between the 2 discrete "0" and "1". However, even if I think my code is ok, it simply doesn't work, as the value is always "0"(default value is 0 for the global variable "sms" i use). The code I'm posting below is without an "else" state that is following the first "if". But my problem is inside the first "if" state. Please note that jumper wires are ok and also I've tried 3 different soil moisture sensors, two of which were brand new. Any ideas on what's wrong?
//Start of program

char auth[] = "**************";
char ssid[] = "88888";
char pass[] = "99999999";

int Relay1 = D1;
int Relay2 = D2;
int val2;
float val3;
int sensor_pin = D7;
int pinValue;
SimpleTimer timer;
elapsedMillis timeElapsed;
DHT dht(DHTPIN, DHTTYPE);
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
  digitalWrite(Relay1, HIGH);
  digitalWrite(Relay2, HIGH);
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, level);
}

BLYNK_WRITE(V1) {
  pinValue = param.asInt();
}

void loop()
{
  Blynk.run();
  timer.run();
  if (pinValue == 0)
  {
    some code here
    sms=digitalRead(sensor_pin);
    if ( sms == 0)
    {
      if (val2 <= 14)
      {
        code here          }
      else
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);

      }
    }
    else //(sms == 1)
    {
      some code here
    }
  }

Do you mean the sensor_pin sensor is the issue? What sensor is it?  Does it need a pull-up resistor?  If you wire a logic HIGH to sensor_pin instead of the sensor, will it the code's logic work as expected?   I'd add a couple more Serial.println() statements to tell you some debug info.

@Dave X https://images-na.ssl-images-amazon.com/images/I/51YJV7u7mYL.SL1000.jpg

@Dave X Also i when i formated the paste of code, i forgot the int sms=0; global variable.

Serial.println() lines were added. But sms value remains == 0.

jumper wires are ok ... what jumper wires?

reduce the code to the smallest code necessary to demonstrate the problem.

I mean physical wires which were used to connect sensor to arduino.

Code was reduced.

int sms=0;   This variable can NEVER EVER have any value between 0 and 1.  If you try to give it any value between the two it will end up with a 0.  Read up on what types of numbers an int can hold if you don't understand why.

There isn’t a sms=... anywhere in your code. Where would sms get any different value than the initial?

My mistake. I just erased it in order to reduce code. Now you can see where sms gets a value.

Sketch doesn't compile.

Obviously, since code is reduced....

What voltage does the sensor put out?  If you measure the D7 pin with a meter, is it ever above the 3 volt logic HIGH threshold to be interpreted as a 1?

I would put the sensor in sum very wet soil and have some code like this loop(){Serial.println(digitalRead(sensor_pin));delay(500);} and see what it says.  It might be that you have to tweak the pot on the board to set the sensitivity and it only goes high when it passes a certain value.


text:
Fool Proofing My Arduino IC Checker
I am creating an IC checker for some high school juniors since a faulty IC can be a nuisance of a bug to find when bread-boarding. These ICs are all simple TTL gating from the 74LS series; the set I am using are all 14-pin and have VCC and GND at pin 14 and 7 respectively.
Thus far my prototype's hardware looks like this:

14 digital pins to connect to the IC inputs/outputs
1 analog pin reading a joystick to navigate through the IC options
1 analog pin set to digital read as a button, which starts the checking process
1 analog pin writing to an LED to indicate whether the IC is valid
2 analog pins (SDA and SCL) as a serial bus to control my display

I actually have the prototype working for a few ICs, but I am concerned that these high school students may test an IC under the wrong selection. Since the digital pins have to dynamically change input/output depending which IC its checking, this allows for inputs and outputs to be mismatched, which could prove fatal to both the IC and the Arduino board.
I want to know if there is a way to check that inputs and outputs are misaligned without having serious electrical failure. Possible some advanced pin control I am unaware of?
Also, if you could answer my question with an example with the 74LS00, whose pinout is diagrammed below and datasheet can be found here.

Very interesting project, but Arduino knowledge is not involved.

Just add some current limiting resistors to the Arduino pins. Those shouldn't affect the operation of the device-under-test, but will prevent damage if something isn't connected right. Might I also suggest putting in some sort of protection in case the chip is inserted upside-down.

Perhaps this would be better on electronics.SE

https://hackaday.com/2018/02/15/building-an-arduino-smart-ic-tester-for-25/ might be of interest

The simplest way to "fool proof" your system (i.e., to prevent damage by a fool, not make it so it always works right even with a fool) is to add a resistor to each connection. The resistor should be sized so that if an IO pin is HIGH and it's connected to a LOW output on the chip the current flow is below the maximum allowed by both ends.

simulate this circuit – Schematic created using CircuitLab
If D5 is set HIGH and the output of the NAND is LOW the voltage difference (assuming a 5V Arduino) would be around 5V. I=V/R, so 5/1000 is 5mA - way below the maximum of 25mA (40mA burst) of the Arduino.
It won't tell you that you have connected the wrong chip, but it will protect both the chip and the Arduino in such an event.
Since it now doesn't matter if the wrong chip is selected you could in fact cycle automatically through each of the chips testing each on in sequence until you find one that gives the correct results. No need to select a specific one - if no chip matches then it's a faulty chip.

Won't a resistor set up of this type drop the voltage across the system significantly? TTL ICs tend only to operate between 4.75V and 5.25V.

No. 1: you're not putting a resistor in the supply connections, only the signal paths. 2: The voltage drop is proportional to the current, and the current from an output to an input is minuscule (an input is very high impedance).

Oh duh, sorry for that comment. I tested this out and it works well.

I would connect each of the IC's IO pins to both a digital output and
a digital (or analog) input of the Arduino, like this:

simulate this circuit – Schematic created using CircuitLab
Drive each pin with the digital output, alternatively LOW and HIGH.
While doing this, read the pin voltage through your input:

If the IC pin is an input, you will have no significant voltage drop
through the protection resistor. Your reading should be LOW when
driving the pin LOW and HIGH when driving it HIGH.
If the IC pin is an output, you will have 5 V through the
resistor whenever the IC's output value doesn't match your Arduino
output. The reading on your input will be independent of the level of
your output.

Obviously, an Uno doesn't have enough I/O pins to implement this idea.
You could use a Mega instead. Notice also that with this setup you don't
need the joystick input: you could just test for every known IC type
until you find one that matches the observed behavior, then display the
part number on your LCD.

You can use a shift register instead of directly using arduino outputs.

Alternatively, just one input pin and switch the pull-up resistor on and off.

@PeteKirkham: You probably would want a pulldown also.

Great idea but I only have the arduino uno.

I am tempted to repeat the old engineering trope "You can't make it foolproof - fools are so ingenious".
If you want to proceed, and are prepared for the complexity 2 solutions suggest themselves.

Limit the current supplied by the Arduino output if connected to a pin on the IC configured as output.
Probably less complex is to test each pin by loading it to 0V and 5V to find which are TTL outputs. A TTL input will unable to source any significant current, while an output will be able to draw current to/from either 0V or 5V.

Either will require quite a bit of additional hardware.
This is not strictly an Arduino problem, but an Arduino would be an ideal solution.


text:
How does DDRD |= _BV(PD2) differ from digitalWrite(2,HIGH)?
I'm attempting to copycat the work of Louis Frigon's Toyota Aux Enabler. I have (with a lot of help on this site) managed to begin capturing and understanding messages on the AVC-LAN bus, but I can't quite send messages.
Frigon uses the following line to drive output signal to high:
DDRD |= _BV(PD2) | _BV(PD3);

I have more or less no idea what this means. He then 'releases the output' with the following:
DDRD &= ~( _BV(PD2) | _BV(PD3) );

If I copy these lines verbatim I don't get the same results. If I set the output high and then read the bus, I don't even see the signal I'm putting out. I wonder if this is related to the differences between his Atmega8 and my Arduino Nano?
I can't paste my or Frigon's work here due to character count limitations, so here is his github for the project: https://github.com/halleysfifthinc/Toyota-AVC-LAN
The most important files to my question are BigSchematic.jpg and AVCLanDriver.c.
Here is a dump of my current code: https://pastebin.com/NG9U5FuL
Here is my schematic: https://i.stack.imgur.com/csiVv.jpg

I give you +1 for the your work investigating your problem.

Each port on the ATmega328P (or the ATmega8 for that matter) is
controlled by two registers¹:

DDRx, where x is B, C or D, is the “data direction register”. It is
used to set the pin to either input or output. Writing to this
register is roughly equivalent to calling pinMode().
PORTx is the port's “data register”. It is mostly used in output
mode to set the pin to HIGH or LOW. Writing to this register is
equivalent to calling digitalWrite().

All this is covered by the Arduino tutorial on direct port access.
And, of course, by the datasheet; more specifically by
section 18.2: “Ports as General Digital I/O”.
As you may now notice, the original code does not use anything like
digitalWrite() to write to the bus, relying instead of the equivalent
of pinMode(). This is related to the electrical characteristics of the
bus:

You write a “physical 1” by actively driving AVC+ high and AVC− low
You write a “physical 0” by releasing the bus, in which case the
potentials of those lines are set by the termination resistors.

That's why you see InitMCU() setting PORTD for driving AVC+ high and
AVC− low, but leaving DDRD in its initial state (“leave pins
tri-stated” says the comment). At this point the bus is in the
“released” state. Then pulses are sent by setting the pins to output
mode (“Drive output to signal high” in the comment) and, after an
appropriate delay, setting them back to input mode (“Release output”).

¹ I am leaving away the details that are irrelevant to the code in
question, like the internal pullup or pin toggling via PINx.


text:
USB Host Shield plus 2 identical joysticks
I'm trying to get two identical joystics (Saitek cyborg 3D) running with the USB-Host-Shield on a Mega 2560 and an USB-Hub.
I already get the event-messages of both of them:
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>

// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

#include "hidjoystickrptparser.h"

USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid1(&Usb);    // first Joystick
HIDUniversal Hid2(&Usb);    // second Joystick

JoystickEvents Joy1Events;
JoystickEvents Joy2Events;

JoystickReportParser Joy1(&Joy1Events);
JoystickReportParser Joy2(&Joy2Events);

void setup() {
        Serial.begin(115200);
#if !defined(__MIPSEL__)
        while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
        Serial.println("Start");

        if (Usb.Init() == -1)
                Serial.println("OSC did not start.");

        delay(200);

        if (!Hid1.SetReportParser(0, &Joy1))
                ErrorMessage<uint8_t > (PSTR("SetReportParser1"), 1);
        if (!Hid2.SetReportParser(0, &Joy2))
                ErrorMessage<uint8_t > (PSTR("SetReportParser2"), 1);
}

void loop() {
        Usb.Task();
        Serial.print("\tX1: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.X, 0x80);
        Serial.print("\tY1: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Y, 0x80);
        Serial.print("\tX2: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z1, 0x80);
        Serial.print("\tY2: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z2, 0x80);
        Serial.print("\tRz: ");
        PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Rz, 0x80);
        Serial.println("");

}

My question is: How can I distinguish the events from the different joysticks.
I'm trying to get some kind of port-information from the USB-Hub. Unfortunately something like
!hid->GetAddress()

within the JoystickReportParser doesn't do the job as it always returns 0.
Any ideas?

look at the hub demo

That's what I'm doing since several days but I don't get the clue. I get message-events but how do I recognize from which port they do come?
In the hub demo there is this function: PrintAllAddresses() which takes a pointer to the device. But it's called within this statement: Usb.ForEachUsbDevice(&PrintAllAddresses);

In the hub demo there is this function: PrintAllAddresses() which takes a pointer to the device. But it's called within this statement: Usb.ForEachUsbDevice(&PrintAllAddresses);
So how would I call something like this from within the JoytickReportParser or the eventhandler OnGamepadChanged ?

Or how do I get a pointer to the device from which a message-event comes in?

To be honest. I'm not so familiar with all this pointer arithmetic.
All these -> :: ! * .  Is still a little bit wired to me.

i am talking about this demo ... https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/hub_demo/hub_demo.ino  .... it looks like it prints a whole bunch of info about every usb device that is plugged in ..... start with that

the ! is a boolean not statement ... when it is rainy it is !sunny

@jstola I'm afraid you statement is incorrect sometimes it is sunny && rainy at the same time.

logically, that is true, but it was meant as a rough example of the not operator (also my comment is incorrect because the not is really a unary operator, not a statement)

Thank you very much for your help. @jsotola I already ran this hub-demo. So I know that the two Joysticks are attached to two USP-Ports at the hub, which have addresses like A and B. The output of the PrintAdress() Function is something like (0,1,A) and (0,1,B) for the two Joysticks.
What I do not know is. How can I access this information from within the event-handler-function called void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt) {} from the Joystick-Demo.

A documentation of the USB-HUB-2.0 Library can be found here: http://felis.github.io/USB_Host_Shield_2.0/inherits.html. (There's a nice class hierarchy at the bottom of the site). From looking there it seems to me that the class USBHID that might be responsible for the Joystickreadouts seems to inherit from the class USBDeviceConfig (or vice versa what would not make sense to me but who knows. Does the direction of the arrows indicate the direction of inheritance in this diagram?)

So my question is: What line of code would I have to add to the event-handler-function void JoystickEvents:: OnGamePadChanged(const GamePadEventData *evt) {} in hidjoystickrptparser.cpp from the USBHIDJoystick.ino-Demo to get these A and B USB-addresses from my previous comment? So when a message-event comes in I know from which Joystick it comes.

Or let me put the question in other words. The void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt) {
}-Function gets a pointer to an event-object *evt. This *evt-object must somehow be connected to the USBdevice-object where it comes from. But how can I access this, and how can I figure out which method to call stepping through the inheritance hierarchies to get the address of the USBdevice?

Or maybe like this: In the hub-demo I find the function:
void PrintAllAddresses(UsbDevice *pdev)
{
UsbDeviceAddress adr;
adr.devAddress = pdev->address.devAddress;
Serial.print(adr.bmAddress, HEX);
Serial.println(")");
}
So if I could somehow get this handle *pdev from within the event-handler-function from the Joystickdemo, I could imagine to get this address. But unfortunately I do not know how to get this.

I am trying to solve the same issue. I got already working in the main void loop: Serial.print(Hid1.GetAddress());
But to distinguish the 2 identical joysticks in the event loop, did you already manage -> Palmstroem?

this could be a possible answer:
https://github.com/Bratski/Arduino-2-Joysticks-to-PPM

Not quite the question that was asked but part of the problem.
This is a simple introduction to pointers.
int variable = 42;                              // Create a variable
int* pointer = &variable;                       // Create a pointer to the variable (by getting its address)
*pointer = 99;                                  // Set the address to a new value
printf ("variable has the value %d", variable); // Print 99.

&x get the address of x
*y dereferences the pointer y, which means it 'turns it back to a variable' (this is simplistic view which isn't really true, but will do for now).
So you could, if you wanted (which you wouldn't) do this *&z which would be the same as doing z.
Basically think of & and * as a pair of complimentary operators like - and + or * and /.  (They aren't operators, but to start with it might help).
The next problem is when you do this
SomeFunction(&variable);

All function parameters in C/C++ are passed by value by default.  This means the function gets a copy of them not the actual value.  So if you had:
void FunctionOne (int val)
{
    val = 99;
}
int val = 4;
FunctionOne(val);
printf("val = %d", val);   // You will see 4 printed.

If you pass by reference then you will see 99 printed, to pass by reference you can do it one of two ways.
void FunctionTwo (int& valByRef);
void FunctionThree (int* valPointer);

FunctionTwo only works with C++ (It will work with an Arduino).
FunctionThree might cause a segmentation error if NULL is passed in and the function writes to it.
If it helps in my opinion pointers was one of the hardest concepts to grasp in classic C/C++ so don't worry if you don't understand it just have a play with it and see what you can do.
Calling Methods

object.method() - Call the function method on the instance called
object which is of type X.
object->method() - Call the function method on the instance called
object which is a pointer of type X.
object::method() - call the function method
which is a static member of class object (static means it doesn't
change any data within an instance of a class)
*object->method() - Avoid this like the plague.  It either means *(object->method()) or (*object)->method() to know you would need to look at the type of object and the return type of the function.  Its easier just to bracket it to remove ambiguity.

As for *object.&method() I've never come across that one, but that doesn't mean it doesn't exist. :)

Those who don't understand pointers are doomed to program in Javascript the rest of their lives.

Thank you very much for this explanation. Good explanation! What confuses me is: Sometimes you can access a property by object.method or by object.object.method then by object::method and object->method or object.&method or *object.&object::method and object.@->/!%&wtf$method and so on. These things were not made for human brains to be understood.

Are you saying I'm not human? :)
(See edit)
Its learning a new language, and you just have to remember certain rules, the more you use them the more they become ingrained, there is no short cut :(

Thank you very much. Superhuman!
Any ideas for the original question? I'm inside a signal-handler-function and want to access an attribute of a parent or grand-parent class, but don't know how to find the right method. The documentation at http://felis.github.io/USB_Host_Shield_2.0/class_u_s_b_device_config.html seems to be quite comprehensive. But I don't get the clue.

!Hid->GetAddress() always returns 0. Maybe I need to do something like *evt.HIDDevice.Hid->GetAddress() but all trials like that lead to compile errors.

this could be a possible answer, in Arduino Code, the USB Host Shield 2.0 library is necessary:
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>

// Logitech Attack 3 HID report
struct GamePadEventData {
    uint8_t X, Y, Z1, Z2, Rz;
} __attribute__((packed));

class JoystickEvents {
    public: virtual void OnGamePadChanged(const GamePadEventData *evt, int joystick);
};

class JoystickReportParser : public HIDReportParser {
    JoystickEvents *joyEvents;
    uint8_t joyId;
    uint8_t oldPad[sizeof(GamePadEventData)];
    public: JoystickReportParser(JoystickEvents *evt, uint8_t id) : joyEvents(evt), joyId(id) {}
    virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
    if (!is_rpt_id && len == sizeof(GamePadEventData)) {
        // Checking if there are changes in report since the method was last called
        bool match = (sizeof(oldPad) == len) && (memcmp(oldPad, buf, len) == 0);
        if (!match && joyEvents) {
            joyEvents->OnGamePadChanged((const GamePadEventData*)buf, joyId);
            memcpy(oldPad, buf, len);
        }
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt, int joystick) {
    Serial.print("Joystick ");
    Serial.print(joystick);
    Serial.print(": X: "); PrintHex<uint16_t>(evt->X, 0x80);
    Serial.print(" Y: "); PrintHex<uint16_t>(evt->Y, 0x80);
    Serial.print(" Z1: "); PrintHex<uint8_t>(evt->Z1, 0x80);
    Serial.print(" Z2: "); PrintHex<uint8_t>(evt->Z2, 0x80);
    Serial.print(" Rz: "); PrintHex<uint8_t>(evt->Rz, 0x80);
    Serial.println();
}

USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid1(&Usb); // first Joystick
HIDUniversal Hid2(&Usb); // second Joystick

JoystickEvents JoyEvents;
JoystickReportParser Joy1(&JoyEvents, 1);
JoystickReportParser Joy2(&JoyEvents, 2);

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

    Serial.println("Start");

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay(200);

    if (!Hid1.SetReportParser(0, &Joy1) || !Hid2.SetReportParser(1, &Joy2)) {
        ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1);
    }

}

void loop() {
    Usb.Task();
}


text:
Can you use digital pins as PWM output?
I am currently working on a robotics project that requires 16 PWM outputs to control 16 servos. Is it possible to use Arduino Uno's digital pins as PWM output pins through code?
If it is not possible, what microcontrollers do you suggest to use on such a project?

“The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega.”

You can get a PCA9685 servo controller card to multiplex 16 servos through I2C. e.g.:  https://www.adafruit.com/product/815

Only specific Digital Pins marked with ~PWM can generate a PWM signal. In the case of arduino Uno the pins 3,5,6,9,10,11 are all hardware PWM driven, and are marked on the Uno with a ~ or something.
Others can be driven with software PWM(though I wouldn't recommend it). As the Arduino Uno uses the ATMEGA328P, the number of pins is same with other boards using same processor.
On the other hand if you want to run 16pins for PWM, its best if you use Arduino MEGA 2560 because its processor supports more than 6 Hardware pins for PWM. Also you get the advantage of a higher memory storage for your code

PWM is not used to control servos.
Servos need a pulse that is 1 to 2 ms wide, with 1.5 ms wide being the center position, that occur every 20 ms (50 Hz).
A 2560 has enough timers and the library to control up to 48 servos.

It is a form of PWM, though not the PWM generated by analogWrite().


text:
Communication over UDP between Dues with Arduino WiFi Shield
I'm using the Arduino WiFi Shield to make two Arduinos Due communicate using UDP. The first node to send a message (the Client) doesn't always receive a reply from the other node (the Server). The code for the Client:
#include <string.h>

#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>

#define BUFSZ 90

// variables for WiFi connection
char ssid[] = "ssid";
char pass[] = "pwd";
int status = WL_IDLE_STATUS;

char sendBuffer[BUFSZ];
char recvBuffer[BUFSZ];

WiFiUDP Udp;
unsigned int localPort = 51515;

IPAddress server(192,168,88,251);
unsigned int serverPort = 12345;

void printWifiData()
{
    // print your WiFi shield's IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print("IP Address: ");
    Serial.println(ip);

    // print your MAC address:
    byte mac[6];
    WiFi.macAddress(mac);
    Serial.print("MAC address: ");
    Serial.print(mac[5],HEX);
    Serial.print(":");
    Serial.print(mac[4],HEX);
    Serial.print(":");
    Serial.print(mac[3],HEX);
    Serial.print(":");
    Serial.print(mac[2],HEX);
    Serial.print(":");
    Serial.print(mac[1],HEX);
    Serial.print(":");
    Serial.println(mac[0],HEX);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial); // wait for serial port to connect

    // connect to WiFi network
    while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
    }

    // print connection details
    Serial.println("You're connected to the network");
    printWifiData();

    Udp.begin(localPort);
    strcpy(sendBuffer, "abcdefghijklmnopqrstuvwxyz123456789101112131415161718192021222324252627282930313233343536");
}

void loop()
{
    Udp.beginPacket(server, serverPort);
    int len = Udp.write(sendBuffer);
    Udp.endPacket();

    Serial.print("Sent ");
    Serial.print(len);
    Serial.println(" bytes.");

    delay(10);

    int packetSize = Udp.parsePacket();
    if (packetSize > 0) {
        Serial.print("\nReceived packet of size ");
        Serial.println(packetSize);

        Serial.print("From ");
        IPAddress remoteIp = Udp.remoteIP();
        Serial.print(remoteIp);
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into recvBuffer
        int len = Udp.read(recvBuffer, BUFSZ);
        if (len > 0) {
            Serial.println("Contents:");
            Serial.println(recvBuffer);
        }
        else {
            Serial.println("Read 0 bytes.");
        }
    }
    else {
        Serial.println("\nNo packets yet.");
    }
}

Server:
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>

#define BUFSZ 90

// variables for WiFi connection
char ssid[] = "ssid";
char pass[] = "pwd";
int status = WL_IDLE_STATUS;

char sendBuffer[BUFSZ];
char recvBuffer[] = "acknowledged";

WiFiUDP Udp;
unsigned int localPort = 12345;

void printWifiData()
{
    // print your WiFi shield's IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print("IP Address: ");
    Serial.println(ip);

    // print your MAC address:
    byte mac[6];
    WiFi.macAddress(mac);
    Serial.print("MAC address: ");
    Serial.print(mac[5],HEX);
    Serial.print(":");
    Serial.print(mac[4],HEX);
    Serial.print(":");
    Serial.print(mac[3],HEX);
    Serial.print(":");
    Serial.print(mac[2],HEX);
    Serial.print(":");
    Serial.print(mac[1],HEX);
    Serial.print(":");
    Serial.println(mac[0],HEX);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial); // wait for serial port to connect

    // connect to WiFi network
    while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
    }

    // print connection details
    Serial.println("You're connected to the network");
    printWifiData();

    Udp.begin(localPort);
    Serial.println("Waiting...");
}

void loop()
{
    int packetSize = Udp.parsePacket();

    if (packetSize) {
        Serial.print("Received packet of size ");
        Serial.println(packetSize);

        Serial.print("From ");
        IPAddress remoteIp = Udp.remoteIP();
        Serial.print(remoteIp);
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into recvBuffer
        int len = Udp.read(recvBuffer, BUFSZ);
        if (len > 0) {
            Serial.println("\nContents:");
            Serial.println(recvBuffer);

            Udp.beginPacket(Udp.remoteIP(), 51515);
            Udp.write(sendBuffer);
            Udp.endPacket();
        }
        else {
            Serial.println("Read 0 bytes.");
        }
    }
}

I don't know if it's a timing problem... So I've tried to use delays after the Client send its message but the issue persists. So the Client sends many messages to the Server but receives few replies. I didn't want to put the part of the code in the Client when it's waiting for a response inside a loop in case the first message is lost (so the Client will never receive a response anyway). Did anyone have a simular problem or a suggestion to fix this issue?

duplicate of http://forum.arduino.cc/index.php?topic=525579

UDP is not a protocol that guarantees delivery

I was able to solve the problem. First of all, I needed a bigger delay between the send and receive parts in the Client.
So I'm using delay(35);. This is important so the Client can have enough time to receive the reply before sending another message.
Also, inside the Server, the buffers to send and receive a packet were inverted.
So, the correct would be:
char sendBuffer[] = "acknowledged";
char recvBuffer[BUFSZ];

I understand the messages can stil be lost because UDP does not guarantee delivery, but with a larger delay in an isolated WiFi network all of the messages from the Client got a reply.


text:
Is it possible for ESP8266WiFi client to request the number of clients currently connected to Access Point?
My system consists of several ESP8266 based 'stations', which are synchronised in a way that all of them go into deep sleep and wake up on the same schedule. All stations are WiFi clients. All stations run on batteries and energy saving is critical.
One of the stations is a Master. It contains a modem/router that serves as AP to all stations.   The AP is switched OFF during the sleep phase. When a Master wakes up it switches on the AP and thus starts a communication session available to all stations. When all stations have their data sessions completed and disconnect from AP, the Master switches off the modem/router and goes to sleep.
My question is about the Master being informed that there are no other clients actively connected to the AP. My current solution is WAN based - each station reports to the Web Service on the start and end of their connection. Is it possible to achieve the same result locally - by a request from the WiFi client to the Access Point?

You likely could simply probe the network you are on.  In Linux you would use the nmap command.  Model your code after that command.

I'm voting to close this question as off-topic because the actual question has absolutely nothing to do with Arduino.  The reality of the situation is entirely dependent on the unspecified capabilities of the AP and the other clients.

You can avoid these kinds of questions by reading the documentation or by checking the header files.

What reseache have you done on this topic? Example using a search enginee and searched for "esp8266 show clients connected"? Questions that show no research is normaly closed.

It seems you failed to read and/or understand the question. The system described is successfully implemented at several remote outback locations where it runs on solar power unattended for months. To ensure smooth failover all units are interchangeable, the system has no server, all ESPs are WiFi clients. I challenge you to find a solution to my question thru your 'research'. Anyway, I am happy with this question being closed. Thank you.

Use WiFi.softAPgetStationNum() to return the number of clients connected to an ESP8266 AP.

Thanks a lot, dandavis!
Exactly what I was looking for.


text:
GSM and GPS module don't work together
I am trying to create a project which involves getting latitude and longitude via GPS Module and send it via GSM Module. My problem here is that individual code is working perfectly. However, if am to initialize both together, none will work.
#include "GSM.h"//wrapper class for Sim800l library
#include "GPS.h"//wrapper class for TinyGPS library
GSM *gsm;
GPS *gps;
void setup()
{
    Serial.begin(9600); // Debugging only
    gsm = new GSM();//initializes SIM800l
    //gps = new GPS(11,10 );//initializes NEO6MV2//uncommmenting this line won't make both modules work
}
String telNum;
int i = 1;
void loop()
{
    /*
    Serial.println(gps->getLongitude(),6);
    Serial.println(gps->getLatitude(),6);
    */

    Serial.println(gsm->read(i,telNum));
    Serial.println(telNum);
     ++i;
}

sounds like you need to specify software serial pins.

also, that's not a 5v device, and your red wire goes nowhere ;)

The original libraries uses software serial. Or maybe I didn't understand you @dandavis

I got it working by initializing and  deleting the pointer to the GPS and GSM object.
Initialization and freeing of the objects are made in the loop function. I initialize the GPS, run it in a loop for sometime, destroy it and initialize the GSM and same procedure as GPS.
Though I don't know if it'll have any effects but its working perfectly
#include "GSM.h"
#include "GPS.h"
GSM *gsm;
GPS *gps;
void setup()
{
    Serial.begin(9600); // Debugging only
}

unsigned long previousMillis = 0;//could be any value depending on how quick you want it to elapse
const long interval = 100; //could be any value depending on how long you want it to run
void loop()
{
    gps = new GPS(6, 7);//initialization <SoftwareSerial::begin() function called here>
    while (previousMillis <= interval)
    {
        //GPS codes here
        ++previousMillis;
    }
    delete gps;         //destory initialized object
    previousMillis = 0; //reset value

    gsm = new GSM();    //initialization <SoftwareSerial::begin() function called here>
    while (previousMillis <= interval)
    {

        //GSM codes here
        ++previousMillis;
    }
    delete gsm;//destory initialized object

    previousMillis = 00;//reset value
}

You can't use two softwareserial devices together (or not reliably, and not without knowing exactly what you are doing).
It's not even easy using one software and one hardware serial together unless you know what you are doing.
SoftwareSerial blocks everything else from happening while it's sending or receiving, so using it for things that send unsolicited messages (as GPSs do all the time) causes havoc.
The best you can hope for is to use HardwareSerial for the GPS and SoftwareSerial for the GSM, which is call-and-response most of the time.
Better would be to use a better board that has multiple hardware serial ports.

Ok. Do you have any link that can  guide me through the hardware serial? Gooogling it just keeps bringing up libraries and no examples.

You can use Listen function
for example:
First_softwareserial.listen();// when you need gsm serial

Second_softwareserial.listen();// when you need gps serial

but both libraries in the Question have the SoftwareSerial built in. so show how to use them the way you describe


text:
How to calculate actual Baud Rate and its percent error?
I am using an Arduino Uno, and I need to create a program that calculates the actual baud rate and the percent error for all standard baud rate in Arduino monitor program.

It's listed in datasheets. The table is called: "Equations for Calculating Baud Rate Register Setting"

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

See http://wormfood.net/avrbaudcalc.php

Jasmine, if you found the below answer helpful, please upvote it and/or mark it as the answer. That's a good way of thanking @EdgarBonet for his hard work. See https://stackoverflow.com/help/privileges/vote-up to understand why voting is important.

First, look at the code used by the Arduino core library to configure
the USART baud rate register: it's in
HardwareSerial::begin(). The general formula is
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;

but beware of the hard-coded exception. You can replicate that part of
the code in your own.
Then, look at the ATmega328P datasheet. More specifically, at section
24.4.1. Internal Clock Generation – The Baud Rate
Generator. Here you find the formula
BAUD = F_CPU / (8*(UBRR0 + 1))

assuming the U2X0 bit has been set (again, beware of the hard-coded
exception). Combine both formulas and you get the actual baud rate.


text:
LED blinking count with LDR sensor
How to count +1 all the time if LED blinks with LDR sensor
Image:

If i turn on led it must count into serial monitor 1 and if i turn off led and turn on again then it counts 2.
To turn on led I must put my hand into LDR sensor.
It also looping text in serial monitor "First LDR sensor is Dark".
int ledPin1 = 7;
int ledPin2 = 8;
int ledPin3 = 9;
int ldrPin1 = A0;
int ldrPin2 = A1;
int ledTest = 200;
int ldrStatus1 = 0;
int ldrStatus2 = 0;
int ledCheck1 = 0;
int ledCheck2 = 0;
int Count = 0;

void setup() {

  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);

  pinMode(ldrPin1, INPUT);
  pinMode(ldrPin2, INPUT);
}

void loop() {

  ldrStatus1 = analogRead(ldrPin1);
  ldrStatus2 = analogRead(ldrPin2);

   if (ldrStatus1 <= ledTest) {
    digitalWrite(ledPin1, HIGH);
    Serial.println("First LDR is Dark");
    ledCheck1 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin1, LOW);
    ledCheck1 = 0;
   }

   if (ldrStatus2 <= ledTest) {
    digitalWrite(ledPin3, HIGH);
    Serial.println("Second LDR is Dark");
    ledCheck2 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin3, LOW);
    ledCheck2 = 0;
   }

   if ((ledCheck1 == 1) && (ledCheck2 == 1)) {
    digitalWrite(ledPin2, HIGH);
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin2, LOW);
   }

}

At the moment it counts when it is turned on, like seconds..
How to fix or make it work correctly?

I really don't know what you want to ask... what means +1 all the time? Should it count the number of transitions (of one or both leds?), maybe you have short values which are incorrect (cheap LDRs) and you have to remove short 'spikes' / false postives.

@MichelKeijzers When I put my hand on LDR sensor it must turn light on and tell in serial monitor 1 time turned on and then if i take my hand off led is turned off. and if I repeat it count to 2 and again then 3...

Did you check what values you get when you put your hand over it? And analyzed them? Print out every number (can be many) and check if your program behaves the way you expect when using the values you received. You might have to filter some, or use an average or other way to remove some values that you didn't expect (but the sensor still sends).

@MichelKeijzers Sensor printing "First LDR is Dark" and looping it. How I can make it no loop and counts +1 ?

That means that  if (ldrStatus1 <= ledTest) is always true ... check the value to see if it is what you expect.

Please edit your question to make it clear what you're asking.

@per1234 edited my question.

Use state change detection and hysteresis for counting pulses in an analog signal.
const int lowerThreshold = 150;
const int upperThreshold = 200;

const uint8_t analogPin = A0;
const uint8_t ledPin = LED_BUILTIN;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  static bool state = LOW;
  static unsigned int counter = 0;

  int analogValue = analogRead(analogPin);
  if (state == HIGH) {
    if (analogValue < lowerThreshold) {
      state = LOW;
      counter++;
      Serial.println(counter);
      digitalWrite(ledPin, LOW);
    }
  } else { // state == LOW
    if (analogValue > upperThreshold) {
      state = HIGH;
      digitalWrite(ledPin, HIGH);
    }
  }
}

This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)

The red waveform is the analog input from the LDR. The gray rectangular wave is the state (and the state of the LED). The counter is incremented at each black, vertical dashed line.

LED is always ON..

Then change the thresholds. Do you understand how it works? That's the first step.

I changed low treshold to 0 and led still turned ON. Changed ledPin to 7 where is my led and still led turned on.

That's to be expected, if you set the low threshold to 0, it is impossible to turn off the LED. Go through the sketch, try to understand the logic. Try it with a potentiometer first (left terminal to ground, center terminal to A0, right terminal to 5V) and set the low threshold to 256, and the high threshold to 767. Turn the potentiometer and see what happens to the LED. Then use the analogReadSerial example to see what values you get from the LDR. Adjust the thresholds accordingly.

Edited my question.

@JoeDavid: Have you tried the suggestions in my previous comment?


text:
Can I use atmega328P without capacitors?
I need to use atmega328P without arduino board, so far I know that I will need 16MHZ Quartz Resonator and two 22nf capacitors. However, I have seen that other people are using atmega328P without capacitors.
What is the role of those capacitors? Can I use atmega328P without capacitors?

You need 22pF (picofarad) capacitors, not 22nF.

You also need power supply bypass capacitors.

you can use it without caps and with a crystal, at half speed, but maybe half price too

Those specific capacitors form part of the resonant clock oscillator circuit. If you are using a quartz crystal then they are required. You can't do without them.
If you use a 16MHz ceramic resonator, however, they don't need the capacitors (they're built into the resonator).
Also, if you have your ATMega328P on a breadboard the capacitance of the board itself is sometimes enough to "get it working", though as soon as you transfer your circuit to a permanent PCB it will suddenly stop working for no apparent reason.

One could also use the build-in 8MHz RC oscillator, and remove the crystal entirely.

@Gerben Indeed. Or use an external clock source, like a MEMS oscillator.