text:
How can I dim a 10w LED?
I'm trying to dim a 10w LED via Arduino PWM.
This is the LED that I have: http://www.banggood.com/10W-Warm-Pure-White-High-Brightest-Save-Power-LED-Light-Lamp-p-88169.html
Without knowing much about this stuff, I bought this (namely because it had LED, DIM, and PWM in its name): http://www.ebay.com.au/itm/121437119430?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
I can't get the eBay dimmer to work for love or money.  When I connect it to ground directly on the battery terminal, it goes off, which means the dimmer circuit is working.  I don't even know where to start with MOSFET dimming solution, but I think that the IRFZ44N MOSFETs are the wrong ones because they won't turn on with 5v power (they need 10v or something, but those are the ones I have on hand).
I can't seem to find any good guides on how to do this after stacks of googling, and to be honest, I don't even know if those LED's can be dimmed in the first place.
What do I need to make this happen?

Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read its datasheet and so you can get a guess on how it should work:

attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
attach the LED to the terminals LED+ and LED- (remember the polarity!)
attach a transistor to pull down the pin DIM
send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)
EDIT:
How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done

That sounds great :) A couple of questions though, what transistor should I attach to pull down the pin DIM, and how would I know what frequency the PWM is pulsing at?

Any n transistor is fine. Attach an NPN with a base resistor, or attach an nMOS and you don't need any resistor (i prefer the second solution). Any transistor is fine: I usually choose nMOS in a sot23 smd case, but you can choose anyone - the required power is really low - and possibly logic level - i.e. Gate Threshold Voltage lower than 2V. If you don't know how to attach it, just ask. As for the frequency, according to this arduino page frequency is s approximately 490 Hz or, on pins 5 and 6, approximately 980 Hz. You can measure it though

I don't know how to attach it :(  Can I take you up on that option of asking you how to attach it? :D

@LewisCianci I added the (very complicated) wiring scheme. You just need... A MOS. no external components, no difficult wiring, just an nMOS.

So, just so I have this clear, you're saying I can use the existing LED Driver I have, as long as I have an nMOS sitting in between the Arduino and the light?  The only MOSFETs I have on hand are these: http://www.banggood.com/10Pcs-IRFZ44N-Transistor-N-Channel-Rectifier-Power-Mosfet-p-953277.html.  Will they work?  I heard that these MOSFETs aren't "logic level" so Arduino can't even turn them on.  You're amazing by the way. Tell people in your vicinity that, and tell them that I am witness to this fact.

I don't think that MOSFET I linked to is even close to what you're saying.  I think this is what you mean? http://www.ebay.com.au/itm/General-Purpose-Transistor-BC807-BC807-40-SOT-23-PNP-PARK-5C-0-5A-45V-/181873441750?hash=item2a58807bd6:g:CSgAAOSwsB9V-mlS

Those are power mosfets, so you should probably save them for power applications ;) moreover as you said the threshold voltage is 2-4 V, so it's not recommended. For this tasks I usually use an AO3402 (I bought a batch of them some time ago, so I have it lying around). 100 pcs are aroung 4 AUD from China on ebay. If you want something from Australia, I found that element14 Australia sells some BST82 at 0.49$ for 5 mosfets (shipping fees are high, but sometimes local sellers allow you to buy from distributors like element14, rs, digikey... without having you pay the shipping fees). .. continue

So for instance this is from element 14, this is from RS, or you can check from any distributor. Just look for N-channel MOSFETS (usually under Semiconductors -> Discrete) with a threshold voltage under 2V and you are fine. Double check that the gate-source voltage can be at least 5V and you found your transistor. Now, small caveat. This is for the definitive circuit, because I THINK that your circuit should already work. If you want to double check if it .. continue

works properly BEFORE buying the mos, you can try to use the ones you have on hand because, looking at the typical curves on the datasheet (see figure 1) at 4.5V Vgs and a current below 1A you should have less than 0.1V, which SHOULD make the dim work. So just for a quick check you can use the IRFZ44N, but I suggest to change them as soon as possible. And.. The ebay transistors you posted are PNP, not nMOS, so they won't work. As for the compliment, thank you :) You made me blush ;) Glad if I can help you

Thanks again for all your help.  So, I found this FET at my local electronics shop (JayCar) and this is the datasheet: https://www.fairchildsemi.com/datasheets/2N/2N7000.pdf.  It talks about a threshold voltage max of 3v, but typical at 2.1v. Would that work? And if it would work, would it be ideal or not?

Well, this should work. Lower Vgs(th) are better, but according to the "On-Region Characteristics" graph with a 5V Vgs you get a 0.5V Vds for a current of 0.5A. Since the current is much lower, the voltage is lower too, So, yes, it should work.. It's not the best one, but since it is the only one you have it should work. Just try it and let me know ;)

I would suggest the CAT4101 PWM controllable constant current sink LED driver.  You might want 2 in parallel for the higher current.
They can deal with up to 1A each (theoretically) though they may get a bit hot at that current level - so it would be better to parallel them so they deal with roughly 500mA each.

Is there a board with this chip on it with io pins? Or would I have to just buy the chip and wire it manually?

Have you asked Google? There's some pictures of boards on there, so chances are there are boards available (I used to sell one but haven't made any for a while).

What is the advantage of using the CAT4101 over the MBI6651 the user already has?

I know for a fact the CAT4101 works well (and easily) with the Arduino. I have never heard of an MBI6651.


text:
Communicating between two arduino terminal using Xbee
I have 2 Arduinos, mounted with Xbee Shield and Xbee S1 module on each.
One arduino is mounted on car chassis while another is connected with PC. Our AIM is to send signal from the arduino connected on PC and the motor will be controlled by the Arduino connected on car chassis.
Here is the code of the arduino connected with PC:
char msg= "";
void setup(){
 Serial.begin(9600);}

void loop(){
 msg=Serial.read();
 serial.println(msg);
}

Here is the code of the Arduino on car chassis:
char msg = ' ';
int motorA1 = 2;
int motorA2 = 3;
int motorB1 = 4;
int motorB2 =5;

void setup() {
  pinMode(motorA1, OUTPUT);
  pinMode(motorA2, OUTPUT);
  pinMode(motorB1, OUTPUT);
  pinMode(motorB2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  while(Serial.available()>0){
  msg=Serial.read();
  switch(msg){
   case 'f':Serial.println("Forward");break;
   case 'b':Serial.println("Backward");break;
   case 'r':Serial.println("Right");break;
   case 'l':Serial.println("Left");break;
   case 's':Serial.println("Stop");break;
 }
if(msg=='f'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  Serial.println("Running Forward");
  }
if(msg=='b'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,HIGH);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,HIGH);
  }
if(msg=='s'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='r'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='l'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  }
}
}

Now our next AIM is to send back a feedback from car to the Arduino terminal of PC, e.g. if we are giving 'f' as a input and we get a reply 'Running Forward' on the next line. What line of code should we incorporate for that?

Isn't your code doing that already in the switch statement?

You need two serial connections on the pc Arduino. One that connects via xbee and one that connects to the pc/usb monitor. You need to describe what hardware you have because it can be complicated if you are using a shield with fixed serial pin assignments.

//your code looks almost ok. The thing that i am feeling wrong is that arduino at the PC end. It should communicate with PC and 2nd arduino at the same time. So use arduino mega or "#include " library to avail extra Serial at this end if you are using arduin uno. Your code will be like this..
char msg= "";

void setup(){
Serial.begin(9600);
Serial1.begin(9600)//<----error
}

void loop(){
 msg=Serial.read();
 serial1.println(msg);//<- - -error
}

Please tell me how to add extra serial on the arduino at PC using software serial library as I have UNO. please provide me the final code

source: Stack Exchange

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

sort: votes


text:
Makeblock Arduino keeps stopping from motor overpower protection
I got a makeblock Arduino. Sometimes when I make it go forward at full speed, all motors stop for 3 seconds and it beeps shortly. I think it is that the motors are a little hard to turn for a moment and it stops to prevent damage to the motors. It is getting very annoying. Is there any way to disable it or make it less sensitive?

It is unlikely the pause in operation is because of the motors.  It is more likely the Makeblock is stopping because the  motor controllers are too hot.  Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch.  If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.
An alternative explanation involves a limited power supply.  It could be that when the motors are demanding high current, the voltage drops and the processor resets.  Consider a power supply that can offer more amperage.  Or larger capacity batteries.

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


text:
Variable was not declared in this scope
When I compile this code I get a  error: 'currentState' was not declared in this scope.
The code:
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 }

state currentState; <---- Error

const int BUTTONPIN = 4;
const int ROTARYPIN = A0;

void setup()
{
  //Open Serial Monitor for debugging purposes
  Serial.begin(9600);

  //Configure the pins
  pinMode(BUTTONPIN, INPUT);
  pinMode(ROTARYPIN, INPUT);

  //Initialise the LCD
  lcd.begin(16, 2);

  //Assume that the current state is wait for start up signal

  currentState=WAITSTARTUP;
}

You have missing semicolon after the enum:
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 };  // <-- here

//go the Tools > Boards and check that you have selected the right option of your hardware? your remaining code is almost ok. But remember to add semicolon ";" sign at end every coding line.
  enum state: int{NOTREADY,WAITSTARTUP,WAITSECRET,REVEALSECRET};
  state currentState; //<---- Error

  const int BUTTONPIN = 4;
  const int ROTARYPIN = A0;

  void setup()
  {
    //Open Serial Monitor for debugging purposes
    Serial.begin(9600);

    //Configure the pins
    pinMode(BUTTONPIN, INPUT);
    pinMode(ROTARYPIN, INPUT);

    //Initialise the LCD
    lcd.begin(16, 2);

    //Assume that the current state is wait for start up signal

    currentState=WAITSTARTUP;
  }

I don't see what has board selection to do with this problem. And the solution to the actual problem was already posted.


text:
How to write arduino code which reads the value of a flex sensor?
Since this is this the first time im doing Arduino, im really confused what the code is to:
write a code which reads the value(nae the value 'flexValue') of a flex sensor connected to analog input AN0.
The value should be a 10-bit integer number having value between 0-1023, inclusive.

https://www.arduino.cc/en/Reference/analogRead


text:
Software reset on Micronucleus possible?
I'm wondering if anyone knows if it's possible to do a software reset using the watchdog timer on a microcontroller using the Micronucleus bootloader.  When I try it, it doesn't fully reset, as in when connected with USB to a computer, it doesn't appear as a libusb device for a short period of time.
I'm suspecting a watchdog timer reset isn't as early in the boot process as necessary for Micronucleus to wait for programming.
I'm using an ATTiny841 to make a small wrist watch for my son, and I wanted to keep it to a single button.  I've been resetting for programming with a pair of tweezers grounding the reset pin side of a pullup.  Not a huge deal if it's not possible, once I have the code set, there won't be much need to re-program.
Here's the watch so far:  https://www.youtube.com/watch?v=lkH16xzkSJM
Thanks in advance!

So you are trying to put the ATTiny into bootloader mode? I think you need to look at the ENTRYMODE setting of the micronucleus bootloader

Ahhh… that looks like it would do it exactly!  Thanks!   I had just been using the pre-compiled firmwares for the 841.  Looks like I'll have to take the plunge and learn how to compile my own.

I just flashed a bootloader compiled with the entry mode set to watchdog and it works perfectly!  Thanks so much, I wouldn't have thought to look for a solution there.

Great to hear. Your project already looks great. Looking forward to seeing the end result (I already subscribed to your youtube channel).

For anyone interested, the watch is pretty much complete.  You can read more about it here:
https://hackaday.io/project/163887-vlads-round-watch
or here:
https://www.hackster.io/chris3d/vlad-s-round-watch-ea1c8f

Thanks. I had already seen it come by on hackaday.io, and recognized it. Liked and Followed. It's looking amazing. Especially the metal housing. Most diy watched i've seen just add some straps, and call it a watch.

Thanks, yea, I enjoy the hardware design part as much as I do the electronics!

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


text:
ESP8266 Supply Voltage dropping below 3.3V
I am trying to power an ESP8266 with a 3.3V regulator (this one, can supply ~ 1A). I've been struggling for days to get the ESP to work – it will occasionally boot, occasionally connect, but then not work again for hours. What I mean by "not working" is that it will often have trouble communicating over UART; or, upload my code, but not run it; or, run my code and crash on an Exception 0.
Now I have noticed that my voltage rail is dipping severely, sometimes below 3V. If I press my reset button, the level returns to 3.3V, but then when the ESP "boots" (but often not running any code, or crashing), it dips back to 2.9V. It is also fine while programming.
Does this suggest my ESP is simply fried? It's possible I briefly misconnected a wire when I first got the unit.

power an ESP8266 - is this a bare esp8266 (which one, 01, 7, 12 etc) with nothing else connected to it?

Yeah, ESP-01, I think. Just have a 5/3.3V logic level converter and some decoupling caps.

Are you just using a bare regulator, or do you have an actual module?

Just have a 5/3.3V logic level converter with something connected to that? if not, remove that, see if that "helps"

Just the bare regulator, with the recommended caps. Main power supply is Arduino 5V via USB.

@JaromandaX the logic level converter is for USB to Serial.

what's the capabilities of the power supply? I mean if the input to the regulator is 5V 100mA I dont' think you can get 3v3 @ 1A output ... can you?

It's my computer's USB, via Arduino. Arduino has a 500 mA fuse and a FET switch on USBVCC. Not sure how much my computer is actually providing. Maybe I'll try with a powered USB hub.

How hot is the regulator getting? To draw anywhere near the rated 1A you need lots and lots of heatsinking.

I think it was my computer. Powered USB hub seems to be working..."Current Available (mA): 500
Current Required (mA): 100
Extra Operating Current (mA): 0"

how much is the arduino itself using?

None. I don't have a FTDI cable :/ so the arduino is held reset (Reset tied to GND) and I'm just using it for the USB to Serial.

The ESP8266 will do an analog calibration when it is running the user code. This will typically be the worst case power requirement. The peak current requirement can be as much as 1/2 an amp. While your regulator probably can supply that I would bet your interconnecting wiring, and maybe the power source, are causing too much voltage drop.
The fact that you can see the voltage go down to 2.9 volts makes me thin that you have serious problems.
Early on when I started with the ESP8266 I was getting flaky operation. I put it down to bad code. But eventually I ruled that out. I took my setup to work (where I design electronic products) and looked at the power connections with a digital scope at the module. Right at the last point before the traces run under the shield. (I use the ESP-12 modules) It dipped just under 3.0 volts for two microseconds, and that was enough to cause a reset.
These things are not tolerant to any power dips. And this is why I recommend anyone starting with the ESP8266 to buy a Nodemcu or a Wemos type module. Something that has the regulator right at the processor.

Yeah, I definitely played myself here. The $5 savings were not worth the hassle.

You probably have not damage the module. It will probably work fine if all the rest of the circuitry is done well.

It's working now with a powered USB hub. See answer below.

It was a power issue. Everyone tells you the ESP8266 needs a lot of current, and I didn't believe them.
In case anyone else runs in to this issue, I was powering the ESP via a 3.3V regulator (fine), being fed from and Arduino's 5V (fine). However: I was plugging my Arduino directly into my MacBook. It seems that my Mac was limiting USB power. Using a powered USB hub (max current ~2A) worked fine, but you could probably also get away with directly powering VIN on the Arduino (or a standalone 3.3V supply).

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


text:
Trying to print text on LCD display from Arduino trinket
I'm trying to simply program an Arduino trinket to display some text on an LCD display.
I'm basically trying to follow this, except connect it to a Trinket rather than an Arduino Uno. The background color of the LCD display is changing as expected from the loop function in my Arduino code, but it's just displaying some o's and arrow's for text on the LCD display.
I'm new to Arduino's (and EE in general), but am a computer programmer.
What am I doing wrong that the sample code in the above link doesn't print text on my LCD display?

Since you mention the target board is an "Arduino Trinket" instead of "Arduino Uno", could there be some difference in how the LCD display was wired? In other words the pin assignments may be different than expected in the example code. As a diagnostic you could try the LCD Hello World example (under File - Examples - LiquidCrystal - HelloWorld if you're using the Arduino IDE). If that doesn't work then you need to find the schematic for your board, determine which LCD pin connects to which ATmega328 pin, and then which "Arduino" pin number that is, so you can update the source code.

Disregard my above comment; I misinterpreted the question; usually Arduino + LCD means an HD44780 LCD connected directly to the ATmega328. That's not the case here. You actually have a serial (RS232-like) connection between two devices. So the real problem is more likely incorrect baud rate, or some other RS232 protocol related issue.

Looking at the first photo, was there some reason you connected the white serial data wire to the trinket's "Digital #0" instead of "Digital #2" as in the example code? Be aware that on Arduino UNO, digital #0 is used for serial receive, so may cause problems to use that pin for a serial transmit. It looks like Digital #2 is not currently used on your board.

Finally tracked down what Arduino Trinket is: ATtiny85 not ATmega328 - very different beast. Your linked example code uses SoftwareSerial (ATtiny85 has no hardware serial). Are you sure you have the correct flag settings? If the ATtiny85 was set to internal 1MHz clock instead of internal 8MHz clock, baud rate will be wrong. I'm not even sure if internal clock is stable enough to support serial comms. If the "trinket" has a external clock oscillator, make sure the ATtiny85 flags are correctly configured to use it. Try to wrangle an oscilloscope to verify the serial comms timing.

@MarkU The reason I used #0 is b/c I had already tried using #1 and #2 and i didn't know if there was a difference between the pins.

How would i check the flag settings? Also I'm pretty sure I tried the Hello World example and it didn't work.

The liquid crystal hello world example code does not work.

You could try this tutorial first to verify that you can get Serial working. Then add LCD. https://learn.adafruit.com/trinket-bluetooth-alarm-system/code. Use the software serial section to debug your trinket communication.

Operating this display should not be out of the range of the ATTiny85 abilities. I have one using a two-way serial connection for a setup routine, that modifies EEPROM values.

First off connect to the LCD Backpack using the USB connector and test it through there to rule out it being faulty.
At the bottom of that page:

For more commands, check the github repository (see the Downloads tab) for a python script that will test all commands on the display.

Testing Trinket Serial:
What you can do is take your trinket and run a basic Serial connection program to test if the Trinket is sending the right info out.
Trinket:
#include <SoftwareSerial.h>
// Create a software serial port!
SoftwareSerial comm = SoftwareSerial(0, 1); //RX,TX
#define LEDPIN  PINB2
void setup() {
  //set baud
  comm.begin(9600);
  DDRB |= (1 << LEDPIN);  // set LED pin to output mode
}

void loop() {
  //print a specific character once a second

  comm.println('a');
  PORTB |= (1 << LEDPIN); // turn on LED
  delay(500);            // 0.5 second delay
  PORTB &= ~(1 << LEDPIN); // turn off LED
  delay(1000);
}

Then you need another Arduino, like an Uno, Leonardo:
// For leonardo use Serial1 for the connection to trinket
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Ready...");

  // set the data rate for the SoftwareSerial port
  Serial1.begin(9600);
}

void loop() { // run over and over
  if (Serial1.available()) {
    char incoming = Serial.read();
    Serial.println(incoming);
  }

}

Or the stock balnk sketch and connect the Trinket Serial out to Arduino TX-> 1.
If using an UNO you can set up a SoftwareSerial style of the above.
I recommend this rather, a USB-Serial converter as it will be quicker and cleaner.
Next you need to see what is coming out. If the received data is correct then there is an issue in the LCD display, try re-flashing the LCD board with new firmware.
If the data comes through correctly then move onto using the Adafruit  code and still connecting it to the other Arduino boards serial connection, replacing the Serial.println(Serial1.read()); with Serial.println(Serial1.read(),HEX);.
If the data still comes through correctly then the data is not being received properly by the LCD backpack.

LCD Backpack
You should test the display board with another Arduino, UNO or Leonardo (32u4).
Run the Adafruit tutorial code and see the results. If the code works then there is a problem with the Trinket and the SoftwareSerial library.
If there are again errors that happen with the LCD backpack when used with a 'normal' Arduino then it is the problem.

Recomendations
Download the ATTiny core from High-Low Tech and burn the 'bootloader' to reset the fuses to 8MHZ setting, also this is a good core to use if you want more space on the ATTiny.
Possibly re-flash the trinket bootloader and make sure the internal clock is 8MHz; the SoftwareSerial library is touchie I believe.

Warning: I do not have a ATtiny85 nor the lcd so this is purely based on what I found after some reading up on this mcu.
What I would do in your situation:
As the trinket is using a ATtiny85 it does not have hardware serial. So a software variant is needed.
You opted for software serial (which is the most obvous in Arduino world) but which seems to be the hardest solution.
According to this source Serial communication with the Tiny's is is possible (And I quote)

you might have to tune the internal oscillator to get a stable
  connection.

Assuming your lcd does not need to send data back; I would try the TinyDebugSerial.

Bear in mind that adding an external crystal would be the easiest/most reliable. But this will cost you 2 specific I/O pins.
There might also be memory issues, since the ATTiny85 has a lot less memory as the ATMega328.
The Arduino Nano (or pro micro) might fit your physical size requirements, while being a lot more "powerfull".


text:
why are there odd spikes in the USB serial data transfer rates?
I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.
I looked into the serial communication using the simplest program I could, but it produces odd results.
void setup() { Serial.begin(9600); }
void loop() { Serial.println("00000"); }

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.
Using the seconds as a marker, I then count the number of data lines for each second.  for example:
44 00000  // recorded at time 44 seconds
44 00000
44 00000
45 00000  // recorded at time 45 seconds, etc

I was expecting that there would be a somewhat stable value for this.  Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second.  When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.
Collecting the zeros for 5000 seconds produced the following results:
most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000.  This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.
What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.
Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created.  That isn't too bad and could be due to timing.
But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.
The percent breakdown is as follows:
137 sets of 00000:  79.15%
138 sets of 00000:  13.8%
139 sets of 00000:  0.39%
140 sets of 00000:  0.51%
141 sets of 00000:  2.05%
142 sets of 00000:  4.11%

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain.  with 137 sets of 00000 there are 685 characters sent serially in one second.
with 142 sets of 00000 there are 710 characters sent serially in one second.
What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

Is there any explanation for the variability?
Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.
I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.
Using a delay of 8ms produced another interesting result:
with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters.  this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.
After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.
This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets.  The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.
I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second.  What could be causing this? and what can be done to make the transfer rates more constant?

While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.
As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its origin just by looking at the timing of its arrival.  That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.
A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino.  That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.
If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.

This could be largely to do with how USB serial works.
USB has a number of different methods of transferring data between the device and the host. Both CDC/ACM use FT232 use a method called bulk transfer. This is a very low priority transfer method and data is moved across the bus as and when it can - that is, when the bus isn't doing anything else. If there is anything else happening on the bus (and there will be) the transfers get delayed until the bus is doing nothing else.
If timing is critical for a protocol, such as USB audio or video where you have to have the data transferred to the host absolutely right now a different method is used. This is called isochronous. It is the highest priority of data transfer, even higher than interrupt data.
However there is no way on the Arduino to use any form of isochronous transfers so you will have to come up with some other method of managing your timing.
As Chris has mentioned the most common method is to include a timestamp with each packet of data. That packet may contain just one sample, or it may contain a block of samples. The important thing is to know when the block starts and from that infer the time of each sample within the block.
It is also important to ensure that your communication with the host isn't running at 100% saturation. You should be running at the highest baud rate that is reliable and only send data at regular intervals giving you time to get the data in between each transfer. Keeping your data packets as small and efficient as possible is also good for keeping you transfer rate sustained properly.

The problem is not USB priority, it is that USB is asynchronous from the serial source, so packet grouping should be considered meaningless. Time stamping packets is not the solution and not supported without changing the USB converter anyway. The serial data can encode an almost regular timing, but the timing of the data through USB is meaningless and should be ignored by the application in favor of encoded timing, either literal or implied.  Using that, you can do audio over bulk transfers in most modern lightly loaded cases.

I think you misunderstood most of my post there...  CDC/ACM Bulk Transfers are asynchronous to the UART source, yes. Isochronous aren't - they are synchronous (or close enough). That is why they are used for audio and bulk transfers aren't. Yes, it is possible to fudge it enough with bulk transfers using a custom higher level protocol, and it is that higher level custom protocol to which I refer when I talk about timestamping packets - not timestamping USB packets but your serial data. If you have a packet that contains 10 samples which are from 1ms intervals and you know the first sample ...

... is at 829736ms then you also know the time of each subsequent sample in that packet. That batching of packets isn't real-time but it is accurate on a per-sample time basis. Bulk transfers can, and will, be delayed by higher priority USB traffic - especially on a bus that is shared with other devices - especially devices that use isochronous transfers. To get the best results directly connect the Arduino to a USB port on the computer and, if possible, check that other devices don't use the same root hub.

No.  Even isochronous transfers, while more regular in rate, are still asynchronous to the source - and they are allowed to be dropped entirely.  In neither case can one ascribe meaning to the USB timing, or even the timing of the USB packetizing process.  Rather, the timing has to come from the original sample clock, or if one is using a serial UART kept busy to sample something that does not have its own clock, then the baud rate.  The receive then either operates using only the source's timing implicit in the data (ie, if is is only doing signal processing).

Or if it is producing audio output, it must buffer the data and then play back using another sample clock, that is either synchronized by a low bandwidth PLL to the buffer level, or more commonly fixed frequency with a variable sample rate converter in between.

And that is EXACTLY what I am saying in my answer!  ADD YOUR OWN TIMING TO YOUR SENT DATA!

No, you said timestamp the USB packets, which is a fundamental mistake - that captures the meaningless timing of the packetization, not the timing of the source which is what matters.

No that is NOT what I said! Learn English!  "As Chris has mentioned the most common method is to include a timestamp with each packet of data." Not each USB packet. Each packet of DATA!

Which is the USB packets - because there are no "packets" before that.

Yes, there are packets!  At the moment the packets are 6 bytes long - 5 × 0 with a delimiting \n. That is a packet.

Packets exist at different layers in a protocol. Packets within packets within packets.

That could make sense if it were written on its own, but when mentioned following a few mistaken paragraphs implying USB could be source synchronous, it really looks like you are recommending timestamping the USB transfers.

Well I am not. How would you do that anyway? It's not in the CDC/ACM protocol. You are thinking I am recommending something that is not possible to do. Why would you think that?

You had already proposed things not in the CDC/ACM

Especially when I am specifically pointing to what you are saying to do!

Where do I do that then?

Isochronous is not in the CDC/ACM (nor would it solve this problem)

I never said it was. You really do need to learn to read - or at least to pay attention to what you are reading and not skim it.


text:
Send RF 433MHz data to Domoticz RfxCom with protocol X10 from Arduino Nano
I have installed Domoticz on Raspberry Pi and bought an RfxCom 433MHz emitter/receiver.
It works well for example with Chacon DiO 54781 door sensor.
I want to create my own sensor with Arduino that would be recognized by Domoticz as a native RF 433MHz device.
In first place, I want to make a flooding sensor, I also need an On/Off information.
I would like to implement X10 protocol because it seems to be the simplest one.

I finally found a documentation about RF X10 protocol:
X10 RF Receiver.pdf
With following Hardware :

Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
RF 433MHz emitter/receiver  (3€) (Note: only the emitter is used)       https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
3 wires : VCC, GND, Signal (on Arduino pin 2)

I've created the following working code for Arduino Nano :
/*
* Custom sensor (base code)
*
* Emission in RF 433MHz with the X10 protocol for Domoticz
*
* Hardware :
*   Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
*   RF 433MHz emitter/receiver  (3€)        https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
*       Note: only the emitter is used
*   3 wires : VCC, GND, Signal (on Arduino pin 2)
*
* Documentation found for RF X10: http://www.printcapture.com/files/X10_RF_Receiver.pdf
*
* Example of malformed data received in RfxMngr in mode "nodec" (before this code was correctly debugged) :
*
*       Packettype        = UNDECODED RF Message
*       UNDECODED NEC:1C515C86F0
*
*
* Correct data that is now receveived by RfxMngr with this program :
*
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 13
*       housecode     = D
*       unitcode      = 1
*       Command       = On
*       Signal level  = 7  -64dBm
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 14
*       housecode     = D
*       unitcode      = 1
*       Command       = Off
*       Signal level  = 7  -64dBm
*------------------------------------------------
*/

const int pin_emit = 2;         // Signal pin for RF433 emitter
const int pin_led = 13;         // Internal LED : it will be ON when the "On" command is sent in RF, and OFF the the "Off" command is sent (changed each 60s)

const unsigned int X10_A1_ON = 0x00;
const unsigned int X10_A1_OFF = 0x20;

const unsigned int X10_address = 5;     // this is Housecode. In my case 5 results in "D" house code
unsigned int X10_data = X10_A1_ON;      // command. I have implemented only On/Off for unit code 1

void setup() {
  pinMode(pin_led, OUTPUT);
  pinMode(pin_emit, OUTPUT);
  digitalWrite(pin_emit, LOW);
}

/**
* Bit to 0 : 1.125ms between rising edges, so before next bit
*/
void X10_sendBit_zero()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(570);       // Total 555+570 : 1125µs = 1.125ms
}

/**
* Bit à 1 : 2.25ms entre les "rising edges"
*/
void X10_sendBit_one()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(1695);      // Total 555+1695 : 2250µs = 2.250ms
}

void X10_send8bits(unsigned int data)
{
  // - Send the 8 bits, and then the complementary of the 8 bits.
  // from documentation: "Within each byte, bit7 is received first and bit0 last"
  int mask = 0x80;
  for(int i = 0; i < 8; i++)
  {
    int bit = mask & data;
    if (bit == 0)
      X10_sendBit_zero();
    else
      X10_sendBit_one();

    mask = mask >> 1;
  }
}

/**
* Sending a byte consists of sending this byte, and then sending the opposite of the same byte.
* As we send the opposite as well as the data, the total duration is always the same : 8 * (1.125ms+2.250ms) = 8 * 3.375 = total of 27ms
*/
void X10_sendByte(unsigned int data)
{
  X10_send8bits(data);
  X10_send8bits(~data);
}

/**
* Send a complete X10 packet
*
* Total duration :
* (9ms + 4.5ms) + (27ms + 27ms) + 0.555ms + 40ms = 108.055 ms
*  from doc: "It appears, from articles on the 'net, that other people have seen a range from 95 msec to 116 msec for various transmitters and that standard X-10 transceivers can tolerate timing variations of 30-35% from nominal."
*/
void X10_sendState_once(unsigned int data)
{

  // - Header
  digitalWrite(pin_emit, HIGH); // "Burst" de 9ms
  delayMicroseconds(9000);
  digitalWrite(pin_emit, LOW); // Silence de 4.5ms
  delayMicroseconds(4500);

  // - Data
  X10_sendByte(0x50); // - Address
  X10_sendByte(data); // - Data

  // - Send a last rising edge to validate last bit
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitraty value (but always the same), for "VCC" state.

  // - Footer
  digitalWrite(pin_emit, LOW); // Silence de 40ms pour signifier la fin de l'émission
  delayMicroseconds(40000);

}

/**
* Send a complete packet multiple times (this X10 protocol has not ACK))
* From doc: "Most X-10 RF transmitters send a minimum of five copies of the code separated by 40 msec silences although some can send single bursts."
*
*  5 times 108.055ms = 540.275 ms, half a second
*/
void X10_sendState(unsigned int data)
{
  // - "clean" to be sure to have a zero for the first rising edge on init
  digitalWrite(pin_emit, LOW);
  delay(1);

  // - Send 5 time complete packet
  for(int repeat=0 ; repeat<5 ; repeat++)
    X10_sendState_once(data);

}

void loop() {

  if(X10_data == X10_A1_ON)
    digitalWrite(pin_led, HIGH);
  else
    digitalWrite(pin_led, LOW);
  X10_sendState(X10_data);
  delay(60000);              // 1 minute

  // - I change state each 60 seconds to see changes in Domoticz
  if(X10_data == X10_A1_ON)
    X10_data = X10_A1_OFF;
  else
    X10_data = X10_A1_ON;
}

By changing House code and data, it is now possible to create our own RF sensors.

Just to say, since my previous answer, I concluded it was too much effort for each new sensor to find how to implement a new protocol. So I finally tried and adopted "MySensors", because I only need to feed it with payload.


text:
Arduino uno, VIN and 12 volts
I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?
I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.
If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

Possibly. It depends exactly what it is you want to drive.
When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).
Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).

Thanks for the info. As mentioned I plan to drive an oled strip and it requires at least 10V.

It's all a question of the current. You need to total up the currents of everything - motors included - and make sure it stays below 1A.

That depends on the motor shield - for some motor shields you have to cut a circuit path (or unset a jumper) to separate the power for the motors from arduino's power!


text:
Schematic for the adafruit motor shield v2.3
I am trying to locate a schematic for the Adafruit motor shield v2.3. It has many ports and currently I have found little to no explanation of what is on the board. I located this picture which highlights the motor ports, servo ports, and Arduino Pins. But what about everything else?
What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins? What is the PWMs 0,1,14,15? How is the big empty board in the center setup?

Everything can be found out by reading the schematic which, incidentally, is the first hit on Google when you search for "Adafruit motor shield 2.3 schematic":

What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins?

Yes. They're just there to make it easy to solder wires and jumpers to.

What is the PWMs 0,1,14,15?

They are connected to PWM pins 0, 1, 14 and 15 of the PCA9685.

How is the big empty board in the center setup?

It's just holes. Known as a "matrix prototyping board" for you to solder your own components and things into. Nothing there is connected to anything at all, it's up to you to make the connections with solder and wires.
As you can see from the schematic the only Arduino pins used are SDA/SCL (A4 and A5) and two PWM pins D9 and D10. Everything else comes from the on-board I2C PWM chip.

Thanks for clearing it up. I found this schematic earlier but it didn't go into detail like you mentioned in your post.


text:
Powering Adafruit motor shield
Making sure not to blow anything up before testing.
I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the  motor shield to power the nema-17 motor and a serial connection to power the arduino.
Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?

You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.
But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.

Thanks, that is exactly what I needed to know. I shall use an external power supply for the motor shield.


text:
How to program the Robotdyn Mega 2560 PRO MINI?
I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.
How do I connect the pins to an FTDI?
Which setting do I have to use in the Arduino IDE?

Connect the Arduino to the FTDI in the following way:

FTDI - Arduino
VCC - VCC
GND - GND
RX - TXD
TX - RXD
DTR - 100nf capacitor - RST
CTS is not connected

Use the following settings in the Arduino IDE

Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

The image shows the Arduino with colored connectors and with 4 extra rows of connectors. These are not part of the original Arduino. I added them to make it easy to connect lots of I2C devices for testing.


text:
What is the difference between the digital temperature sensors SHT31 and DHT11 or DHT12?
I am looking for a digital temperature sensor with I2C interface.
I found the SHT31 and the DHT12 (compatible to DHT11). Both also include humidity sensors. And I found libraries for both of them. But I did not find a comparison.
https://sea.banggood.com/GY-SHT31-D-Digital-Temperature-and-Humidity-100-RH-I2C-Sensor-Module-For-Arduino-p-1167498.html
https://sea.banggood.com/KEYES-DHT12-Digital-Temperature-and-Humidity-Sensor-Module-Compatible-DHT11-For-Arduino-p-1400920.html
What are the (significant) differences between those sensors and libraries?
In the moment I want to use a sensor to measure the intake air temperature of a motorcycle. One degree celsius accuracy is good enough for this purpose. I don't want to calibrate them, this is why I looked for the digital sensors.

If the dht12 is as terrible inaccurate as the dht11, then the humidity is not 5% accurate, but more like 50%. The dht12 can be used for 3.3 and 5v arduino boards. The sht31-d can also be used for 3.3 van 5v arduio boards. the sht31-d is accurate. Conclusion: dht12 = bad, sht31-d = good.

Thanks, that good enough for me. I will order the SHT31-D. But for the record: Is that your personal experience or do you have any source for this information?

Both. I have a dht11 and dht22 that are very bad in measuring the humidity value. It turns out that when they are packaged in the wrong plastic, the humidity sensing element gets disturbed. This is a test (the sht31-d was not tested): http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many.html but this test does include the sht31: https://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many_addsht31.html I also trust the information that adafruit gives: https://www.adafruit.com/product/2857


text:
One Arduino collects data, several other Arduinos use the data. What is a simple way to do this?
I am looking for a way to exchange a few bytes of data from one Arduino to two or more additional Arduinos. It's a one way communication and speed is not a problem. 10Hz is fast enough.
Data Collector Arduino: I have one Arduino with SPI and I2C shields which collects and analyzes data from a CAN-BUS in a motorcycle. The CAN-BUS supplies lots of information but I filter it down to few info like which lights are on, intake temperature, motor RPM, which gear.
Light Control Arduino: This Arduino should know which lights are on. Depending on low beam, high beam, indicators, etc. it will control additional lights which are not part of the original bike.
Motor Control Arduino: This Arduino should know the current RPM, gear, etc. and work with that data.
The question is how do I "transfer" the data from the data collector to the other Arduinos? If it would be a little simpler I would connect some digital pins which the data collector would write and the others would read. But there are not enough pins for my needs and why use 10 pins when maybe 2 are enough.
All the Arduinos use SPI and I2C connected devices so I don't think it's a good idea to use SPI or I2C for communication between the Arduios.
I guess Serial communication would work with 2 Arduinos but not with 3 or even more. Maybe I could use multiplexing or something like that?
Maybe I could let the data collector Arduino write data into some kind of shared memory and the other Arduinos could read it?
What do you suggest? I am sure there are simple solutions out there but I didn't find anything. I don't mind any extra ICs.
Before someone suggest to do all in one Arduino: Maybe it would be possible. But I really like to keep the modules (Arduinos) separate and I want to be able to add others later if I want to. Then I only want to change the software of the collector Arduino and don't touch the others.

why not do everything with one Arduino?

It is possible to send out data from one Arduino to multiple others at once via serial (UART). You simply connect the TX of your master Arduino to the RX of all the slave Arduinos. All receiving Arduinos will get the same data with that. You only need 1 pin (for the connection sender TX to the multiple RX). This is a bit limited to the number of slaves and the speed, but that doesn't seem to be an issue here (since you only have a few).
This is a 1-way communication, since at any line there must not be more than 1 TX (sender). If you have more than 1 TX on a line, you will burn your hardware as soon as both TX send out data simultaneously.
I remember some sites that stated it to be possible to also do multiple sender UART, when you adhere to a protocol and put in some safety hardware (I think they used diodes and current limiting resistors). But that is somewhat out of scope here. If you really need a 2-way communication, you maybe should rethink the whole structure of your solution. As Juraj suggested in his comment, it might then be easier to unite the functions to less Arduinos.

Be sure, that the Arduinos share the same ground. This is needed for any communication, when you don't utilize extra hardware (like an optocoupler).

You can do it simply by addition of extra RX and TX pins by use of library like Software Serial Library. For reference you can go here https://www.arduino.cc/en/Tutorial/TwoPortReceive . By using this library you can increase number of ports in master arduino and you probably can give command to other slave arduino commands through master arduino. In this way each arduino can communicate with each other.

That also imposes problems, since you can only listen to 1 SoftwareSerial interface at any time. But for one way communication that is no problem.


text:
Deep sleep mode for the Uno without complicated circuits?
so I'm building something using an Uno that will run on batteries - so, I've watched a couple of these low power tutorials to lessen the energy consumption so the batteries can last longer, but they're not exactly what I want - they all require some sort of circuit. I've found this tutorial (http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/) which only needs an LED, and it's ideal, but I would like to know if you know of any other methods which would reduce consumption to less than 5mA without using any complicated circuits (other than unplugging the Uno)
Thank you!

Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.
See for instance, https://www.gammon.com.au/forum/?id=11497
With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.
The hardware/software support for low power cannot really be used before the board is design for that.
Cheers!

Thanks for your answer! Would this work by any chance?

Yes, that works fine. The suggested circuit basically turns off the Arduino board by disconnecting it from the battery. The button in the circuit will turn on the power of the board when pressed. This could be modified to an alarm signal from a RTC for time based start up.

The circuit (with or without RTC) could be mounted on a shield together with the battery pack to build a low-power unit.

Probably want to load your sketch with a Programmer so it runs immediately and does not wait out the bootloader starting up.  An advantage of using Power Down Deep Sleep is that an Interrupt wakes the processor and it can run immediately following the interrupt processor.  I made a remote control that way with an unmodified 8 MHz Promini and 3.7V, 1000mAH LiPo, would run about a month on a charge, and draw just a few mA when it went back to sleep after an RF transmission of the button press (433 MHz transmitter).  I think I just powered it via the VCC pin, bypassing the regulator.


text:
Arduino UNO USART problems
I need to send 6 bytes value from Arduino UNO to the actuator using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:
#define BAUD_PRESCALER 0x67
int buttonPin1 = 4;
int buttonState1 = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buttonPin1, INPUT_PULLUP);
}

unsigned char data1 = 0x00; // 0
unsigned char data2 = 0x14; // 20
unsigned char data3 = 0x01; // 1
unsigned char data4 = 0x01; // 1
unsigned char data5 = 0x00; // 0
unsigned char data6 = 0x00; // 0

void USART_Init(void) {
    /*Set baud rate */
    UBRR0 = BAUD_PRESCALER;
    UCSR0A = 0x00;
    /*Enable receiver and transmitter */
    UCSR0B = 0x08;
    /* Set frame format: 8data, 1stop bit */
    UCSR0C = 0x06;
}

void USART_Transmit( unsigned char data ) {
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    {
        ;
    }
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        USART_Init();
        USART_Transmit(data1);
        USART_Transmit(data2);
        USART_Transmit(data3);
        USART_Transmit(data4);
        USART_Transmit(data5);
        USART_Transmit(data6);
    }
}

http://www.zaber.com/wiki/Manuals/T-LA#Initial_Setup_and_Testing

sorry my bad...

It is not the main problem just a note,USART_init does not have to be called every time, it is enough if you call it in setup().

The comment /*Enable receiver and transmitter */ is incorrect: you are only enabling the transmitter.

The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.
Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.

I think that your BAUD rate setting is wrong. The UBRR0 register is a 16 bit wide one thus should be accessed in two 8 bit part, via UBRR0H and UBRR0L. You can check it in the datasheet.
If you further check the datasheet there is an example code in addition to the USART description which shows a correct way of initialization.

#define FOSC 1843200 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
void main( void )
{
    ...

    USART_Init(MYUBRR)
    ...
}

void USART_Init( unsigned int ubrr)
{
    /*Set baud rate */
    UBRR0H = (unsigned char)(ubrr>>8);
    UBRR0L = (unsigned char)ubrr;
    /* Enable receiver and transmitter */
    UCSR0B = (1<<RXEN0)|(1<<TXEN0);
    ...
}

As you can see the UBRR's value is calculated using the system clock speed FOSC, with MYUBRR macro which is an equation from the datasheet. Later this value is being set in two part upper 8 bit:
UBRR0H = (unsigned char)(ubrr>>8);

lower 8 bit:
UBRR0L = (unsigned char)ubrr;

(Your transmit function seems to be correct. And as I commented it is enough to call the USART init once in the setup().)

Splitting the write to UBRR0 may have been needed many years ago, but it is completely useless today: gcc knows very well how to write to a 16-bit I/O register.

Also, your formula (ok, Atmel's formula) for calculating MYUBRR is bad: it will systematically round down. You should instead use <util/setbaud.h> from avr-libc, which correctly rounds to the nearest integer. Or better yet, use Serial.begin().

I would recommend you to use the arduino's built in UART library. Try this code:
int buttonPin1 = 4;
int buttonState1 = 0;

unsigned char data1 = 0;
unsigned char data2 = 20;
unsigned char data3 = 1;
unsigned char data4 = 1;
unsigned char data5 = 0;
unsigned char data6 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);           // set up Serial library at 9600 bps
  while (!Serial);              // wait till UART initialized, for arduino UNO

  pinMode(buttonPin1, INPUT_PULLUP);
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        Serial.write(data1);
        Serial.write(data2);
        Serial.write(data3);
        Serial.write(data4);
        Serial.write(data5);
        Serial.write(data6);
    }
}

You should know that as long as the button is pressed data is being sent to the actuator. With that being said, with one button press you may have the commands sent 10 times. Thus, you have to deal with that in your code.

Thank you for your comment. I have tried to use your code but there was only a blink of yellow LED that indicates the existence of serial communication. The actuator did not move. One thing I am not clear, why I need to deal with the commands that may sent 10 times?

Since the code is executed in a loop void loop() and the if statement if (buttonState1 == LOW) is true, UART data is going to be sent as long as the button is pressed even though it is pressed for just 30ms or 40ms. The program scanning is much more faster than a couple of milliseconds.

The actuator should go to the absolute position 275 microsteps and stop there. Can you change the linear position of the actuator by hand and try again

I have changed the position of the actuator manually to original position and send the move absolute command once, but it does not move. I am wondering if the data sent is not in the right form.

To narrow down the problem did you try the Zaber Console it is free and open source. You can find a C lib as well in the same link.

I think you should try another baudrate as well e.g. 115200 . I have read the C  lib. The data structure is the same as above except that a reply from the actuator is expected.


text:
Sending serial bits in arduino
I am a newbie in Arduino and serial communication. I am working on a project that use Arduino to send data bits to an actuator using RS232 communication protocol. In order to control the actuator, an instruction consists of 6 bytes must be sent with 9600 baud, no hand shaking, 8N1 format.
Here are the instructions:
Byte 1 - Device, Byte 2 - Command, Byte 3 - Data(LSB), Byte 4 - Data, Byte 5 - Data, Byte 6 - Data(MSB)
For example to send 1, 20, 1, 1, 0, 0 (Move the actuator to absolute position of 257 microsteps)

This is my draft code. How can I send start and stop bit? I am confused on sending start and stop bit. The Serial.write() is sending binary data as a byte. Does it mean that I write Serial.write(20), the compiler will send the data in 00010100 binary format? I am quite frustrated with serial communication.

The Serial.write is working on a level of bytes and byte arrays, not bits. You don't need to implement the lower level stuff when using it. Anyway, looks like a major misunderstanding of things.

The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.
20 is actually sent as 0001010001
So your code will just be a series of Serial.write() calls for each byte you want to send.
Serial.write(1);
Serial.write(20);
Serial.write(1);
Serial.write(1);
Serial.write(0);
Serial.write(0);

Or as an array:
uint8_t data[6] = {1, 20, 1, 1, 0, 0};
Serial.write(data, 6);

Thanks for the comment, I will try using your suggestion :)

20 is sent as 0001010001: least significant bit first.

Yeah, I just blindly copied his example without checking.

Read the language reference: https://www.arduino.cc/en/Reference/Serial
..and for write(): https://www.arduino.cc/en/Serial/Write
....notice that it "writes" the bytes or buffers you define. You have already defined the baud rate and started the serial channel, then all you need to do is pass the characters or strings you want to send to the write function.
In your application it may be best to build a 6 character command string and send it all at once as a string. You must then remember that With "write" you are responsible for "writing" the cr and lf which is probably needed as a command terminator in your receiving device.
For your kind of application it may also be possible to use "println" which appends a cr/lf automatically for you. It depends on your protocol.

You certainly don't want to use println() with a binary protocol.

@EdgarBonet. If it' is a truly binary level serial protocol that's true. However I did qualify it, it's unusual to see simple protocols like this not be easily keyboard creatable strings.

You failed to read (or understand) the second paragraph of the original question.

Not at all, I assumed given the grade of question that the OP may not have described the problem completely.  I completely covered his question accurately in my first paragraph. I simply gave an option if that was suitable. I have altered the answer....hope it meets your niggle.


text:
Broadcast data to radius of at least 500 meters
I need to broadcast small amounts of data in a radius of about 500 meters to 2 Kms. in real time. Any compatible receiver in the range should be able to receive that data. Is there a suitable module for the same? I am considering HC-12 but don't think it can used for broadcasting data to all the surrounding receivers.

look into LoRa gateways, then use whatever MCU/software you want.

Maybe you can look into the LoPy Microcontroller, a MicroPython enabled controller, that has a 1km WiFi range. It uses the Espressif ESP32 chipset (with 802.1b/g/n 16mbps WiFi) and has Bluetooth (BLE & Classic) integrated into the board.
(Reference: https://www.pycom.io/product/lopy/)

You can use NRF2L01 2.4ghz rf tranceivers.They have a range of approx 1 km without antannae and 1.8 km with antannae.Also the ESP8266 wifi module normally has a range of 300m but can be used for the ranges you require with some big dish antannae.


text:
Is two modules using Serial Interface on one Arduino Uno possible?
I was wondering if I have both a Bluetooth HC-05 module and a GPS module (uBlox 7N) is it possible both for both to be using the serial interface?
I'm aware they cant be operating simultaneously with one another but if I using the RX TX pins for the GPS module, can I receive a location, store it in a variable then terminate the GPS serial usage and using software serial with 2 pins of my choice transmit data via the Bluetooth module which also requires the serial pins?

No, you can not do it on one serial interface. However you can use Software Serial library and "create" second serial interface.

Yes, you can use multiple SoftwareSerial ports, but you can listen only at one at a time. The easiest solution is a arduino mega 2560 board with 3 extra hardware serial ports.

You are right, that you need one Serial interface for each module. The Uno has only 1 hardware serial interface (hardware means, that the Arduinos hardware will do the communication work in the background and you can let it do other things in the meantime). But you can add more serial interfaces, on other pins, that work purely through software. For this the SoftwareSerial library is meant.
SoftwareSerial comes with some limitation, since the load of communication has to be done in software instead of hardware. For example it becomes unstable at high baudrates. Especially for the HC-05 you should not use baudrates of 115200 baud and higher. Also - since it uses pin change interrupts to work - you can only listen at one SoftwareSerial at any given time.
Since you only have 2 modules, it should be easily possible, to utilize SoftwareSerial and access both of them with the Uno. If you at some time want to use more serial modules, you can still change to a bigger board like the Mega.
Note: Be sure to disconnect the module from the hardware serial, before programming the Uno over the Serial interface (USB), or the programming will fail.


text:
GPS only works when I click Reset on Arduino or Reopen Serial Monitor
I cannot work this out!
My Ublox 7n GPS module will only print data in the serial monitor once when I either click reset on my Arduino Uno or reopen and close my Serial monitor.
So whenever I have the serial monitor open and click reset on my Arduino it quickly spits out all the data on it and then stops, same when I open the serial monitor after being closed.
Here is my code:
#include "TinyGPS++.h"
void displayInfo();
const unsigned long PUBLISH_PERIOD = 1000;
double latitude = 0, longitude = 0;
TinyGPSPlus gps;
unsigned long lastPublish = 0;

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

void loop()
{

    while (Serial.available() > 0) {

      if (gps.encode(Serial.read())) {
        displayInfo();
     }
    }
  delay(1000);
  Serial.println("new");
}

void displayInfo()
{
  if (millis() - lastPublish >= PUBLISH_PERIOD) {
    lastPublish = millis();
    char buf[128];
    delay(1000);

    if (gps.location.isValid()) {
      snprintf(buf, sizeof(buf), "%lf,%lf", gps.location.lat(), gps.location.lng());
      //  Serial.println(buf);
     latitude = gps.location.lat();
     longitude = gps.location.lng();
     Serial.println(gps.location.lat());
     Serial.println(gps.location.lng());
     Serial.println(latitude, 8);
     Serial.println(longitude, 8);
      }
  else {
    Serial.println("no location");
  }
}
}

I've attached an image of my serial monitor, the gps data came through when I closed and reopened it.

opening Serial Monitor resets Uno

ah well that solves minor part. Any idea why it is doing what can be seen?

gps.encode(Serial.read()) is always false later?

I think it has to do with the millis() part. the PPS is flickering on the ublox, I think the clock might be damaged or something. I dont have anything connected to the PPS leg on the GPS though.


text:
DHT11 Sensor : Stand-by or Shut down?
I have an ATmega328P monitoring room temperature and humidity. It is enough for me to monitor every 8 seconds. In these 8 seconds, I am putting my Atmega to sleep.
Now , I want to know : Does shutting down the DHT11 for these 8 seconds affect the performance of the sensor in any way or is it advisable to keep it running (stand by) for these 8 seconds ?
[Shutting down means connecting the Vcc of the sensor to GND by means of digitalWrite(Sensor_pin,LOW);]
Also , (The below question is applicable only if your answer to the above question is to keep it in Stand-by) :-
I want to modify the above project such that Temp & Humidity is measured as and when only an input button is pressed.
In this case too, should I keep the DHT11 running?
Is a running DHT11 sensor more accurate than a instantly powered on DHT11 ?
[And in case you are speculating , yeah,I want to save the 50 micro-amps Standby current of the sensor.(but of course without sacrificing accuracy of the sensor)]

Have you tried to do a practical test? Start the sensor, do some sample readings? And by the way, have you used a search engine and search for "wake up time"?

I searched google.com for "DHT11 wake up time" but got nothing relevant :(

I do switch off DS18B20 as you explain it, because they seem to overheat, if powered constantly. If I do switch off my DHT22 betwean readings, the (first) reading fails about 50% (wrong values, reading error), so I keep i powered.

I googled, "DHT11 wakeup time", found this: https://forum.arduino.cc/index.php?topic=58531.90

@MatsK As I said,  nothing "relevant"

i wouldn't think a room would change that much in 8 seconds, certainly not more than the DHT11's error margin, unless it's some environmental chamber or something; slow that sampling down man...

At times like this it is useful to refer to the datasheet.  You can, in that document, find this paragraph:

4. Power and Pin
DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do not send any instruction to the sensor in within one second in order to pass the unstable status. One capacitor valued 100nF can be added between VDD and GND for power filtering.

So you can see that if you power down the sensor completely you have to wait at least 1 second before you can do anything with it.
With it just in the low power mode it defaults to between readings you can immediately start reading as soon as your ATMega wakes up.
So you have to ask yourself: Does running the ATMega at full power for 1 second consume more or less power than running the DHT11 in low power mode for 8 seconds?
As a rough guestimate - if the ATMega is using 30mA (ballpark figure) for 1 second (that's 30mAs - milliamp-seconds), and the DHT11 uses 50uA for 8 seconds, then you have 0.05*8 = 0.4mAs.
That's 0.4mAs (sleeping) vs 30mAs (powered down). So I'd go for leaving it powered and avoid the one second delay at full power.
Another option that may save more power would be to:

Power off the DHT11
Sleep 8 seconds
Power on the DHT11
Sleep 1 second
Read DHT11
Go to 1

Of course, that means your loop then takes 9 seconds not 8. You could compensate by sleeping for multiple amounts to make 7 seconds:

Sleep 4 seconds
Sleep 2 seconds
Sleep 1 second
Power on the DHT11
Sleep 1 second
Read DHT11
Power off the DHT11
Go to 1

But of course that then makes your sleeping less efficient - so is it really worth it?

"Is a running DHT11 sensor more accurate than a instantly powered on DHT11?" I tried to mean,  is a DHT11 which is running all the time more accurate than instantly (which is being powered on, waited for a second,  taken reading and switched off) powered DHT11?

No, it's no more or less accurate. Because you've had to wait for a second anyway before taking a reading it's been "always on" for the past second anyway.


text:
Comunication between Android and Arduino
I am trying send data from an Arduino to an android device with bluetooth.
I want to send a date y and when it arrives, turn on a led, but when I send the data nothing happened.
This is my code for Arduino (I use the bluetooth module hc-05)

char entrada;
void setup()
{
pinMode(8,OUTPUT);
Serial.begin(9600);
digitalWrite(8,LOW);
}
void loop()
{
   if(Serial.available()>0)
{
 entrada=Serial.read();
 if(entrada=='1')
 {
    digitalWrite(8,LOW);
    Serial.println("1");
  }
 }

And in the side of android i have this codec with my handler and thread for inputstream and outputstream
public void run()
    {
        byte[] espera=new byte [256];
        int esperaalmacen;
        while (true) {
            try {
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera).sendToTarget();
            }catch (IOException e){}
        }

And in my activity main I have:
       @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
        }
    }

My modulo I have configured as slave.

have you tried establishing a master-slave setup using I2C?


text:
Why I cannot connect directly Arduino UNO and Xbee S2?
I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.
i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.
what i have to do?

If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.
Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.

thanks for the answering, so is there no way to connect PC-Arduino UNO-Xbee s2 module when arduino MCU is programmable?
or does arduino can properly programmed and active when i programmed xbee s2 module and arduino separately?

You could use an Xbee shield like this https://www.sparkfun.com/products/12847 (there are other variants), which includes a switch so that you can easily switch from Arduino-programming mode to X-CTU mode. A common option is to just use the SoftwareSerial library (I think it's automatically included in the Arduino IDE) and just use 2 other pins for communicating with the xbee, so that pins 0 and 1 are free for programming on the Arduino via USB. But with this method I think you'd still have to swap the wires back to the Rx and Tx pins (0 and 1) on the Arduino if you want X-CTU to see the xbee.


text:
PIR motion wake ESP8266 from deepsleep
I'm trying, what I thought would be simple, to wake a sleeping ESP8266 via motion detected by a PIR.
There are a lot of schematics around and they all seem to go about it more or less the same way, and the simplest form seems to be this:

Where RST is the RST pin of the ESP8266 and Trigger is the PIR's trigger line.
The problem I'm finding is that this is not working.
The PIR is working fine, and throws out almost 3v for 2 seconds when triggered and 0 when no motion is detected.
My ESP is being woken up when the PIR trigger is OVER, not when it STARTS. So if the PIR senses motion for a long time, the ESP will only wake up when the motion STOPS.
The PIR is one of these.
The ESP is currently a NodeMCU on breadboard, but the final product will be a Wemos D1 Mini.
What am I doing wrong here?

you measured only 1/2 of your circuit .... The PIR is working fine, and throws out almost 3v for 2 seconds when triggered ... how about measuring the RST line

The RST line has 3.3v as expected. When the PIR fires, the voltage on RST drops to zero, which I expect to wake the ESP. However, the ESP only wakes when the PIR stops firing and the voltage to RST goes back up to 3.3v. I don't get it.

it is simple, the esp8266 stays in reset mode as long as RST is active (low) .... it leaves reset mode and starts executing its program when RST becomes inactive (rising edge on RST)

What you need is an edge detector. As long as the PIR output is hight, the ESP stays in reset mode.
You can use a capacitor to do the trick, as shown in the following schematic.
You'll probably want to get rid of the pull-down resistor R1 since you're using an open-collector output.

If the voltage at the collector is the blue curve, then the resulting voltage at the output of the circuit will be similar to the yellow curve. (Note that this simulation used an ideal square wave as input, produced by a push-pull output from a CMOS chip, for example. An open-collector output will have slightly different characteristics, the high peak won't be as high.)

At the instant when the collector voltage drops to (almost) zero, the voltage across C1 will be 0V, so the output is close to 0V as well. Then the capacitor immediately starts to charge through R2, so the voltage on the reset pin rises exponentially.
To prevent a high voltage peak when the PIR turns off, a diode is used to discharge the capacitor more quickly. If the resistor at the collector is large enough, this might not be an issue at all.
The same principle is used in the Arduino UNO, for example, to reset the ATmega when DTR goes low.

Thanks. That is very useful. Based on your schematic and a few others I found, I have re-worked my wiring to this: http://groovy.globi.ca/img/20180722-3404caebc3bdc7f233726e6afe54ffea.png
This is working very well. The ESP is woken quickly, and by setting D3 LOW, is prevented from re-booting while running.
The problem I'm now facing is that the PIR output pin is showing a negative voltage. I want to connected it as an INPUT to the ESP so it can check the status, but the ESP goes crazy when connecting it. Any ideas?

If D3 goes from low to high when trigger is low, trigger will get pulled negative. (Because there was a negative charge on C1). The output impedance of most PIRs is greater than 1kΩ, so the voltage will go negative. You need a resistor on your base. If you do the edge detection after the transistor, you shouldn't have to worry about this. You can still use the AND configuration you have right now.

Hmm. I put another NPN between V++ and the edge detect with trigger to the base, but I'm still getting a negative voltage on the trigger. Where exactly do you think the resistor should go, and what value? Is the 1M resistor maybe too high in this circuit?

Use your initial circuit, the one you used in your question. Then add the circuit of my answer (without R1). Connect your RST output to my DTR input. Then add the second transistor between the emiter of the first transistor and ground (collector 2 to emitter 1, emitter 2 to ground, base 2 through a resistor to the GPIO pin of the ESP).

I tried adding your edge detector to my original circuit at RST, and it looks like this: http://groovy.globi.ca/img/20180723-d02a55da8edcc7ec95a59ce5c8a93f5b.png
However, when I plug D3 into the ESP, it never boots - just throws gibberish to the serial console and dies. Did I mis-interpret your instructions?

You forgot your pull-up resistor at the collector, and the base resistor of the second transistor. D3 is the boot select pin for the ESP8266. You're pulling it low through the transistor, use a different pin. Avoid D3, D4, and D8, as they all have special functions at boot time.

I appreciate your patience and apologize if I'm being stupid, but by adding the pull-up to the collector, I'm now reading a consistent 3v3 at RST. This is the current circuit (except that Q5 base is going to D1 now and not D3 as suggested): http://groovy.globi.ca/img/20180723-6931232cc901e6c1d521acb48828cad0.png. When the PIR fires, no change happens and the ESP is not triggered.

You didn't pull up the base of the lower transistor.


text:
How do I include a file that is not a .h, .c or .cpp file?
I am using the ADF7030 on the breakout board (not motherboard) and I am trying to interface it with an Arduino Uno. I want to load the transceivers configuration file onto the chip using SPI. To do this, I need to include the ".cfg" file but when I use the C style array (as in the datasheet - code below) it says that it can't find the file in the .ino sketch.
const unit8_t Radio_Memory_Configuration [ ] = {
     #include "Settings_ADF7030-1.cfg"
}
How could I include this file?

I guess the Arduino IDE preprocessor is making it difficult for you. As it copies files to a build directory it might miss your specific configuration file. Try changing the file suffix to .h just to test this.

From looking at the arduino-builder source only files with the following extensions are copied to the build directory: .ino .pde .h .c .hpp .hh .cpp .s
So you will need to use one of those extensions.


text:
ESP8266 as WiFi monitor
I'm about to buy two ESP8266 modules. I want them to use as an auto deauth device. The first module will monitor my WiFi router's packet transmission. If a certain device receive loads of packets from my router (which hogs my network) the second module will deauth that device or flood "forged" packets. There will be a threshold so a simple web browsing will not trigger the deauth process from the second module. Btw. My router doesn't support traffic shaping & QoS. Only a different kind of QoS (DHCP & IPP/TOS) which is useless because my ISP doesn't support it.

So to disable a device that hogs your connection, you start flooding the connection to that device? That doesn't really sound like the way to go.

You may try to flash openWRT on a router and/or make a second access point for guests that has max up/down.

@Paul It's an ADSL/WiFi router combo. It's a new-ish hardware but every custom firmware are not available for this device but the other version (without ADSL) is supported.

You're going to face significant challenges with this.
The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.
I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack.  The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).
So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.
Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.


text:
Comparing two char array
I modified a code which replies BAR when I send FOO. The problem is the if else statement always lands on else which prints Wrong command. I tried comparing it to string FOO(??) and also comparing it to char FOO with the same buffer size but no joy. This is the code:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "##########";
const char* password = "##########";

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}

You are comparing a char* to a char*. Array's are contiguous memory locations and the variable name for an array in this case command_1 and incomingPacket point to the first element in the array. Since they are two different array's, the location of the first element in command_1 is different than the location of the first element in incomingPacket so command_1 will never equal incomingPacket.
In order to check if the incoming packet equals "Foo" try
if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the strcmp() compares two null terminated character arrays and returns 0 if they are equal.
Just ensure that the incomingPacket is null terminated I have never worked with this library before.

> if (incomingPacket == command_1)

that statement is testing if pointer incomingPacket is pointing to the same address as pointer command_1.
to compare strings, you can either use a ready-canned function (if your compiler supports it), or to define your definition of "string equality" and execute it. most likely that requires comparing size first, and the individual characters in the string until a mismatch is found, or you have exhausted one of the strings.


text:
Reading/Writing salvaged EEPROM
Recently I stumbled myself on a fairly old blood sugar test strips canisters. Inside them, I found this what they called "Code Card" which inside, an EEPROM Microchip 93LC46B a 1K Microwire compatible serial EEPROM. I want to salvage them for my Arduino project. Is possible to read/write data to them? and how to determine the capacity? I only see 16 bit word size on the datasheet and 1K on the title.

Page 1 of the datasheet: The Microchip Technology Inc. 93XX46A/B/C devices are 1Kbit low-voltage serial Electrically Erasable PROMs (EEPROM).  - in what way is that vague?

Yes you can use it with Arduino. You just have to read the datasheet.

@Majenko Didn't notice that but thanks

BTW, MicroWire is almost like SPI, but CS is active high not active low.


text:
Seven segment display multiplexing
I have written a code that displays a number into a seven segment display without manually setting the Arduino pins HIGH/LOW for each number. Now, my problem is how can I display a number larger than 9? This is my code and it works for only 1 digit number: (The seven segment display truth table is inverted because I'm using common anode 7seg)
#define SEG_A 2
#define SEG_B 3
#define SEG_C 4
#define SEG_D 5
#define SEG_E 6
#define SEG_F 7
#define SEG_G 8
#define DEC_P 12

#define SET1 9 // [!][!][x]
#define SET2 10// [!][x][!]
#define SET3 11// [x][!][!]

struct segmentmap {
  uint8_t num;
  const int segment[7];
};

const struct segmentmap segments[] = {
  // n   A  B  C  D  E  F  G
  {0, {0, 0, 0, 0, 0, 0, 1}},
  {1, {1, 0, 0, 1, 1, 1, 1}},
  {2, {0, 0, 1, 0, 0, 1, 0}},
  {3, {0, 0, 0, 0, 1, 1, 0}},
  {4, {1, 0, 0, 1, 1, 0, 0}},
  {5, {0, 1, 0, 0, 1, 0, 0}},
  {6, {0, 1, 0, 0, 0, 0, 0}},
  {7, {0, 0, 0, 1, 1, 1, 1}},
  {8, {0, 0, 0, 0, 0, 0, 0}},
  {9, {0, 0, 0, 1, 1, 0, 0}}
};

void setup() {
  Serial.begin(9600);
  for (int x = 2; x <= 8; x++) {
    pinMode(x, OUTPUT);
    Serial.print("Segment pin: ");
    Serial.print(x);
    Serial.println(" is set to OUTPUT mode.");
    digitalWrite(x, HIGH);
  }
  pinMode(DEC_P, OUTPUT);
  pinMode(SET1, OUTPUT);
  pinMode(SET2, OUTPUT);
  pinMode(SET3, OUTPUT);
  digitalWrite(SET1, 1);
}
int x = 0;
void loop() {
  if (x > 9) {
    x = 0;
  }
  updateDisplay(x);
  delay(1000);
  x++;
}

void updateDisplay(int input) {
  for (int x = 0; x <= 9; x++) {
    //Serial.println(segments[x].num);
    if (segments[x].num == input) {
      Serial.println(segments[x].segment[0]);
      ////////////Simplify this part//////////////
      digitalWrite(SEG_A, segments[x].segment[0]);
      digitalWrite(SEG_B, segments[x].segment[1]);
      digitalWrite(SEG_C, segments[x].segment[2]);
      digitalWrite(SEG_D, segments[x].segment[3]);
      digitalWrite(SEG_E, segments[x].segment[4]);
      digitalWrite(SEG_F, segments[x].segment[5]);
      digitalWrite(SEG_G, segments[x].segment[6]);
      ////////////////////////////////////////////
      //Multiplex here?//
    }
  }
}

It looks like you are using a 3 digit common anode display.
If your code currently works, fixed to display something on digit 0, then you could get it working for all 3 digits by adding/updating the following:
// globals:
byte display_buffer[3] ;  // representation of the display which you can change in loop()
byte anode_map[3] = { 9, 10, 11 } ;  // anode pins

void loop() {
  if (millis() % 5 == 0 ) updateDisplay();  // every 5mS - better to use a timer
  if ( millis() % 1000 == 0) {  // every second
    if (x > 9) {
      x = 0;
    }
    display_buffer[0] = x ;  // just for testing
    display_buffer[1] = (x + 11) % 10 ;
    display_buffer[2] = (x + 12) % 10 ;
    x++;
  }
}

void updateDisplay() {
   // called every x Ms preferably with a timer
   // selects next item from display_buffer_ptr and displays it
   //
   static byte display_buffer_ptr ;
   display_buffer_ptr ++ ;
   if ( byte display_buffer_ptr > 2 ) display_buffer_ptr = 0 ;
   int input = display_buffer[display_buffer_ptr] ;
   for ( int i = 0 ; i < 3 ; i++ ) {
       digitalWrite( anode_map[i], ( i == display_buffer_ptr ) ) ;  set current anode HIGH, rest LOW
   }
   // rest of your code to display the value of input

}

This is not the most elegant solution but involves minimal changes to your code.
It is more usual to use an array of byte for the mapping digits to segments.
You may have to optimise the switching of the anodes to stop ghosting.

my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.
your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.


text:
How to Sort Elements of Array in Arduino Code?
/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.
lt[6]={35,15,80,2,40,110};

Have you tried man 3 qsort? - Arduino programming is nothing more than C/C++ so you can use almost everything available there. Know your Language!

Simplest, though not most efficient, is a bubble sort. https://en.wikipedia.org/wiki/Bubble_sort

Online version: qsort() manual from avr-libc.

@Kwasmich no i am new in this field, please help me.

I'm voting to close this question as off-topic because it's a programming question.

@EnricBlanco can i not ask any programming question?

Stack Overflow is a much better match for your question than this site.

@EnricBlanco but this site is much active in respond than stack overflow, so i tried this. So i request to open this topic for discussion as it is helpful for me. Thanks

@EdgarBonet , it really helped me. please upvote the question.

As mentioned in the comments, qsort is a good option:
// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
  // Need to cast the void * to int *
  int a = *((int *)cmp1);
  int b = *((int *)cmp2);
  // The comparison
  return a > b ? -1 : (a < b ? 1 : 0);
  // A simpler, probably faster way:
  //return b - a;
}

void setup() {
  // The array
  int lt[6] = {35, 15, 80, 2, 40, 110};
  // Number of items in the array
  int lt_length = sizeof(lt) / sizeof(lt[0]);
  // qsort - last parameter is a function pointer to the sort function
  qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
  // lt is now sorted
}

void loop()
{
}

@Johny Mopp it really helped me.