text:
Opening and closing a hatch with different switches
I'm new to the whole Arduino thing and I'm not much of a programmer myself so I need some help...
The goal is to have 4 buttons which a person who operates it gives out different outputs from the motor connected too a hatch. The relays are connected to a hatchmotor with limit switches at both closed and fully opened positions.
My idea is like this:

button1 = activates relay 1->opens the hatch,
button2 = activates relay 2->closes the hatch,
button3 = endless loop, opens and closes the hatch,
button4 = deactivated both relay 1 and 2, and stops the loop.

My code so far:
const byte knappstangd(4); //limit switch, closed position
const byte knappoppen(5); //limit switch, open position
const byte brytareoppnalucka(6); //momentary switch for opening hatch
const byte brytarestangalucka(7); //momentary switch for closing hatch
const byte startaloop(8); //momentary switch for starting the "loop"
const byte stoppaloop(9); //momentary switch for stopping the loop.

const byte relastanga = 2; //activates relay 1 which closes the hatch
const byte relaoppna = 12; //activates relay 2 which opens the hatch

void setup()
{
    pinMode (knappstangd,INPUT);
    pinMode (knappoppen,INPUT);
    pinMode (brytareoppnalucka,INPUT);
    pinMode (brytarestangalucka,INPUT);
    pinMode (startaloop,INPUT);
    pinMode (stoppaloop,INPUT);

    pinMode (relastanga, OUTPUT);
    pinMode (relaoppna, OUTPUT);
}

void loop()
{
    if(digitalRead(brytareoppnalucka)==HIGH){       //if momentary switch brytareoppnalucka = 1 do this:
        digitalWrite (relaoppna, HIGH);             //open hatch
    }

    if(digitalRead(brytarestangalucka)==HIGH) {     //if momentary switchå brytarestangaluckan = 1 do this:
        digitalWrite (relastanga, HIGH);            //close hatch
    }

    if(digitalRead(stoppaloop)==HIGH) {             //if momentary switch stoppaloop=1 do this:
        digitalWrite (relaoppna, LOW);              //turn off relay for opening
        digitalWrite (relastanga, LOW);             //turn off relay for closing

        if(digitalRead(startaloop)==HIGH) {         //if momentary switch startaloop=1 do this:
            digitalWrite(relastanga, HIGH);         //start with closing the hatch to set a zero point

            if(digitalRead(knappstangd)==HIGH) {    //if limit switch knappstangd=1 do this:
                digitalWrite (relastanga, LOW);     //turn off Relay for closing
                delay (200);                        //wait 0,2 seconds
                digitalWrite (relaoppna, HIGH);     //turn on relay for opening
            }
            if(digitalRead(knappoppen)==HIGH) {     //if limit switch knappoppen=1 do this:
                digitalWrite (relaoppna, LOW);      //turn off relay for opening
                delay (200);                        //wait 0,2 seconds
                digitalWrite (relastanga, HIGH);    //turn on relay for closing
            }
        }
    }
}

Just to be aligned between the description and the source code, could you add what is the label of button1, button2, button3 and button4 ? Is button1 equal knappoppen(5); or knappstangd(4); ?

Yeah the buttons equals the momentary switches.
Button 1 = brytareoppnalucka
button 2= brytarestangalucka
button 3= startaloop
button 4= stoppaloop
Sry for swedish involved in programming lol, makes sense in swedish

What is the problem? 2. The switch is active high? How about your pull-down circuit?

What i'm experiencing right now is that if i push button1, the relay1 for opening turns ON as intended but keeps being turned ON for some reason... All the other switches does not work at all... not even Button 3 which simply says turn both relay1 and relay 2 OFF.

If a switch is active it gives out HIGH input to the board. (Normally open).

I'm not sure, but I think, what you need is a 4th if statement that check if none of the buttons are pressed, and turns of all the relays. Or on turning on the "open-hatch" relay, you should add a while so it waits till the end-switch is triggered, so it can turn off the relay.

For the activity of "relay1" (relaoppna), you have defined a state to be HIGH when "button1" (brytareoppnalucka) goes to HIGH, but no condition to go back to LOW. Are you expected that the "button2" (brytarestangalucka) should do that simultaneously as rising "relay2" (relastanga) to 'HIGH` ?


text:
Voltage on analog pin arduino when arduino turned off
So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

internal logic can be also configured as high impedance (High Z) - did you consider that?

All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

simulate this circuit – Schematic created using CircuitLab
The internals of the ATMega chip can be visualised for this purpose as a small resistor:

simulate this circuit
If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

simulate this circuit
That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.
It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.

If you add a large value resistor between the analog pin an the analog voltage source, not enough current can flow to cause damage. You have to be careful that the resistor doesn't influence the reading. Another option is to have a lower value resistor, but add an external clamping diode that can handle a lot more current.

The resistor increases the output impedance of whatever you are reading the value from - and yes, if too high it can affect the accuracy of your reading. It does provide some protection though. A better diode will protect the internal diode, but it won't stop the problem of back-powering through the internal logic. The proper solution is to use a MOSFET to isolate the input when there is no power applied.

An example and explanation can be found here: http://electronics.stackexchange.com/questions/134157/jtag-circuit-to-prevent-back-powering

So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

yes and yes.

Every AVR datasheet I've read gives the absolute maximum input voltage to a pin as something like Vcc + 0.5V - which in this case would be 0.5V.

source: Stack Exchange

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

sort: votes


text:
How to interpret accelerometer data to get decimals from -255 to 255
I'm using gy-521 module and I'm wondering how can i get useful readings from it so that i could work with the data that I'm receiving.
I want for AcX and AcY variable values to be from -255 to 255.
How to make this work.
sample data that I'm getting right now
X = 16380 Y = -64
X = 8116 Y = 3520
X = 12564 Y = 8728
X = -12652 Y = 1296
X = -17732 Y = -2420
X = -14576 Y = -2264

;
#include<Wire.h>
const int MPU_addr=0x68;
int16_t AcX,AcY;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  AcX=Wire.read()<<8|Wire.read();
  AcY=Wire.read()<<8|Wire.read();

  Serial.print("X = "); Serial.print(AcX);
  Serial.print(" Y = "); Serial.println(AcY);

  delay(333);
}

And what are the values you are actually getting from it?

X = 16380 Y = -64
X = 8116 Y = 3520
X = 12564 Y = 8728
X = -12652 Y = 1296
X = -17732 Y = -2420
X = -14576 Y = -2264

Use this code:
AcX = map(AcX, -32768, 32767, -255, 255);
AcY = map(AcY, -32768, 32767, -255, 255);

Of course, you won't be able to store the resulting value in int8_t since its range is from -128 to 127.
Here you can read more about Arduino map() function.

Or just divide the values by 128 (the same as a right-shift by 7 bits).

That is correct. However, by using map() you can tweak the input/output ranges. The sensor maybe doesn't return values below some threshold and in that case using shift would result in lower resolution of the output.

could you give me an example

For example, if you notice the sensor never returns values below -25000 you can use AcX = map(AcX, -25000, 25000, -255, 255); to increase the output resolution. Of course, the maximum value that sensor returns, in that case must not be above +25000. If the maximum value is e.g. 26000 then you must use AcX = map(AcX, -26000, 26000, -255, 255);

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


text:
delete or free on object causes Arduino to hand or reboot
I've read a lot about dynamic allocation for strings or buffers, but that's not my case.
I plan to implement much blinkers types as classes, all inheriting from a base Action class.
I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :
Action** actions = new Action*[10];

In the code, I will do something like :
int i = GetFreeActionID();
actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

Then the loop will call a method of the object and it works fine.
When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :
if (actions[i]->Do() != 0)
{
  delete(actions[i]);
  actions[i] == 0;
}

Howerver, I see in the serial console that when it comes to the delete instruction, the Arduino just reboots itself ...
Tryed also free instead of delete with same result.
How could I safely free the object when it's not used anymore ?
It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.

Please post a Minimal, Complete, and Verifiable example. Action** actions = new Action*[10]; - you aren't declaring an array of 10 pointers, you are declaring an array of 10 pointers to pointers. Is this really what you want?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes. - I don't understand that at all.

i'd really like to understand, I felt I was declaring a pointer to an array of pointers, not an array of pointers to pointers, I thought an array of pointers to pointers would have been something like Action** actions[10];

Ah yes, you are probably right there. :)

  actions[i] == 0;

That statement has no useful effect. Perhaps you mean:
actions[i] = 0;

oh god, man, you saved my life! Sometimes I feel my eyes need glasses ... Such a mistake, it works perfectly now!


text:
What is the principle of scanner
I find a 2.4GHz scanner in this web . I want to do same thing in 433 Mhz with SI4463. But I fail to understand it's principle. Who can explain it ? Thanks.

This might help; http://www.silabs.com/Support%20Documents/TechnicalDocs/AN633.pdf

But I fail to understand it's principle. - what principle do you want explained exactly? I don't see what this is to do with Arduinos.

@NickGammon  I don't know the algorithm i.e how does it work.

@MikaelPatel  It's too hard for me ....

I find a 2.4GHz scanner in this web . I want to do same thing in 433
  Mhz with SI4463. But I fail to understand it's principle. Who can
  explain it ?

The scanner you found loops through the channels looking for activity. The channels are defined by the NRF24L01. And activity is received signal within the channel above threshold (RSSI). For this device this is a single bit.
Other devices define RSSI as the signal quality/level for the latest received package. This is the case for the SI4463.
Cheers!

I use http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html   to control SI4463, but the RSSI is zero although there is a interference at same frequency . Do you know how to do it ?

Please post your test program/code.

BW: The RSSI value from SI4463 is for the latest received package. Interference is not detected by the RSSI in this case.

Yes, so ,I don't know how to do the same thing. And I have add my code in my question. Thanks very much.

@MikaelPatel - What the 446x RSSI means depends on what mode it is operating in.  If the poster wants to measure things that are not compatible signals, they probably do not want to be operating in packet mode.

@MikaelPatel  I think you are right. But I can't find a suitable mode in RH_RF24.


text:
How to use this Arduino code to control multiple different LEDs?
I am making an Android-controlled LED system over Bluetooth but I need to use 4 LEDs. I have done Android app but I am not able to figure out this Arduino code. Can some please help me get this done?
char command;
String string;
boolean ledon = false;
#define led 5

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

void loop() {
  if (Serial.available() > 0) {
    string = "";
  }

  while(Serial.available() > 0) {
    command = ((byte)Serial.read());
    if(command == ':') {
      break;
    } else {
      string += command;
    }
    delay(1);
  }

  if(string == "TO") {
    ledOn();
    ledon = true;
  }

  if(string =="TF") {
    ledOff();
    ledon = false;
    Serial.println(string);
  }

  if ((string.toInt()>=0)&&(string.toInt()<=255)) {
    if (ledon==true) {
      analogWrite(led, string.toInt());
      Serial.println(string);
      delay(10);
    }
  }
}

void ledOn() {
  analogWrite(led, 255);
  delay(10);
}

void ledOff() {
  analogWrite(led, 0);
  delay(10);
}

what is the data format sent for android? what is the results expected?

you only define 1 led but want to control 4?

android application is sends code like TO & TF for on&off respectively the result i want is to switch 4 leds on and off by those commands which are sent by android app over bluetooth

yup i actualy got this code from a website em a total newbie to this so i have no idea

Its better if you use SoftwareSerial for Bluetooth, so the native serial port can be used to debugging. But in case you doesn't need them:
uint8_t led[4] = {5,6,7,8}; // pin for LED 1,2,3,4
char command1,command2;
String string;
  void setup()
  {
    Serial.begin(9600);
    for (int i=0; i<4; i++)
        pinMode(led[i], OUTPUT); //set all LED pin as OUTPUT
  }

  void loop()
  {
    if (Serial.available() > 1) //run if 1 bit or more data received
    {
    string = "";
        command1 = Serial.read();
        command2 = Serial.read();
        switchled(command1-'0',command2-'0');
    string = command1+command2;
    }
    delay(1);
  }
void switchled(char pinLED,char statusLED)
{
    if (statusLED == 0 || statusLED == 1)
    digitalWrite(led[pinLED-1],statusLED);
    else
    digitalWrite(led[pinLED-1],!digitalRead(led[pinLED-1]));

    Serial.print("LED ");
    Serial.print(pinLED);
    Serial.print(" = ");
    Serial.print(digitalRead(pinLED));
}

The code reads 2 byte of data, so if your phone sent "11" the 1st led will turned on, and "10" will turn the 1st led off. The first digit is the LED index (1/2/3/4) and the second digit is the LED state (0/1), other than that, the LED on selected index will be toggled;

the following error comes up when trying to compile ---string was not declared in this scope --- if (Serial.available() > 1) //run if 1 bit or more data received     {     string = ""; // ---string was not declared in this scope ---         command1 = Serial.read();

still unable to compile shows ";" expected before string but adding that gived another error please verify the code

updated answers

still compilation error please check it on the software then upload

There are a million reason of compilation error. I compiles successfully. Please keep in mind that I have no obligation to do this "app" of yours, I am just trying to help. Do some effort, this is not "please-make-me-a-code.com". I'm out of here.


text:
getHostByName always failing to find a valid ip
I'm using an arduino Uno and a CC3000 wifi shield. I installed Adafruit library in arduino to get access to Wifi network. I'm currently trying to run some samples that comes with the library. It successfully connects to Wifi network and returns

IP Addr: 192.168.137.101
Netmask: 255.255.255.0
Gateway: 192.168.137.10
DHCPsrv: 0.0.0.0
DNSserv: 8.8.8.8
localhost -> 172.217.22.46

Pinging 172.217.22.46...0 replies

But when it tries to connects to a remote service like "www.adafruit.com" or "www.google.com" it assigns ip to 0 which means the host ip unknown. My wifi-hotspot is capable of providing internet connection. Can anyone please tell me what can I do to access remote web site through Wifi from this configuration. Setup method of one of the sample codes that I tried is mentioned below.
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  displayDriverMode();
  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  }

  displayMACAddress();

  /* Optional: Get the SSID list (not available in 'tiny' mode) */
#ifndef CC3000_TINY_DRIVER
  listSSIDResults();
#endif

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  while (! displayConnectionDetails()) {
    delay(1000);
  }

#ifndef CC3000_TINY_DRIVER
  /* Try looking up www.adafruit.com */
  uint32_t ip = 0;
  Serial.print(F("www.adafruit.com -> "));
  while  (ip  ==  0)  {
    if  (!  cc3000.getHostByName("www.adafruit.com", &ip))  {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  uint8_t replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  if (replies)
    Serial.println(F("Ping successful!"));
#endif
  Serial.println(F("\n\nClosing the connection"));
  cc3000.disconnect();
}

You should display obtained DNS server address too. The domain names can't be resolved without valid DNS server setting.

@KIIV Sorry. I updated the question with DNS  and DHCP details.

My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.


text:
ESP8266 NodeMCU first WS2812 LED lights up green
I'm trying to power some WS2812 LEDs from my ESP8266 ESP-12E NodeMCU board (circuit here). I'm simply trying to use the NeoPixel Strandtest which works perfectly on my Arduino UNO with the same LED strip, but when I change the #define pin 6 to #define pin D4 (or 12 as GPIO) only the first LED lights up and it's green. I did throw in a 470 ohm resistor between data and DIN, but that didn't do anything different.
When I use one of the other pins, nothing seems to light up, even if I disconnect all pins and hit reset. Here is my wiring:

Don't mind the actual 3v -> 5v. It works fine with 3v. I have also tried powering it off externally. I have tried all other pins from D0 to D7 (I saw many people say "STAY AWAY FROM PIN D8"). Could my ESP8266 be dead on arrival?

How long is your strip? And have you read and understood the NeoPixel uberguide (https://learn.adafruit.com/adafruit-neopixel-uberguide/overview)?

@Paul 3 pixels long. NeoPixel has nothing to do with this, except I'm using their example code. It works fine on my Arduino UNO so it should work fine on this as well.

Could you hook up the 5V input from the LED strip to USB-POWER pin of the NodeMCU?

@Paul There is no 5v USB-POWER pin. VIN doesn't provide 5v. Even if I hook it up externally to 3.3v or 5v, the LED strip won't work.

Hmm, I have a NodeMCU board that has an 5V usb pin, don't get why they shouldn't break that out, since it's an useful pin.

But, it's either that the strip doesn't get enough power (or the voltage drops after each LED) or the ESP8266's timing being messed up (or some sort).

To debug the voltage, you can try powering with another 5V supply and connect both grounds. You could also try to power it with the Arduino, and control it with the ESP8266 (and combine grounds).

@Paul How come it that all examples I've found online (literally 10+) won't work? I can light up a regular LED simply setting it to HIGH though.

What if you power the strip from behind the first LED?

@Paul From behind the first LED? Meaning what?

I'll write up an answer with my options/thoughts, that'll be easier

@Paul If it's not an answer, don't bother writing an answer. If it's assumptions, don't bother writing it.

The WS2812 parts are very picky with respect to timing.  Any jitter at all will give unexpected results.  We're talking less than a millionth of a second off. This is why you have difficulties controlling WS2812 parts with OS based computers like a Raspberry Pi.  My guess is that a ESP8266 is too preoccupied with controlling the radio to be able to keep to the precise timing necessary to control WS2812 parts.

You should also be aware that the Arduino paradigm (I resist calling it an OS) has not been cleanly ported to every processor / target which claims to be Arduino compatible.  Last month I was having problems controlling simple things like GPIO state on an ARM based Arduino.

@st2000 How come it that everyone else has no issues then?

My suggestion, if nothing else here works, is to use a common / well-known Arduino (like a ProMini) to drive the WS2812 parts and control it from the ESP8266.  Both are small boards and shouldn't mess with the size of your project.  Sorry about so many comments instead of an Answer.  But I am guessing at your problem.  And putting a guess into a StackExchange Answer is looked down upon.

@st2000 I could control my other Arduino from the ESP8266, but that's honestly not going to happen.

@MortenMoulder, really?  Well then, long wires and under powered supplies are my next goto answers (guesses).  After that comes product variation.  Including parts (so do check, as already pointed out, if another board works) as well as software (try to get older or newer versions of the board). w.r.t. power, are you asking for more power from the ESP8266 than it can deliver to the strip?  If you are using a 5 volt supply, try bypassing the ESP8266 and deliver 5 volts to the strip directly from the power supply.  Depending on your strip length, your supply should be of good size (Amps).

@st2000 Power is not the issue. Leave that out of the equation :) My guess goes to faulty board. If none of the examples I have tried (10+ at the moment), my guess is that it's faulty. I see no other explanation. If people with the exact same board can get theirs to work, mine should work as well.

I'll add one more suggestion.  As this is almost the same problem I had when moving from an Uno to an ARM based Trinket.  Make sure your SDK is up to date.  I'm more familiar with how ARM folds into the Arduino SDK.  But I suspect the ESP8266 will also have custom files that have their own versions independent of the SDK to support the differences between it and a classic Arduino.

@st2000 So updating my Arduino IDE? It's set to auto update and it's the newest according to their website. Could the bootloader have something to do with it? I haven't touched that at all.

Let us continue this discussion in chat.

So here comes my solution: I was playing around with NeoPixelBus by Makuna and the examples. I noticed in one of his examples, it said:

// You can also use one of these for Esp8266,
// each having their own restrictions
//
// These two are the same as above as the DMA method is the default
// NOTE: These will ignore the PIN and use GPI03 pin
//NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);

So I tried outcommenting that line and used that instead, and then it worked! I've always used Neo800KbpsMethod whenever I saw NeoPixelBus being used, because that was what other people did. Notice it also said:

These will ignore the PIN and use GPI03 pin

That pin is the RX pin on my board. No other example I have seen, has used the RX pin on the board.
After 6+ hours of constant troubleshooting, I can finally power on my strip and control each LED!

The Adafruit library uses direct port manipulation. It doesn't totally surprise me that trying to run this on another chip doesn't work as expected. I did a small library that uses the SPI hardware for a simple implementation (no assembler). However that also only works on a single pin - the one that supports SPI output on the Atmega328P.

I believe the Adafruit libraries have defines for specific implementations on Arduino and the ESP8266. However, since the timing is so strict, it may just be a little off on your specific board (and just right with the other options enabled). Also mind that ESP8266 pin  numbering isn't the same as the Arduino numbering (and maybe even specific to your board). You may still want to consider using another type of (spi based) ledstrips in the future, since it's easier, less dependable/flimsy, more tweakable and much more cross platform.

Ok i got it working after banging my head for couple of days, i was using a Node MCU Board V3, the pin number on board were D1 D2 D3 D4 etc all other library when data was connected to D4 in code where we specify the pin number we use to write D4.
However for FASTLED codes tbe code you need to write is just 4 without the letter D and when i did the same it just worked like magic

Please read and understand the manual
You say it works on an Arduino, a big difference between the Uno and ESP8266 is the voltage (and voltage regulators).
Another difference is the chip/architecture itself.
So that leads to having to debug these two factors.
Debug the power/circuit/voltage
Please check if the 3V pin of your particular dev board can supply the current for the 3 LED's.
Alternatively you can try by using another 5V power supply, or the 5V from your USB or (Arduino, since that did work) to try and power the LED's.
Another problem may be that the voltage will slowly go down over the length of the strip. Your strip is small, though you also power it from 3V, increasing the effect. You can try to power it on multiple points, or from the middle.
Try using a logic level shifter to increase the logic output pin from 3V to 5V, it may not be sufficient to transmit the data. This usually isn't a problem, but you should exclude this possibility.
The guide also shows some peculiar things regarding the wiring. They say you should use a capacitor between the + and - lines. I don't see how that can fail, but you may as well try.
Also doublecheck the wiring, maybe some connector is a little loose. I've also had problems with LED strips that have been bent, the copper may come loose from the strip, or the strip may get teared a little.
You should also check with another piece of LED strip, just to be sure.
Debug the controller
It works on the Arduino, but not the ESP8266, and we have checked that it's not due to the voltages/power.
The NeoPixels have pretty strict timing, I would actually advise anyone to NOT use them. Since you can't write to the strip "pixel by pixel", you'll have to put the whole strip in memory, and then send it all at once.
Other SPI based LED strips can receive the pixels one by one, like streaming. So you can simply make a loop that sets a color and sends it (while slowly increasing color, to make an virtually infinite rainbow effect). The cool thing is that it even doesn't block interrupts from happening. (Neopixels disable interrupts, need 3 bytes per pixel, and can't do calculations between sending)
If you still want to use NeoPixels, there may be a timing issue. You can check at which clock speed you've set the ESP8266.
Also are you using ESP show with the right "is800KHz" option? espShow(pin, pixels, numBytes, is800KHz);
You may also try another ESP8266 from another manufacturer, to be sure that it's not the board. They may have used a crystal that isn't as accurate as it should be.

I am 1000000% sure the voltage is not the problem. When powering the strip from the ESP8266, but getting the data from my Arduino, it works perfectly. I did specify the 800 KHz when setting up the NeoPixelBus (using NeoPixelBus example, for instance). The problem is this: Everyone who has guides on how to set this up, does nothing but grab an example and change to the correct pin. I did that. I did exactly what they did. I have the exact same pinout as them, so I expect the boards are somewhat similar (same MHz clock, same board type, etc.).

From practice, when your expected results do not manifest .. isolate and go back to basics, test on a known working strip/board, test 3V/5V, read the available options .. as @MortenMoulder mentioned the trick was the  NeoPixelBus lib and the specific RX pin

Ok, I am using WS2812B with nodemcu and Fastled. Now all folks out there reading this need not worry about voltages if your led is not blinking at all. It was not working at D0, it worked for me when I changed to D1, I am not aware of issue though. Need to check that.
I did not use any other component and connected directly to nodemcu.
Below is the simple code for first led to blink.
#define FASTLED_ESP8266_RAW_PIN_ORDER
#include <FastLED.h>
// How many leds in your strip?
#define NUM_LEDS 3

// For led chips like WS2812, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define DATA_PIN D1
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(9600);
    // Uncomment/edit one of the following lines for your leds arrangement.
    // ## Clockless types ##
    FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
    Serial.println("Setup");
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  //digitalWrite(DATA_PIN, HIGH);
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

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


text:
GSM shield 2 - Fully erase memory buffer
I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.
What I'd like to do
My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem[1].

I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the sms.flush() function. This function is available from the GSM.h library, which is bundled with the Arduino IDE by default.

and here comes the first glitch: the flush()function reference page states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that flush() would only work for outgoing messages...
...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use flush() to delete received SMS.

So for me, flush() really works both for outgoing and received SMS. Am I right?
What I did
Here is how the program works:

The arduino receives a SMS and is asked to light a LED
It does as instructed
then sends a SMS back saying that the LED is ON.
The DeleteSMS function is triggered

Here is the code:
void DeleteSMS(){
    int MessageQtt = 0;
    Serial.print(F("["));
    do{
        sms.flush();
        MessageQtt++;
    } while (sms.available() > 0);
    Serial.print(MessageQtt);
    Serial.print(F(" message(s)"));
    Serial.println(F(" have been deleted]\n"));
}

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also any SMS received in the mean time.
But it doesn't work and I can't really find out why.
My devices

Arduino UNO
GSM Shield 2
local (France) provider SIM card

Thanks all in advance for your input...
(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

[^1]: From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the memory buffer, but I can't really retrieve my source on that one.

Well, for those who might find it easier to take a look at the whole code, I translated it in (broken) english here.

Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.
So, the bottom line: never try to use the shield without a good powering system.


text:
How to run 50 IR LEDs off an Arduino UNO?
Hi I have 50 camera devices I want to program. Luckily the camera devices have a param.xml file I can import. I have already loaded the param.xml file on each of the camera devices however, now I need to import the param.xml file.
The devices work on IR waves, Usually I would have to import the params on each individual device with a remote but I decided to try and create a neat project where I would attempt to program all of the devices at once using an Arduino.
I would like to buy 50 IR LEDs, make small booster circuits for each LED and then point each one too the receiving module on the camera devices. All the Signal wires would be connected to Arduino pin 3.
I am mostly concerned about all the signal wires connected to Arduino pin 3. is there perhaps some kind of circuit I can use on pin 3 to ensure that this project will work perhaps someone Knows of a better way or has some advice?
Any suggestions will be appreciated.
I am not worried about power because I will connect the IR LEDs + & - to an external Power supply with adjustable current and voltage.
Booster Circuit:
Link To IR Led Datasheet
Link To Transister Datasheet

simulate this circuit – Schematic created using CircuitLab
This is the code I am using with an Arduino Uno and I have tested it with the IR booster circuit and it does work.
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendNEC(0x1067E21D, 32); // Login
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 1
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 2
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 3
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 4
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 5
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 6
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
    }
    delay(5000); //5 second delay between each signal burst
}

Do you want to control all 50 of them at once?

If your Vcc is not an LED driver (constant-current source), you will likely want a current-limiting resistor of at least 200Ω. The datasheet you linked to shows a voltage drop of about 1.2V and a current draw of nominal 20mA
V/A=R => (5V - 1.2V) / 0.020mA =>190Ω

If you are using a separate power supply, make sure you connect the grounds.

Do they all need to receive the same commands? Since you're thinking of only using pin 3.

@Paul: Yes, however If I can get the Arduino Mega to send signals over 50 pins or at least 25. Then I reckon that would be a significant upgrade compared to my initial question because I will be able to send each camera device a different command or I'll be able to send each device the same command depending on what I want to do with the camera devices.

You should put a current-limiting resistor in series with each LED.
You could then try to drive all of those LEDs from a beefy transistor, like
a power MOSFET or a Darlington. Alternatively, you can use a small
transistor for each LED, and then drive all of them from a PNP transistor,
like this:

simulate this circuit – Schematic created using CircuitLab
This way, if you want to drive some of the LEDs independently, you can just
connect an Arduino pin to its R2.
Beware that the PNP reverses the logic: pin LOW turns the LEDs ON.

Re “drive all of those LEDs from a beefy transistor, like a power MOSFET or a Darlington”, using an inexpensive Arduino-compatible motor-driver board or shield would also work, although some of them might be challenged when trying to switch at IR data rates

@Edgar Bonet I'm just curious, would an Arduino Mega be able to drive each of my 50 IR LEDs individually, Since it has 50 pins?

@Jonas: Looking at the datasheet of the ATmega2560 (p. 356) it would seem it can source up to 800 mA (3 pin groups @ 200 mA per group and 2 groups @ 100 mA). You should check the mapping of the AVR pins to the Arduino pins and make sure you do not exceed any of the group limits. You should also probably use an external power supply, rather than USB, and check that the voltage regulator does not get too hot.


text:
How to make auto keyboard using arduino nano V3.0 ATmega 328P ?
I have an Arduino Nano v3.0 ATmega328p board. I want to make an auto keyboard that types in a string when its plugged in. I have googled and found that these chips doesn't support that feature unlike "pro micro". keyboard.h is not supported with this chips. So is there any alternative way to use it as a HID and emulate keyboard inputs using any other additional shield other than using the built in USB port. Im a noob in this field, please help. Thanks in advance.

You can emulate USB on the atmega328. Look at the VUSB project. You just need a few resistors, diodes, and a USB cable.

I found this link : http://www.practicalarduino.com/projects/virtual-usb-keyboard Is that what you've been looking for?

Thank you @Gerben If you could give me some useful links so that i can get the basic codes, that would help me :)

Just google "vusb" and "vusb keyboard". Maybe some of the Adafruit guides for their pro trinket which uses VUSB. I'm currently on my mobile so linking is kind of difficult.


text:
ard-reset-arduino resetting Leonardo/Micro via USB works on OSX, fails on Ubuntu
I'm trying to program a Leonardo (actually a Micro ATmega32U4) via the command line using USB.  Schematically, I'm doing ard-reset-arduino followed by a sleep 1 and an avrdude command.
This works reliably on my Mac (OSX 10.12.1, avrdude v6.3), but bombs out on Ubuntu (Ubuntu 5.2.1-22ubuntu2, avrdude v6.1) with the message:
.avrdude: butterfly_recv(): programmer is not responding

Update: I believe this is actually due to a failure to get the atmega32u4 into the bootloader.  See update at the bottom of this post...
Has anyone seen this?  Any suggestions for debugging strategies or things to try?
Details on the Mac:
Here is the command line with results under OS X:
$ ./ard-reset-arduino --verbose --caterina /dev/cu.usbmodem1411 && sleep 1 && /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -V -D -p atmega32u4 -C /Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -c avr109 -b 9600 -P /dev/cu.usbmodem1411 -U flash:w:./leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/cu.usbmodem1411
/dev/cu.usbmodem1411 has come back after reset

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.
Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "./leds_test.ino.leonardo.hex"
avrdude: writing flash (9146 bytes):

Writing | ################################################## | 100% 0.70s

avrdude: 9146 bytes of flash written
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)
avrdude done.  Thank you.

Details on Ubuntu:
Here is the command line with results under Ubuntu.  Except for the pathnames, all of the options are the same as under OSX:
$ /boot/ard-reset-arduino --verbose --caterina /dev/ttyACM0 && sleep 1 && /usr/share/arduino/hardware/tools/avr/../avrdude -V -D -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/../avrdude.conf -c avr109 -b 9600 -P /dev/ttyACM0 -U flash:w:/boot/leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/ttyACM0
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
/dev/ttyACM0 has come back after reset

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

Postscript
Just to make sure I hadn't borked the bootloader somehow, I moved the Leonardo/Micro back to the OSX and re-ran the reset / programming sequence under OSX.  It worked without error, so I conclude that the resident bootloader is intact.
Update
I believe the real problem is that under Ubuntu, ard-reset-arduino fails to put the Leonardo into the bootloader.
Here's why I believe this is the problem: the resident sketch makes the onboard LEDs blink.  On the Mac, running ard-reset-arduino makes the blinking stop for about 8 seconds.  On Ubuntu, the LEDs continue to blink without interruption after the ard-reset-arduino command returns.
Update 2
Here's an even simpler Python program that resets the Leonardo under OSX but not under Ubuntu.
#! /usr/bin/python
import sys
import serial

ser = serial.Serial(sys.argv[1], 1200)
ser.close()

I'm somewhat embarrassed as to the source of the problem.  It wasn't an OSX vs Ubuntu issue.
Rather, on the Ubuntu system, there was an another application that was holding the USB port open, so attempts to reset the Leonardo were failing.
Rather than delete this post out of shame, I'm leaving it here in case someone else stumbles across the same problem.


text:
Use of struct and sizeof in C for Arduino
I am a newbie in C and I can not understand the point of using a structure in C. Could someone explain to me what is the point of defining a structure in C programming?
For example, this code(written in C for Arduino)
struct books
{
  char name[30];
  char author[30];
  int ID;
} Mybook, Yourbook;

void setup()
{
  Serial.begin(9600);
  // put your setup code here, to run once:
  strcpy(Mybook.name, "Girl in the train");

  strcpy(Yourbook.name, "Gone");

  Serial.print("Name of the book is:");
  Serial.println(Mybook.name);
  Serial.println((long)&(Mybook.name));
  Serial.println((long)&(Mybook));
  Serial.println((long)&Mybook);
  Serial.println(sizeof(Mybook));

  Serial.print("Name of the book is:");
  Serial.println(Yourbook.name);
  Serial.println((long)&Yourbook);
  Serial.println(sizeof(Yourbook));
}

Would use the same amount of memory as defining
char Mybookname[30];
char Yourbookname[30];

And you should type the same amount of lines.
So what is the point?
I have another question:
Why I get 62 for the sizeof(Mybook)? I have not defined it anywhere. Is it set automatically?

It is all about reduction of complexity and abstraction. A book (a struct in your example) has a title, author and identity. Collecting these together instead of scattering them helps when the size of the program grows, and if it "lives" for a long time and needs updating. struct is easy, wait until you get to class :)

@Mikael Patel Thank you, I thought struct and class were the same!

C has no classes. In C++, struct and class are almost the same. The only difference is members being by default private in a class and public in a struct. A C++ struct with no methods (only data members) nor static members is very similar to a C struct.

With classes we approach programming from the point of view of operations on local data (objects). In your example above; the class Book could be used in a collection in a class Library. The Library would have member functions such as lookupBookBy(title/name/identity), borrowBook, returnBook(), etc.

I have not defined it anywhere. - yes you have, in your code.

Don't cross post

Consider the following:
void printBook(const books &theBook)
{
    Serial.println("Name of the book is: ");
    Serial.println(theBook.name);
    Serial.println("author is: ");
    Serial.println(theBook.author);
    Serial.println("ID is: ");
    Serial.println(theBook.ID);
}

void loop()
{
    printBook(MyBook);
    printBook(YourBook);
}

You should appreciate this avoids the code duplication you have in your
example.

Why I get 62 for the sizeof(Mybook)?

30 bytes for name[30] (each char is one byte)
30 bytes for author[30]
2 bytes for ID (the AVRs have 16-bit ints)

No padding between the members because this architecture has no
alignment constraints.

Using Arrays-of-Parts (AoP) to represent a single item or "record" means that record's information is scattered among the AoP. When you need to do more than storing and listing 'N' records, that can get cumbersome and error-prone (as in: you miss one of the AoP when writing one of your routines). It also limits how you can allocate memory for the set of records.
Using an Array-of-Structs (AoS) only requires you to manipulate the one struct as a unit. If you move a record, all of its parts go with it. If you delete it, all of its parts get deleted. When you need more space, you only need to re-declare one array instead each of the individual parts arrays.
And one step up from an AoS is a Linked List of Structs (LLoS). Each record will contains one or more pointers (links) to some other record(s). Sorting then requires nothing more than writing some record's address into this record's link, and you've established a precedence. LLoS really shine when the records get large; writing a couple of pointers is way faster than copying 100 or more bytes. Same with deleting a record (call it "me"): change my predecessor's link-to-me to instead link to my successor, and Bang, done! I'm out of the list, there's no hole left as there would be with AoS or AoP, and my memory can be de-allocated, or I can be linked onto a different list.
Bottom line, arrays can get cumbersome when the data-set is large and and the records are complex. Structs gather a whole record together and allow more flexible manipulation.


text:
ESP8266 Nodemcu create custom PWM with 1.25us resolution
I am trying to control some SMD LEDs WS2812B with the ESP8266-Nodemcu. I am using Arduino environment for coding. Actually I am trying to accomplish a PWM  that is precisely able to:

Go High for 850ns and then
Go Low for 400ns

According to the Spec this, this High Low change is considered as a bit with value 1.
I have tried to delay between the lows and highs, without an effort (delays only work for microseconds and above i suggest).
Do you have any idea how to accomplish that?

I believe you're using WS2812? Then you can use the NeoPixel library. You probably should not bother to try it yourself.

You could have better picked up an SPI based led strip. Since the ESP8266 has to do stuff in the background, it could affect the timing afaik. And the SPI ledstrips are easier to drive.

@Paul yes the libary could indeed be useful. I will try it later. Could you propose me a special model of SPI led stripes?

This could be relevant also: https://github.com/cnlohr/esp8266ws2812i2s, it 'hacks' the I2S bus for accurate timing.

For Arduino, the same I2S bus trick is used here: https://github.com/Makuna/NeoPixelBus/wiki/NeoPixelBus-object#neoesp8266dma800kbpsmethod

It would be really helpful if you could mention in your question what exactly the 'SMD LEDs' are, and what/why the timing requirement is for though. Are you doing actual PWM, or is this a protocol? If it's PWM, why so exact?

I've had luck with the APA120C led strips. There is an extensive review of them: https://cpldcpu.com/2014/08/27/apa102/ search the page for: "WS2812" to see the writeup on the difference between the LED strip types (and why it's so useful)

@Paul thanks sir, i will have a look at this later :)

According to §1.7 (Pulse-Width Modulation) of espressif.com's ESP8266 technical reference document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.”  That range is shown in other sections of that reference, and in other ESP8266 documents as well.  I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.
Depending on what your intent is, you might instead consider use of UART capabilities.  For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low.  [I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.]
The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired.  As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.
Edit 1: As noted in cranphin's comments, cnlohr's esp8266ws2812i2s github page provides code that uses the I²S subsystem and DMA to drive WS2812 LED units.  Using DMA (direct memory access, ie transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs.  Note, cnlohr's page links to a youtube video that illustrates and briefly explains the process.

Thanks for the broad information, this was very useful for me. The UART and I²C thing could be an interesting solution, i will try it at the weekend :)

I ahve tried the I2S thing and it worked! thx

authors: Георгий Змазнев


text:
What USB to UART chip provides highest data rates with Arduino boards?
Checking out online stores for a USB/TTL adapter, I came across a wide range of products, and I'm having a hard time selecting the one which would achieve the highest data rate. I was comparing datasheets of the chips I have seen so far, to understand which baud rates are supported:

FT232R (FTDI): 183 to 3M baud, including 250k, 500k and 1M, 128 RX / 256 TX FIFO
PL2303 (Prolific): 75 to 1.2M baud, not including 250k, 500k and 1M, 256 RX / 256 TX FIFO
CP2102 (Silicon Labs): 300 to 921600 baud, including 250k and 500k, 576 RX / 640 TX FIFO
CH340G (WCH): 50 to 2M baud, not including 250k, 500k and 1M, unknown FIFO size

As explained here, 500k, 1M and 2M are particularly important, because those are the highest baud rates supported with 16MHz crystals. Moreover, data transmission becomes CPU-limited above 500k, so real data rates are practically the same with all three baud rates.
Am I right to assume that in order to get the highest data rate, I essentially have to stay away from PL2303, and prefer FT232R adapters, the other two chips being in the middle? Or are there other factors that I didn't take into account which may affect my choice?

If you really want a high data rate then you should use an Arduino that supports USB natively so you can bypass the bridge entirely.

@IgnacioVazquez-Abrams, the 32u4 for example does support USB

@IgnacioVazquez-Abrams Obviously, the question makes no sense for boards with native USB support. If I were to use Atmega32u4, why would I be shopping for a UART adapter?

At higher data rates the quality of the connection between the UART bridge and the main MCU becomes a factor. I have had reliable communication between FT232 and a PIC32 at 3Mbaud with both chips on the same board and properly routed traces. With separate boards I struggle to get reliable communication at 2Mbaud with 1Mbaud being about the limit.

For high throughput UART isn't really the best technology. As mentioned before you really want to go for direct USB if at all possible. It's all about selecting the right chip to build your project around, not just plumping for the "default" option.

@Majenko With separate boards I struggle to get reliable communication at 2Mbaud - this is a very important point IMO, it means that CP2102 may be actually faster than CH340G in this case. Regarding your second comment, I agree that UART isn't the best for high throughput, but when you have a choice between increasing the baud rate and migrating the project to a board with native USB support, a good UART chip may save you a lot of time.

I guess that another parameter to consider is the amount of internal buffers in these devices. To reach higher throughput you end up having to optimize the Arduino HardwareSerial code (for higher baudrate) and find faster methods to do conversion (e.g. dtoa). These are some of the tricks I did in Cosa to reach >90% effective throughput for up to 2 Mbit. Please see forum for further details https://forum.arduino.cc/index.php?topic=150299.555

@MikaelPatel I have added FIFO sizes to my question. Do they have a big impact on the throughput in practice?

@DmitryGrigoryev Thanks for adding the FIFO size. It is actually important to understand how data flows. The USB signalling/protocol is not each character and it has its own "baudrate". Buffering allows bursts of packages and reduction of the signaling overhead (upstream), and helps even out bit-rate (downstream).

Here's my experience with the above chips over the last two years:
FT232R is the fastest, works well with any baudrates. UART adapters with it are sometimes more expensive than alternatives.
PL2303 is good if you don't plan to go faster than 115200. Additionally, it has the strongest 3.3V reference (available on some adapters as 3.3V output) which can be abused as a 3.3V 20mA power supply. Other chips will refuse to work if you draw more than 5mA from the 3.3V reference.
Prolific is currently fighting against clones by making their up-to-date drivers incompatible with non-original chips, so if your adapter won't work in Windows with code 10, take a look at this page.
CP2102 which looks great in theory didn't work well for me (in Windows 10, with driver v10.1.3). Bulk data transfers at 115200 were in some cases 4 times as slow compared to other chips.
CH340G has a sketchy-looking windows driver, but otherwise works quite well and is often the cheapest option available. Unfortunately, it lack the intermediate baud rates, and getting 2Mbps UART link to work may be hard sometimes. Arduino clones which have this chip on-board do work at 2Mbps without issues (the ones I have seen do, anyway).


text:
How do I run multiple vibration motors from an Arduino Mini with PWM?
I'm building a project for my Physical Computing class that involves 4 vibration motors for varied haptic feedback based on serial input via analogRead. I have each coming out of their own pin and assigned to conditionals.
I'm wondering:

how do i control the PWM of each individual motor?
assuming I need an external power source for the motors, do I need to have a diode and transistor in between each motor and the ground?

Thanks in advance - I'm still learning but definitely looking forward to taking Part II next semester!

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

You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check here about more information on AnalogWrite, and here about Arduino Mini
This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

simulate this circuit – Schematic created using CircuitLab

Why specifically use a zener diode as a flyback? Can't a regular diode (granted it can handle the voltage) do the trick? Is there a specific advantage of using a zener diode over a normal diode?

Sure regular diode will also works, I didn't mention anything about specifically using zener diode

Hi - thanks for the help. I'm pretty solid on the physical routing now, at this point, its more the code I'm worried about. I'm guessing I can use an elseif statement? So for example if I have irPin1 = analogread(irVal1) to set the analogRead for the IR sensor I'm using, and then:
'    if (irVal1 < 400){
digitalWrite(vibePin1 = HIGH);
}
else(){
digitalWrite(vibePin1 = LOW);
}'

From there, how would I distribute PWM values to each sensor? I'm assuming that I'd be creating a pwmVal variable to store something? AnalogWrite(pwmVal = 30) or something like that? Assuming it goes 0-255.

dhimaspw, while you don't mention diode or zener diode in the text, item D in the diagram is a zener, as denoted by bends in the cathode line.  You could edit and substitute a plain diode with a straight line for cathode.

@jwpat7 as you suggested, I've change the circuit. Hope this doesn't cause any misunderstanding.

@Nick if there are new question, in my opinion you should post another question or edit the original instead of asking in comment section.


text:
How to read RPS for fast rotation with status change method in Arduino?
I'm trying to calculate the coming RPS from rotary encoder. I am  trying to get it by checking the status with digitalRead. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help.
Following is the code.
float rps;

void setup() {
  Serial.begin(9600);
  DDRC &= ~_BV (1); // pinMode (A1, INPUT);
}

void loop() {
  static int lastReedState;
  static unsigned long lastTransition;
  int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
  // On a rising transition of the reed switch:
  if (reedState == LOW && lastReedState == HIGH) {
    // HIGH LOW measuring the low period
    // Compute time since last valid transition.
    unsigned long now = micros();
    unsigned long revolutionTime = now - lastTransition;
    // measuring the High period
    // Compute the RPS
    rps = 1.00 / (12.00*revolutionTime) *1000000.00;
    // 12 is rotary encoders resolution
    // Remember this transition.
    lastTransition = now;
  }
  // Remember last state.
  lastReedState = reedState;
  Serial.println(rps);
}

Just asking, what Arduino do you use? Why  not using interrupt?

I am using Arduino Uno. As the matter of fact I have to read 8 input. in that case interrupts become very complicated.

have you tried using multiple PulseIn()?

When I use PulseIn(), it will affect other process after a while. Therefore, I avoid using such function.

Your code is so slow because of Serial.println(rps);. You should at least embed this statement inside something like if (millis() - lastTimePrinted >= PRINT_PERIOD) { ... } and not try to print faster than your baud rate (960 bytes/s).

Use interrupts, and use commands sei() and cli() to turn on and off interrupts. While you do important things turn off the interrupts and when count RPS turn them on again.

Consider using code similar to that shown in answers to the following questions: Reading from a KY-040 rotary encoder with Digispark; and Read RC receiver channels using Interrupt instead of PulseIn; and Can external interrupts be OR'd together on the '328 (Uno)?.
The first answer illustrates a fast-operating state machine to handle quadrature-encoded signals, ie rotary-encoder inputs.
The second answer illustrates handling of multiple encoders via a single interrupt routine, using a pair of two pin-change-interrupt (PCI) pins per encoder.  The method assumes pins of a pair are in the same port.  Most Arduino IO pins are PCI capable; some are not; on some models of Arduinos, some PCI pins aren't brought out to headers, or aren't recognized as PCI by the IDE, as noted in the question Why PJ0 and PJ1 are not reporting as PCINT pins.
The third answer includes code from the first two, and also has a sketch that displays a table of PCI vectors and masks.  This table assists in planning pin layouts to reduce ISR overhead.  For example, if you have half a dozen encoders, you might attach three of them to six pins on one port (and one vector), and the other three to six pins on another port (and another vector).  Or you might put two encoders on each of three ports.  The latter method might run, on average, a little faster (eg a microsecond or so per ISR invocation).

For one channel I'd use Input Capture capability on Timer/Counter 1. Without debouncing it'll be pretty easy.
If you want to read 8 inputs simultaneously, you can use Pin Change interrupts and Timer/Counter 1 as a timebase. If you don't use Serial communication, you can use whole PORTD, otherwise you can use for example 4 channels on PORTC and 4 channels on PORTD. But again, debouncing will be little bit challenging.

I am wondering If it is possible to use more than one interrupt in either PORTC or PORTD . Because I did in that way and could not get proper result for more than one interrupt per either port.

@zalt For Pin Change Interrupts no, there is one Interrupt source for each Port. You have to figure out, which lines were changed. However there is an Arduino library PinChangeInt where you can register callback function for each input.

Implemented with a state machine, quadrature coding does not need debouncing.  Bounce can cause invalid states or extra states,  but they cancel out.

@jwpat7 Right, I've missed it's about rotary encoder(s) and his code looks like he's using something like reed switches.

Ok . So far done for one. I have another question. I make new question.

authors: ปวิชญา ทองบพิตร


text:
Timer for how long button is not pressed
I would like to timer for how long a button is not pressed. So actually if(buttonState == LOW 'for two seconds') than execute the code that comes after it. But the problem is while the user is still pressing the button the timer already starts.
Code:
int ledPin[] = {7,8,9,10};
int ledPin11 = 11;
long randNumber;
const int buttonPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 2000;

void setup() {
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT);
 randomSeed(analogRead(0));
 randNumber = random(1, 16);
 Serial.println(randNumber);
 for (int i = 0; i < 4; i++) {
   pinMode(ledPin[i], OUTPUT);
 }
  pinMode(buttonPin, INPUT);
 }

 void loop() {
  displayBinary(randNumber); //functie 'display binary'
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    if(buttonState == LOW){
    antwoord(buttonPushCounter,randNumber);
    delay(5000);
    displayBinary(randNumber);
  }
 }
 buttonState = digitalRead(buttonPin);
 if (buttonState != lastButtonState) { // als de button word ingedrukt krijgt buttonPushCounter + 1
 if (buttonState == HIGH) {
  buttonPushCounter++;
  Serial.print("Nummer hoe vaak is gedrukt");
  Serial.println(buttonPushCounter);
 } else {
  Serial.println("off");
}
delay(250);
 }
}

void antwoord(int teller, int antwoord) {
 if (teller == antwoord) {
  for (int i = 0; i < 4; i++) {
  pinMode(ledPin[i], LOW);
 }
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 digitalWrite(LED_BUILTIN, LOW);
 delay(250);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 } else if (teller > antwoord || teller < antwoord) {
   for (int i = 0; i < 4; i++) {
    pinMode(ledPin[i], LOW);
  }
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

void displayBinary(byte numToShow) //van byte naar decimaal
  {
   for (int i = 0; i < 4; i++) {
    if (bitRead(numToShow, i) == 1) {
    digitalWrite(ledPin[i], HIGH);
    } else {
      digitalWrite(ledPin[i], LOW);
    }
   }
  }

I would start a timer when the button changes state. Then you timeout if
the button is released and it hasn't changed state for too long:
void loop()
{
    static int lastButtonState;
    static unsigned long buttonChangeTime;
    int buttonState = digitalRead(buttonPin);
    unsigned long now = millis();

    // Record time when button changes state.
    if (buttonState != lastButtonState)
        buttonChangeTime = now;

    // Timeout if button is not pushed for too long.
    if (buttonState == LOW && now - buttonChangeTime >= interval)
        Serial.println("Timeout.");

    lastButtonState = buttonState;
}

Don't forget to update lastButtonState on each iteration.

Your question is not clear enough.
I hope I get what you want.
Do while loop about the pressing...
if (button == LOW)
     while(!digitalread(button)){};

Why the if? If it's true, the while won't continue, giving basically the same effect :)

the if here is just if he want to do something before, is just habit.


text:
Writing new functions into progmem after main program is burned
I've been experimenting with writing very basic operating system-like programs on the Arduino, and so far I have been running user-defined programs on a small virtual machine I wrote.  This has been an interesting experience, but the VM runs on an assembly-like language and not C.
I want to be able to do something more.  I would like to be able to write a core OS, and then install new programs, written in C.  The core OS would get user input for which program to run, and then jump to that program.
Now, I know that I can do this trivially by writing the OS along with all of the programs into a single sketch. The programs are then just functions, and the OS just calls those functions.  However, I want to do this with functions I've written after I've burned the main OS.
From what I can tell, this is just a bootloader with additional user functionality.  However, I don't think that's quite right for two reasons:
First, I keep hearing that you can't write to progmem at runtime.  But isn't that what a bootloader does?  Which is correct?
Second, once a user program ends, I should return to the OS.  As far as I understand it, on the ATMega, once the main function terminates it jumps into a no-operation function and that's that.  I'd need it to jump back to the bootloader and continue the bootloader's operation.  Is that even possible?

If this is what you want to do you have chosen the wrong MCU.  Find something that can run from RAM, even if a bit inefficiently - competing ARM Cortex MCUs typically can.  Also understand that this "C" code you speak of gets compiled to machine instructions before it runs - you can compile C to instructions for a virtual machine, too.

Yes, you're right, and I've got an M0 that I can play around with.  However, I am using the AVR for a few reasons.  First, I'm familiar with it.  Second, because it doesn't just automatically have facilities to run like this I have to create them all myself.  My goal with these projects is to learn HOW those facilities are developed, not to get anything useful out of them.  So I chose a limited chip and made my own workarounds so that I understand how the more advanced chips do it all natively.

Your workaround might be an interesting puzzle, but it's not really how more capable chips would do it at all, but rather a workaround for the anachronistic limitations of the avr.

Seems you can fool the protection

@ChrisStratton: yes, you're right.  But doing it on my own means I get to make my own file system, loader style thing etc.  However, I'm actually probably going to just avoid it all and use a Cortex now that I know they CAN execute from RAM.  I guess it pays to do your homework

@Gerben nothing is being "fooled" but only delegated.  Delegating flash writing to a bit of code stored in a place where that is permissible is an old technique, for example on some MCU's you need a stub running from RAM to actually commit the flash writes.  In that case it's merely delegating from one part of flash to another.

First, I keep hearing that you can't write to progmem at runtime. But
  isn't that what a bootloader does?

Indeed. My understanding is that non-bootloader code cannot write to
the Flash, except on the smallest AVRs. You may need to check the
datasheet of your target MCU.

Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library
you provide. Just implement void exit(int status) in that library and
it will automatically override the version from avr-libc.

Yes, a quick datasheet dive reveals the following:  There are three sections in flash.  Boot is a special section where code running can actively modify progmem.  No-Read-While-Write is a section that does not allow for code to run while it is being updated (the CPU is halted).  Read-While-Write does allow for code to run while it is being updated, BUT the code that runs can only run from the NRWW section.  So it looks like I can write the OS to have an "installer" in BOOT, kernelspace in NRWW, and userspace in RWW.


text:
How to run a timer every 12 hours (exceeding the max size of int) without an RTC?
I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.
I've tried using the SimpleTimer library but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

On the page you linked it takes a long as an argument, not an int: int setInterval(long d, timer_callback f).

@NickGammon has it; there is no such limitation on the interval argument to setInterval() as "it takes milliseconds as an int". It takes a signed long, though it treats it internally as unsigned long, thus the max interval is over 49 days. Mark's answer will work, too, but is not actually necessary.

I better make it an actual answer then. :)

Set the timer for every hour, which is within the limit. In your action, keep a static int, initialized to zero, which you increment each time. When it ==12, do the thing you want to do and reset your int back to zero.

dang that's simple and smart

I'm running into an issue because it takes milliseconds as an int ...

No it doesn't. Look at the function prototype:

int setInterval(long d, timer_callback f);

Call function f every d milliseconds. The callback function must be declared as void f().

The interval d is a long. The int you see is the return value from the function, not the interval.

You have 2 other options to the setInterval() function:

delay() (blocking)
millis() (non-blocking)

Both of these functions deal with an unsigned long which has 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums (and considering that both are in milliseconds), this will last for 49 days and 17 hours.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
12 hours = 12 * 60 * 60 * 1000 = 43,200,000
delay(x) will delay for x number of milliseconds.  The delay function is blocking, meaning that while it is running/delaying you can't do any other task. The code would be:
delay(43200000);

millis() on the other hand is non-blocking and returns the number of milliseconds since power-up.  This can be implemented with the following code:
#define TWELVE_HRS 43200000UL
unsigned long startTime;

setup()
{
  startTime = millis();
}

loop()
{
  if (millis() - startTime > TWELVE_HRS)
  {
    // Put your code that runs every 12 hours here

    startTime = millis();
  }
}


text:
Arduino Due: ADC gain adjustment problem
I want to increase gain of the ADC channel. To achieve this I'm using adc_set_channel_input_gain function from adc.h. Here is the entire sketch:
const byte aPin = A6;

void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);
  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}

void loop() {
  int analog = analogRead(aPin);
  Serial.println(analog);
  delay(500);
}

The problem is that output values are not depending on the gain value.

The function adc_set_channel_input_gain() is not compliant with the basic analog input library which use only analogReadResolution() and analogRead(). Please read more about adc_init(ADC... for the "sam3x".

@J.Piquard, thank you for help, where can I find documentation?

Take a look to that Guide: "Quickstart guide for SAM ADC driver".

Well, the solution was very simple. We just need to call adc_enable_anch() before changing gain or offset of the ADC. I improved my setup and the sketch works as expected now:
void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_enable_anch(ADC);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);

  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}


text:
De-Auth "attacks" using Arduino?
I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3  d).
If you need me to clarify anything, please just ask.
Thanks in advance!

you'll need version 2.0.0 (or earlier?) version of the arduino esp8266 stuff if  you want to compile something that can do this

This seems to be a question about the ESP8266 and not about an Arduino.

If you can transmit raw 802.11, take a look at the code for aircrack-ng, specifically aireplay-ng.c - this software is known to work on arm boards.

Check this GitHub repo, could be what you are looking for: https://github.com/spacehuhn/esp8266_deauther


text:
How can I stop my Servo rotating?
I have a continuous servo motor connected to my Arduino UNO. I want it to react to the Hexadecimal code received by an Infrared remote. I want the motor to rotate once in one direction and then rotate once in the reverse direction and then stop until triggered by the remote again. At the moment, the remote will cause the the motor to rotate once in one way but then it rotates continuously in the reverse direction. Any help would be much appreciated!
#include "IRremote.h"
#include <Servo.h>

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

Servo servoMain;
IRrecv irrecv(receiver);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  servoMain.attach(10);
}

void loop()
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}

void translateIR() // takes action based on IR code received

// describing Remote IR codes
{

  switch (results.value)

  {

    case 551520375: servoMain.write(180); delay(1000); servoMain.write(0);     delay(1000); break;
    default: break;

  }

  delay(500); // Do not get immediate repeat

} //END translateIR

You never tell it to stop. I assume that writing op degrees would stop it.

Have you checked out linked and related questions?  Seems like this question may duplicate some of them.

http://arduino.stackexchange.com/questions/4076/what-is-commonly-done-to-stop-a-servo-after-reaching-desired-position

Unlike a normal servo motor where the argument of the Arduino's servo.write(angle) method represents a position, a continuous servo motor uses the argument for speed and direction.  Most continuous servo motors interpret stop to be approximately 90 degrees.  Full, say, reverse as 0 degrees.  And full, say, forward as 180 degrees.  As stated in the above link:

On a continuous rotation servo, this will set the speed of the servo
  (with 0 being full-speed in one direction, 180 being full speed in the
  other, and a value near 90 being no movement).

Also of interest, most continuous servo motors have an adjustment to set the "90 degree position" (full stop).  That is to say, servo motor control signals are analog, not digital!  It follows that the processor's interpretation of the "90 degree position" may not be the same as the servos' interpretation of the "90 degree position".  Hence the ability to adjust the servos' interpretation.
This picture from the parallax servo tutorials web site shows how this is done:

Thanks a lot for your help. I wasn't aware about the calibration and I got it working with some minor adjustments to the code as well.

I am posting that may help others in future. I have MG996R Servo Motors, this motor when I opened and inside I didn't find LOCK at main wheel and I assume its 360 degree.
I have similar problem that while testing Robotic Arm, my motor was loosing position and it was rotating 360 degree. I tried all sort of remedies but didn't find the solution.
MY SOLUTION: Connect your Servo with external power 5v supply, even connecting 5V to arduino board with round pin does not solve. once I connected with external power with 5V power my issue was solved and motors were retaining position


text:
MAC address arduino
The MAC address is hardwired onto the NIC card when a device is manufactured. How is it that, we get to set a 48 bit MAC address of our choice while programming the arduino ?

It may be factory set to a default value, but that doesn't mean you can't override it.

Arduino's have neither NICs nor MACs. Can you elaborate on where/how you're setting a MAC while programming your Arduino?

Arduinos don't have an Ethernet interface by default, so you have to add one; often this includes an EPROM e.g. http://www.microchip.com/design-centers/memory/serial-eeprom/getting-started/with-mac-address-chips

MAC address is not hardwired in the modern network interface cards; it is set during programming of the configuration of the card, which is loaded on the card's start/configuration.
Modern NICs usually have option for user to set custom MAC address.
If you talk about shield device based on network chip like W5100 - there's no initial configuration within this network card for Arduino; thus by "programming the arduino" you set this initial configuration of the "card". You act like a manufacturer of the NIC.

Your initial premise is incorrect. The MAC address is NOT "hardwired".  In many cases it is held in a very small non-volatile memory chip. But when the Ethernet driver is initialized you can feed it whatever MAC address you want.  For most people they just accept "defaulting" it to the address programmed into the tiny memory.
Remember that the MAC address must be unique. At least within your LAN.  If you start diddling the MAC addresses and you end up with a duplicate, at best you will kill connectivity for your node plus the other node with the same MAC address. Not a good thing to do. That is why people generally just accept the manufacturer's MAC address which is designed to be unique.


text:
How to I press a button once to display text and again to remove it?
My code is displaying voltage and I want to have a button that when pressed it displays a text and when I pressed it again it would turn off the text. I put the word "YES" just for a test
float vPow = 4.7;
float r1 = 1000000;
float r2 = 100000;
const int buttonPin = 8;
int buttonState = 0;
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
  Serial.begin(100);
}

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    lcd.setCursor(0,1); lcd.print("YES");
  } else {
    lcd.setCursor(0,1); lcd.print("");
  }
}

What is wrong with your current code? Also Serial.begin(100) is not right. You should put specified baudrates (i.e 9600/115200).

replace lcd.print ("")  with lcd.print("   ") (3 spaces) to force deleting "YES" on LCD screen

You can try to use a variable which is used to save the last condition. (whether it displaying or removing in the last button-press event)
bool state=false;
bool pressed = false;

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);

  pressed = false;
  while (digitalRead(buttonPin)) pressed = true; //wait the button to unpressed

  if (pressed)
    {
    state=!state;
    if (state) {lcd.setCursor(0,1); lcd.print("YES");}else
               {lcd.setCursor(0,1); lcd.print("   ");} //3 spaces. To erase 3 characters ("YES")
    }
}

You need to somehow debounce the button. Using a long delay in the loop
(your delay(100)) can do the trick, but it's probably not the best
way, as it will slow down anything that you may later add to your
program.
Better would be to write your own debounce function, or to use one of
the libraries that already implement that. For example, with
Bounce2, you would write
something like:
#include <Bounce2.h>

const int buttonPin = 8;
Bounce button;       // debounced button
bool textDisplayed;  // whether the text is displayed or not

void setup()
{
    button.attach(buttonPin, INPUT);

    // etc...
}

void loop()
{
    // Read and display the analog value, then...

    // Update the state of the debounced button.
    button.update();

    // Toggle display on rising edges of the button.
    if (button.rose()) {
        lcd.setCursor(0,1);
        if (textDisplayed) {
            lcd.print("   ");
            textDisplayed = false;
        } else {
            lcd.print("YES");
            textDisplayed = true;
        }
    }
}


text:
Problem with combination of Bluetooth and RF 434MHz with Arduino Mega
I want to receive text from Bluetooth from an android phone to Arduino Mega. Then I want to send that text to other Arduino UNO through RF 434MHz.
Here is my code for Transmitter.
#include <VirtualWire.h>
void setup()
{
  Serial.begin(9600);
  vw_setup(2000);
}

void loop()
{
  String voice;
  digitalWrite(8,HIGH);
  while (Serial.available())
  {                 //Check if there is an available byte to read
    delay(10); //Delay added to make thing stable
    char c = Serial.read(); //Conduct a serial read
    if (c == '#') {break;} //Exit the loop when the # is detected after the word
    voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0)
  {
    Serial.println(voice);
  }
  send(voice);
  delay(1000);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

after compiling, I am getting an error as

exit status 1
  cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

Please anyone tell me a way for solving this.
Problem is at transmitter part only. So I posted only about it.

[This should be a comment, but its too long]

•exit status 1 invalid conversion from 'const char*' to 'char*'
  [-fpermissive]

This means that the function you are calling wants a char* as a parameter, but you are passing it a char* that can't be modified.  The chances are that the send function doesn't modify the value in the parameter, so you might be OK just casting it, but you might get a runtime error if send does modify the value (a segmentation fault most likely, or just an ugly crash).  If you do you will need to allocate a temporary buffer that is big enough (str.length() + 1) and then copy it into that buffer and pass that to send.
So, try this first:
send((char*)voice.c_str());

If that fails then try this:
char* tempBuffer = malloc(sizeof(char) * (voice.length() + 1));
if (tempBuffer)
{
    strncpy(tempBuffer, voice.c_str(), (voice.length() + 1));
    send(tempBuffer);
    free(tempBuffer);
    tempBuffer = 0;
}

Of course if the data is always a fixed length then you can allocate an array on the stack instead of mallocing a buffer onto the heap.

thanking you. It worked very well the first one  send((char*)voice.c_str());    But after that I got another error in transmission. Once I send a string of length 15 characters then after that if I send 16 or more than 15 characters string , it is receiving only up to 15 character in same way the string length is getting fixed and unable to send more length string than previous one.In such a way the length of string receiving is getting reduced. Can you suggest me any solution for this problem?

exit status 1 cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

The compiler is telling you about the issue. You can access the String as a character vector (C string) with the member function c_str(), e.g. send(voice.c_str());
You might need to check that it is not too long for the payload in the VirtualWire library.
Cheers!

I had done what you said then it returned with following error > - exit status 1 invalid conversion from 'const char*' to 'char*' [-fpermissive]


text:
Erratic behavior from 'randomly' generated values in array
Currently working on a data collection algorithm on the Arduino MEGA (ATMega1280) and I've run into a problem with some of the code I've written. I feel my problems may be stemming from the way in which I'm storing the sample points I've generated in arrays ats1 and ats2 or in the ways that I'm generating said sample points in generate_tspairs. Any insight would be appreciated.
I've defined a struct in an external file structs.h

struct tspair{
  int t;
  int s;
};

I have a function defined in generate_tspairs.h
    void generate_tspairs(tspair ats1[], tspair ats2[], int N, int reps1, int reps2, int reps3){

        int alpha = log(N)/log(2); //equivalent to log2(N)

        for(int j =  0 ; j < reps1 ; j++){
            double randomDecimal = (double) random(1000)/1000;
            int r = (int) pow(2,alpha-1)*randomDecimal + 1;
            int s = 2*r - 1; //s is a random odd integer on the interval [1,N-1]

                for(int n = 0 ; n < reps2 ; n++){
                    double randomDecimal = (double) random(1000)/1000;
                    int t =  (int) N*randomDecimal;
                    tspair temp = {t,s};
                    ats1[(j*reps2)+n] = temp;
                }

                for(int n = 0 ; n < reps3 ; n++){
                    double randomDecimal = (double) random(1000)/1000;
                    int r = (int) pow(2,alpha-1)*randomDecimal + 1;
                    int s = 2*r - 1; //s is a random odd integer on the interval [1,N-1]

                    randomDecimal = (double) random(1000)/1000;
                    int t =  (int) N*randomDecimal;
                    tspair temp = {0,s};
                    ats2[(j*reps3)+n] = temp;
                }
        }
    return;
    }

After initializing and setting my two arrays of tspair structs, I am printing the values of the first array ats1 using the following in driver.ino
  int reps1 = 3;
  int reps2 = 5;
  int reps3 = 5;

  tspair ats1[reps1*reps2];
  tspair ats2[reps1*reps3];

  generate_tspairs(ats1, ats2, N, reps1, reps2, reps3);

  for(int i = 0 ; i < reps1*reps2 ; i++){
    Serial.print("t: ");
    Serial.print(ats1[i].t);
    Serial.print(" s: ");
    Serial.println(ats1[i].s);
  }

However, oftentimes I will receive the exact same values across multiple runs of generate_tspairs or when printing the values it will not stop at the end of my ats1 but rather it will continue to print the same line ad infinitum. E.g.
t: 815 s: 523
t: 975 s: 523
t: 244 s: 523
t: 8689 s: -26051
t: 31001 s: 29184
t: -25856 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
...
...
...
t: -2057 s: 6939

What are the types and values of reps1 and reps2?

And why are you using  n <= reps2 instead of n < reps2? If it's intentional it should be noted in comment why.

Where/what are the definitions of the ats arrays, and specifically, are they large enough that you haven't written beyond the bounds of either? What are reps1 and reps2, and the significance of their product, reps1*reps2, which you've used as the limit of the printing loop counter?

@JRobert I neglected to include that information originally, my apologies. Edited the driver.ino section of the question to include that

@KIIV That was a typo on my part, it is < in the code I ran.

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