body:
I have an OLED with this 7 pin pinout:

[![My OLED][1]][1]

I want to use an existing code i found that makes use of U8Glib.
But in the example, use uses 4 pins to control the OLED via I2C.
This is the pinout he uses:

[![Pinout][2]][2]

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

EDIT: Here is also a picture of the back of the OLED PCB that mentions how to use IIC but i do not understand it!
[![back of pcb][3]][3]

  [1]: https://i.stack.imgur.com/b2Uwo.jpg
  [2]: https://i.stack.imgur.com/p9ZW2.png
  [3]: https://i.stack.imgur.com/AVgmd.jpg

title: Running a 7 pin OLED with 4 pins (I2C)

Answers: 4

body:
That is a SPI interface. Often the CS is missing, but you seem to have that pin. I suggest to start with the software PCI mode of the U8Glib.

This is the best explanation that I can find: [Github: SSD1306 based OLED connected to Arduino][1]

Would you consider using the newer [U8g2 library][2] ?
It is easier to use with Arduino boards that have more memory. But it has also the same mode for low memory usage, just like the U8Glib.

  [1]: https://github.com/jandelgado/arduino/wiki/SSD1306-based-OLED-connected-to-Arduino
  [2]: https://github.com/olikraus/u8g2

body:
> Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

i'm sure somewhere there is an i2c->spi bridge. if not, you can always code your arduino to behave like one.

short of that, you can simply code to control the board via spi.

body:
[This page][1] has the answer to your questions. For reference:

> Setting up SPI/I2C Connection with GMS096A OLED Module
>
> Being a new entry to the market, only limited resources are available
> on this small piece of miracle (GMS096A). I2C/SPI configuration always
> demands helpful resources as in any case. For the SPI setup, the
> module comes in 4 wire SPI configuration by default and to make it
> work with the arduinos you can use these libraries from Adafruit.
>
> For the I2C setup it demands a little bit of work on the module.
> Actually it was one of our customers who shared these simple
> configuration steps with us, start with resoldering the resistor from
> position R3 to R1 and then short the R8 resistor with some solder tin
> (0 Ohm resistor). The R6 and R7 pullup resistors are already soldered,
> nothing to do there. Once done, the module is ready for I2C
> communication! The CS Pin is not necessarily needed, so just connect
> it to GND. The DC Pin selects the address. For standard address wire
> it to GND. The RES-pin needs a low pulse at startup and high voltage
> during operation (as in SPI mode), a 100nF capacitor to GND and a 10k
> res to VCC would be ideal!

Your module might differ sightly. But you should be able to figure it out from there. The pulse on the RES-pin needed at startup took me a while to figure out!

  [1]: http://www.rhydolabz.com/displays-c-88/096-oled-display-module-spii2c-128x64-7-pin-blue-p-2079.html

body:
Yes, it works IIC as described above, with my Arduino MEGA.
You can also connect RST Pin at Arduino RESET signal, so no need of extra R and C components


body:
I have started to use GitHub to store Arduino code. However some of my code uses the SSID and password for my WLAN which I don’t want published.

A common way of handling this in non-embedded programming is to use a configuration file, but that doesn’t seem to be a viable approach in programming the Arduino. I’m currently just commenting out the sensitive information before pushing it to GitHub, but one day I’m sure I’ll forget.

Is there another – better - way of handling this?

title: Hiding WLAN password when pushing to GitHub

Answers: 3

body:
Sure you can use a config file. It's called a "header" file, and you just `#include` it in your sketch.

    [config.h (not pushed)]

    const char *password = "DOD982yp398fhgpwbn09tupf0p04";

    [sketch.ino (pushed)]

    #include "config.h"

    // Now you can use the password variable.

Another method, which is better if you have multiple files in your sketch, is to use `#define` instead of variables in your header file:

    [config.h]

    #define WIFI_PASSWORD "348r0yp80ytwp85tpj8yjp98y97t8t"

    [sketch.ino]

    #include "config.h"

    const char *password = WIFI_PASSWORD;

body:
You could commit the following file into your project, named
credentials.h:

    // Replace with your actual SSID and password:

    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

Near the beginning of your sketch, you add:

    #include "credentials.h"

    const char ssid[] = WIFI_SSID;
    const char password[] = WIFI_PASSWD;

Now, you can edit credentials.h to add your real SSID and password, and
go on with your normal git workflow, with one exception: never
`git add credentials.h` again, nor `git commit -a`.

Now, git will always remind you that credentials.h has been modified and
is not staged for commit. It will do so even if you add the file to your
.gitignore. If you always review your changes before committing, this is
only a minor inconvenience. If, on the other hand, you tend to
`git commit -a` without reviewing what you are committing, then this
solution is likely not for you.

------------------------------------------------------------------------

**Edit**: An idea I got from reading Chris Stratton's comments. **If**
you use a Makefile in your own workflow (this has already been discussed
in this site a few times), you could commit this credentials.h to your
repo:

    #ifndef CREDENTIALS_H
    #define CREDENTIALS_H

    // Replace with your actual SSID and password:
    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

    #endif

Make a copy of this file named true-credentials.h and put the real
credentials there (but do not rename the include guard). Then add to
your Makefile

<!-- language: lang-none -->

    CFLAGS += -include true-credentials.h

Keep true-credentials.h and the Makefile out of the repo. You can add
them to your .gitignore or, better yet, to .git/info/exclude.

Now you have a compilable version with dummy credentials in the
repository, you have the true credentials when you compile on your own
machine, and git does not bother you about credentials.h being changed.

body:
Building upon the shoulders of giants I took Edger Bonet's answer and used a slightly different twist.  I went this route because I don't use a makefile and found this solution works well for me in my project.

I created a placeholder credentials.h file with the following info (Edger's answer).

    #ifndef CREDENTIALS_H
    #define CREDENTIALS_H

    // Replace with your actual SSID and password:
    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

    #endif

I further added the reference to this new file in the .ino file.

    #include "credentials.h"

    const char ssid[] = WIFI_SSID;
    const char pass[] = WIFI_PASSWD;

Now the twist.. I excluded the file from being checked for changes using the --assume-unchanged command.

> git update-index --assume-unchanged credentials.h

You can then modify the credentials.h file and wont be prompted to add it to github.

Note, to re-check the file use --no-assume-unchanged.


body:
I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

    Pin 1: TRUE
    Pin 2: FALSE
    Pin 3: FALSE
    Pin 4: TRUE

    Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
    1 + 0 + 0 + 8
    Result: 9

This is pretty efficient.
But how do I decode the pin states from this best?
Or do you recommend a better way to do this?

title: Encode & decode boolean values into a single integer?

Answers: 2

body:
You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the *bit number* in there. The `<<` is *left shift*.

    #define PIN0 (1 << 0)
    #define PIN1 (1 << 1)
    #define PIN2 (1 << 2)
    #define PIN3 (1 << 4)

Now you can combine:

    uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

    if (val & PIN3) {
        // ....
    }

To loop through the pins you can use the `<<` again:

    for (uint8_t pin = 0; pin < 8; pin++) {
        if (val & (1 << pin)) {
            // ....
        }
    }

etc.

body:
use the AND operator.

for example:

pin 2's state would be (result & 0x02)?TRUE:FLASE


body:
I am trying to write a keyboard (Key-glove) program. There are 4 buttons, and inputs should type specific keys. when the keyboard is active, I get output, but not what I am expecting for output. I get "EnE" and "EC".
The Hardware is an adafruit Circuit Playground

Here is my source:

    //keyboard control for TuxKart power Glove
    #include <Adafruit_CircuitPlayground.h>
    #include "Keyboard.h"

    // set pin numbers for the five buttons:
    const int Fire = 6;
    const int Nitro = 9;
    const int Eagle = 10;
    const int _Esc = 12;

    bool slideSwitch;

    void setup() { // initialize the buttons' inputs:
      pinMode(Fire, INPUT);
      pinMode(Nitro, INPUT);
      pinMode(Eagle, INPUT);
      pinMode(_Esc, INPUT);

      Serial.begin(9600);
      // initialize mouse control:
      //Mouse.begin();
      Keyboard.begin();
    }

    void loop() {
      if (!CircuitPlayground.slideSwitch()) {
        return;
      }

      // use the pushbuttons to control the keyboard:
      if (digitalRead(Fire) == HIGH) {
        Keyboard.write('KEY_SPACE');
        Serial.println("A");
      }
      if (digitalRead(Nitro) == HIGH) {
        Keyboard.write('n');
        Serial.println("B");
      }
      if (digitalRead(Eagle) == HIGH) {
        Keyboard.write('KEY_BACKSPACE');
        Serial.println("Z");
      }
      if (digitalRead(_Esc) == HIGH) {
        Keyboard.write('KEY_ESC');
        Serial.println("Y");
      }
    delay(700);
    }

title: weird output from keyboard program

Answers: 0


body:
I'm testing three different Arduino (nano, Uno and Mega) each of them having a nRF module. The codes (sketches) are different for each module.
I've connected the arduinos to my single laptop via 3 USB ports.

Problem is, whenever I want to re-upload a sketch and fix a bug, I have to choose board model and port number of that sketch by using the menus. It has become frustrating using mouse each time I need to change something.
How can I set these parameters in code so each sketch knows which port and model it is related to?

title: How to programmatically choose "board model" and "port number" in Arduino IDE?

Answers: 2

body:
You can't in the Arduino IDE, it's not designed that way (you can't even have different board/port settings in different windows - it's stored in the Java equivalent of a single global).

Instead you will have to switch to a different programming environment.

Personally (since I am the author) I would suggest switching to [UECIDE](http://uecide.org). That has far more advanced facilities than the Arduino IDE, yet still retains most of the simplicity of use.

In UECIDE you can not only have different ports and boards selected in different windows, you can also configure individual sketches to automatically select their board and port.

* **Sketch -> Sketch Properties... -> Objects tab**

 [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/5gjft.png

body:
Take a look at the (similar) question and answer in https://arduino.stackexchange.com/a/9182/22924

It talks about multiple UNOs, but the solution should help here.


body:
Let me explain my question in more details. I want to use ESP8266-01 as standalone micro-controller for my project. I don't want to use Arduino or any other board with that.
Using Arduino i can use two of the pins as software serial and can send different AT commands to ESP module to ESP's Tx and Rx pins, but now what I want is to eliminate the need to Arduino.

What I want to do is to to program ESP itself to toggle mode from AP mode to Host mode on press of a push button. for that I has to send AT commands to ESP from the code while i will write to the ESP itself. Is there any way to achieve the same.

I tried searching a lot but what I found everywhere is how to send AT commands from Arduino.

Thanks in advance.

title: Send AT commands programatically to ESP8266 without Arduino

Answers: 1

body:
You don't use AT commands. You install the esp8266 boards package and program the esp8266 as if it were an Arduino. That means learning the esp8266 WiFi API which has plenty of examples included.

* https://github.com/esp8266/Arduino/


body:
I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!

title: If (serial.available()) conditional statement

Answers: 2

body: In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.

body:
> Scenario A, it appears to me that there is no conditional statement, h

The first is a test on if available() returns a non zero value.


body:
I have an [Adafruit circuit playground classic][1], and the touch-pads are so very sensitive. From a centimeter away, they trigger.  I would be happy to just have regular inputs, or to have the sensitivity reduced. How can I do this?

To clarify, here is my code:

    //keyboard control for TuxKart power Glove
    #include <Adafruit_CircuitPlayground.h>
    #include <Keyboard.h>
    #include <Mouse.h>
    // set pin numbers for the five buttons:
    const int Fire = 6;
    const int Nitro = 9;
    const int Eagle = 10;
    const int _Esc = 12;

    bool slideSwitch;

    void setup() { // initialize the buttons' inputs:
      pinMode(Fire, INPUT_PULLUP);
      pinMode(Nitro, INPUT_PULLUP);
      pinMode(Eagle, INPUT_PULLUP);
      pinMode(_Esc, INPUT_PULLUP);

      Serial.begin(9600);
      // initialize mouse control:
      //Mouse.begin();
      Keyboard.begin();
    }

    void loop() {
      if (!CircuitPlayground.slideSwitch()) {
        return;
      }

      // use the pushbuttons to control the keyboard:
      if (!digitalRead(Fire) == HIGH) {
        Keyboard.write('KEY_SPACE');
        Serial.println("F");
      }
      if (!digitalRead(Nitro) == HIGH) {
        Keyboard.write('n');
        Serial.println("U");
      }
      if (!digitalRead(Eagle) == HIGH) {
        Keyboard.write(0xB2);
        Serial.println("N");
      }
      if (!digitalRead(_Esc) == HIGH) {
        Keyboard.write(0xB1);
        Serial.println("K");
      }
    delay(200);
    }

This code or any other, where capacitive touch sensitivity has not been specified, yields pins having extreme sensitivity. I have read the comments, that say the MCU doesn't feature this natively. If that were true, how would the pins remain sensitive?

My solution to this is to set sensitivity so low, that it is negligible. If capacitive touch sensing is not specified, why am I getting that functionality? Why would this code give me capacitive touch sensing?
Ideally, I would disable the touch sensing somehow, or have the pins simply behave normally, like any other Arduino based device that doesn't have touch sense. But what I have guessed, (shown in code) doesn't work. If there is a more explicit way to specify that IO pins should act as normal pins, without capacitive touch sensing, I would surely like to know.

  [1]: https://www.adafruit.com/product/3000

title: How can the sensitivity of capacitive touch sensors be limited?

Answers: 2

body:
Its not the best method for finding a solution, perhaps, but I was tooling around in the Adafruit_CircuitPalyground repo, and found a macro for the Capacitive touch sensitivity.

The macro is:

    #define CAP_THRESHOLD 300 // Threshold for a capacitive touch (higher = less sensitive).

Located here:
https://github.com/adafruit/Adafruit_CircuitPlayground/search?utf8=✓&q=CAP_THRESHOLD&type=

I'm reading more, and trying to find the libraries for capacitive touch. There may be a much better solution, but for now defining CAP_THRESHOLD works well enough.

body:
`digitalRead(pin)` is the wrong way to read capacitive touch inputs.

In the [file from the example][1] you linked in [your answer][2], the reading is made by calling `CircuitPlayground.readCap(pin, num_samples)` and then the returning value is compared to a threshold.

<!-- language: c++ -->

    const uint16_t TOUCH_THRESHOLD = 300;

    ...

    if (CircuitPlayground.readCap(Fire) >= TOUCH_THRESHOLD) {
       Keyboard.write(KEY_SPACE);
       Serial.println('F');
    }
    ...

You can change the sensitivity by changing `TOUCH_THRESHOLD`. You could also add and fiddle with the second argument to change the number of samples.

  [1]: https://github.com/adafruit/Adafruit_CircuitPlayground/blob/e871c0b23ff6731489045142464f233853ac43cd/examples/mega_demo/CapTouchDemo.h
  [2]: https://arduino.stackexchange.com/a/41446


body:
Is there any support to this chip in Arduino IDE, like bootloaders and boards definitions.. i want to use this chip with 3.3V and 8Mhz crystal speed..

I have seen Nick Gammon bootloaders supports this chip for bootloaders, but not with 8Mhz.? and how to add this chip to Arduino IDE.

anybody help..

thanks you

title: How to use Atmega1284AU with Arduino IDE

Answers: 1

body:
Please check out MightyCore library by MCUdude.

https://github.com/MCUdude/MightyCore

I have used it and can verify it works pretty well with ATmega1284.


body:
When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

 - Have I "bricked" it?
 - What steps can I take to work out what is wrong?
 - What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.

I've checked working usb cable and another laptop but not work.I think **hardware problem**.Once arduino getting hot near usb.

title: I can't upload sketches to my Arduino 101

Answers: 3

body:
It's hard to tell, but you can try a lot of options:

- Use another USB port
- Use another USB cable
- Reinstall the Arduino IDE
- Remove the device in the device manager and try reinstalling the Arduino IDE again
- Try another Arduino (to see if the USB/install is ok)
- Try on a different computer/laptop

body: If you checked all of the above as *Michel Keijzers* mentioned then it might be a hardware problem. Actually, your usb cable might not fitting correctly to the usb port.

body: Simply replace it because it has a 1 year warranty outside the US.


body:
I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.

I'm able to read and copy bytes into an array of bytes.
However, I'm facing an issue with the verification of those bytes.

Here's the code I've written:

    #include <SoftwareSerial.h>

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

    void loop()
    {
        char charRead = 0x00u;
        byte byteArray[10];
        int i=0 , j=0;

        //Clear the array contents
        for(j = 0; j < 10u; j++)
        {
           byteArray[j] = 0x00u;
        }

        //Wait for data on serial channel
        while(Serial.available() > 0)
        {
           //Copy bytes received into array
           charRead      = Serial.read();
           byteArray[i] = (byte)charRead;
           i++;
        }

        //Just for the sake, print the array contents
        for(j = 0; j < i; j++)
        {
           Serial.print(byteArray[j],HEX);
        }

        //Check for first two bytes
        if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
        {
            Serial.println("Verified.");
        }
    }

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.

What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.

Am I doing something wrong here with Serial.read() or some typecasting?

I'm running this on an Arduino Uno

title: Problem with reading series of bytes over serial port

Answers: 1

body:
So, as result of Edgar Bonet's good remark, change

    int i=0 , j=0;

to

    int j = 0;

and define

    int i = 0;

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.


body:
To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?

title: DigitalWrite Cannot Power HC-06 Bluetooth

Answers: 2

body:
A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is **not** suitable for powering meaty RF modules.

Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.

For instance, assuming a 5V module with built in 3.3V LDO:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/YSY9f.png)

<!-- End schematic -->

Note that `/RFEN` is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.

Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.

R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.

body:
> it should have enough power.

Probably not. Debugging is about challenging all assumptions, especially implicit ones.

Put a high side switch there and it should be ok.


body:
I'm new to Arduino, I want to create a restaurant buzzer using Arduino and it should turn on/off via web based interface. It will be locally connected only.

Is it possible to send a signal with the mac address of the master transmitter pc to vibrate the buzzer?

What are the materials should I need? Suggestions or any tips is greatly appreciated.

title: Send signal to vibrate a Restaurant buzzer via web based app to a PC

Answers: 1

body:
You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.

Because you want to do it over WIFI, an Arduino is probably not the best choice.  As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI.  I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.
[![enter image description here][1]][1]

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum.  Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE).  There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs.  You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.

Then your client just needs to connect to the root page of the webserver and the buzzer will sound.  You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.

You can then expand this to identify which client sounded the buzzer.

As to keeping it local, use the firewall on your router.

  [1]: https://i.stack.imgur.com/iH745.jpg


body:
I'm a newbie here. And sorry for my bad English first of all.

Right now I'm working on VLC (Visible Light Communication). I have working code, in which output is displayed on the Serial Monitor. But now I want to print this output on an LCD.

I made necessary changes like including the LCD library and instead of `Serial.print` I used `lcd.print`. But nothing is displayed on the LCD.

Here is the modified code including LCD:

    static int TRESHOLD = 500;
    static unsigned int standardDelay = 13500000; //1350 is limit
    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 7,6,5,4);

    void setup() {
      Serial.begin(9600); // 9600 bits per second
      pinMode(3,OUTPUT); //digital PWM 3 on output
      int sensorValue = 0;
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // initialize the serial communications:
    }

    void loop() {
      WriteChar('h');
      WriteChar('e');
      WriteChar('l');
      WriteChar('l');
      WriteChar('o');
      WriteChar('w');
      WriteChar('o');
      WriteChar('r');
      WriteChar('l');
      WriteChar('d');
    }

    void WriteChar(char str){
      switch (str - '0'){
        case 49:
          //code for a is 011 0001
          LightFlash(false, true, true, false, false, false, true);
          break;
        case 50:
          //code for b is 011 0010
          LightFlash(false, true, true, false, false, true, false);
          break;
        case 51:
          //code for c is 011 0011
          LightFlash(false, true, true, false, false, true, true);
          break;
        case 52:
          //code for d is 011 0100
          LightFlash(false, true, true, false, true, false, false);
          break;
        case 53:
          //code for e is 011 0101
          LightFlash(false, true, true, false, true, false, true);
          break;
        case 54:
          //code for f is 011 0110
          LightFlash(false, true, true, false, true, true, false);
          break;
        case 55:
          //code for g is 011 0111
          LightFlash(false, true, true, false, true, true, true);
          break;
        case 56:
          //code for h is 011 1000
          LightFlash(false, true, true, true, false, false, false);
          break;
        case 57:
          //code for i is 011 1001
          LightFlash(false, true, true, true, false, false, true);
          break;
        case 58:
          //code for j is 011 1010
          LightFlash(false, true, true, true, false, true, false);
          break;
        case 59:
          //code for k is 011 1011
          LightFlash(false, true, true, true, false, true, true);
          break;
        case 60:
          //code for l is 011 1100
          LightFlash(false, true, true, true, true, false, false);
          break;
        case 61:
          //code for m is 011 1101
          LightFlash(false, true, true, true, true, false, true);
          break;
        case 62:
          //code for n is 011 1110
          LightFlash(false, true, true, true, true, true, false);
          break;
        case 63:
          //code for o is 011 1111
          LightFlash(false, true, true, true, true, true, true);
          break;
        case 64:
          //code for p is 100 0000
          LightFlash(true, false, false, false, false, false, false);
          break;
        case 65:
          //code for q is 100 0001
          LightFlash(true, false, false, false, false, false, true);
          break;
        case 66:
          //code for r is 100 0010
          LightFlash(true, false, false, false, false, true, false);
          break;
        case 67:
          //code for s is 100 0011
          LightFlash(true, false, false, false, false, true, true);
          break;
        case 68:
          //code for t is 100 0100
          LightFlash(true, false, false, false, true, false, false);
          break;
        case 69:
          //code for u is 100 0101
          LightFlash(true, false, false, false, true, false, true);
          break;
        case 70:
          //code for v is 100 0110
          LightFlash(true, false, false, false, true, true, false);
          break;
        case 71:
          //code for w is 100 0111
          LightFlash(true, false, false, false, true, true, true);
          break;
        case 72:
          //code for x is 100 1000
          LightFlash(true, false, false, true, false, false, false);
          break;
        case 73:
          //code for y is 100 1001
          LightFlash(true, false, false, true, false, false, true);
          break;
        case 74:
          //code for z is 100 1010
          LightFlash(true, false, false, true, false, true, false);
          break;
        default:
          lcd.print(str - '0');
          lcd.print("CAME IN DEFAULT IN WRITECHAR");
          break;
      }
    }

    void LightFlash(boolean a, boolean b, boolean c, boolean d, boolean e, boolean f, boolean g){

      digitalWrite(3,LOW);
      if (a == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue1 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (b == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue2 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (c == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue3 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (d == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue4 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (e == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue5 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (f == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue6 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (g == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue7 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);
      delayMicroseconds(3*standardDelay); //1 second passed

      long result = 0;
      result = 1000000*sensorValue1 + 100000*sensorValue2 + 10000*sensorValue3
      + 1000*sensorValue4 + 100*sensorValue5 + 10*sensorValue6 + 1*sensorValue7;
      //lcd.print(result);
      PrintChar(result);
    }

    void PrintChar(long binary){

      switch (binary){

        case 110001:
          //code for a is 011 0001
          lcd.write("a");
          break;
        case 110010:
          //code for b is 011 0010
          lcd.print("b");
          break;
        case 110011:
          //code for c is 011 0011
          lcd.print("c");
          break;
        case 110100:
          //code for d is 011 0100
          lcd.print("d");
          break;
        case 110101:
          //code for e is 011 0101
          lcd.print("e");
          break;
        case 110110:
          //code for f is 011 0110
          lcd.print("f");
          break;
        case 110111:
          //code for g is 011 0111
          lcd.print("g");
          break;
        case 111000:
          //code for h is 011 1000
          lcd.print("h");
          break;
        case 111001:
          //code for i is 011 1001
          lcd.print("i");
          break;
        case 111010:
          //code for j is 011 1010
          lcd.print("j");
          break;
        case 111011:
          //code for k is 011 1011
          lcd.print("k");
          break;
        case 111100:
          //code for l is 011 1100
          lcd.print("l");
          break;
        case 111101:
          //code for m is 011 1101
          lcd.print("m");
          break;
        case 111110:
          //code for n is 011 1110
          lcd.print("n");
          break;
        case 111111:
          //code for o is 011 1111
          lcd.print("o");
          break;
        case 1000000:
          //code for p is 100 0000
          lcd.print("p");
          break;
        case 1000001:
          //code for q is 100 0001
          lcd.print("q");
          break;
        case 1000010:
          //code for r is 100 0010
          lcd.print("r");
          break;
        case 1000011:
          //code for s is 100 0011
          lcd.print("s");
          break;
        case 1000100:
          //code for t is 100 0100
          lcd.print("t");
          break;
        case 1000101:
          //code for u is 100 0101
          lcd.print("u");
          break;
        case 1000110:
          //code for v is 100 0110
          lcd.print("v");
          break;
        case 1000111:
          //code for w is 100 0111
          lcd.print("w");
          break;
        case 1001000:
          //code for x is 100 1000
          lcd.print("x");
          break;
        case 1001001:
          //code for y is 100 1001
          lcd.print("y");
          break;
        case 1001010:
          //code for z is 100 1010
          lcd.print("z");
          break;
        case 11000:
          lcd.print("dit gebeurt vaak");
          break;
        case 1011001:
          lcd.print("dit ook");
          break;
        case 100001:
          lcd.print("tenslotte dit nog");
          break;
        case 1011000:
          lcd.print("en dit is de laatste denk ik");
          break;
        default:
          lcd.print(binary);
          lcd.print("CAME IN DEFAULT ON PRINTCHAR");
          break;
      }
    }

I want to print this output on LCD. But I'm not able to do that. Please help me out.

Circuits:

(1) VLC Circuit

[![VLC Circuit][1]][1]

(2) LCD Circuit

[![LCD Circuit][2]][2]

I combined both circuits above and made a final circuit.

The VLC circuit is set up in which DATA is transmitted from SIMPLE LED and Capture on PHOTODIODE. And using LCD Circuit I want to display data on LCD.

  [1]: https://i.stack.imgur.com/BiFnT.png
  [2]: https://i.stack.imgur.com/cDJDf.png

title: Can't print on LCD

Answers: 2

body:
There is so many problems with your code. It can be so much short.

Take WriteChar. Why mess with binary value for chars? Use char directly, just here:

    void setup() {
      Serial.begin(9600);
      WriteChar('h');
      WriteChar('e');
    }

    void loop() {
    }

    void WriteChar(char c) {
      boolean b7 = c & B1000000;
      boolean b6 = c & B0100000;
      boolean b5 = c & B0010000;
      boolean b4 = c & B0001000;
      boolean b3 = c & B0000100;
      boolean b2 = c & B0000010;
      boolean b1 = c & B0000001;

      Serial.println(c);
      LightFlash(b7, b6, b5, b4, b3, b2, b1);

    }

    void LightFlash(boolean b7, boolean b6, boolean b5, boolean b4, boolean b3, boolean b2, boolean b1) {
      Serial.print(b7 ? "1" : "0");
      Serial.print(b6 ? "1" : "0");
      Serial.print(b5 ? "1" : "0");
      Serial.print(b4 ? "1" : "0");
      Serial.print(b3 ? "1" : "0");
      Serial.print(b2 ? "1" : "0");
      Serial.println(b1 ? "1" : "0");
    }

There is more simply ways to write that (using arrays and loops) but this is easier to understand. And better, pass the char directly to LightBlash.

Don't use a string when you just pass a char to a function.

body:
Finally, got the problem. My code is working fine. I have a problem with my LCD connection.

I write

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

Instead of

    LiquidCrystal lcd(12, 11, 4, 5, 6, 7);


body:
I have an arduino Uno and nodemcu development board.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/vsM3q.jpg

I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the [Instructables tutorial][2] named as FromComputerNerd.ino.

Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs [shown in][2]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.

But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?

http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/

title: Differences between nodemcu and arduino processer

Answers: 2

body:
I am suggesting you to buy NodeMCU because it is having inbuilt WIFI, you can connect NodeMcu to internet without much effort compare to connecting UNO to internet, and the best thing is NodeMCU is arduino compatible you can do all possible stuff that can be done with UNO. We can also program NodeMCU in 'C' language using Arduino IDE directly

**Hardware comparison**

*NodeMCU*

1. 128KB RAM
2. 4MBytes ROM(flash)
3. micro USB port
4. Small Board Size

*Arduino UNO*

1. 2kB RAM
2. 32 KB ROM
3. USB type B connector
4. Bigger in size than NodeMCU

> Both are having nearly same prices.

body:
Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.

NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.

see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library


body:
I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.

Can someone help me with the code? Any help is very much appreciated.

Here is my code.

    int Pwmpin=9;//Pwm Output Pin
    int Fchange= A0;//Frequency change through Potentiometer

    void setup() {
      pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
      Serial.begin(9600);
      TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
      TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8
    }

    void loop(){
      float freq=0;
      float count=10000,countt=0,Pinput=0;
      while(1){
        ICR1=count;//variable Frequency
        countt=16*count;
        freq= int(16000000/countt);
        OCR1A=int(count/2);
        Serial.print("Pwm Freq =");
        Serial.println(freq);
        count=10000;
        Pinput=analogRead(A0);//Read input value
        Serial.print("adc value is:");
        Serial.println(Pinput);
        Pinput=(Pinput/0.0113);
        Serial.print("pwm value is:");
        Serial.println(Pinput);
        count=count+Pinput;
        if(count>=100000) {
          count=10000;
        }
        delay(1000);
      }
    }

title: Code to obtain PWM output

Answers: 1

body:
1. Read the datasheet.
2. Figure out which pen mode works for you and which prescaler and top you need.
3. Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.

For your application leave the top value alone.

Your code is far from that.


body:
I cloned https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor
and copied the libraries into the Arduino `libraries` folder. I then launched Arduino and selected the example. I opened the file GestureTest and when I started upload I received this error:

>GestureTest.ino:49:31: fatal error: SparkFun_APDS9960.h: No such file or directory
>
>compilation terminated.

I checked the `SparkFun_APDS9960.h` and I found it in the `Gesture_Sensor/Libraries/src` folder.

Is there a solution to resolve this error?

title: Arduino Gesture Sensor error:No such file or directory

Answers: 1

body:
SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

1. Download the latest release from https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/archive/V_H1.0_L1.4.2.zip.
2. Unzip the downloaded file.
3. Rename the folder `APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino` to `SparkFun_APDS9960`. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
4. Copy the `SparkFun_APDS9960` folder to `{sketchbook folder}/libraries`. You can find the location of the sketchbook folder at **File > Preferences > Sketchbook location**.
5. Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.

UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.


body:
I was browsing through the [hookup guide][1] for SparkFun's OBD-II UART breakout and found something particularly worrying written half way down in a quite casually presented way:

> Keep in mind when you upload this to your board, you will want to disconnect the OBD-II board RX line from the Arduino TX-0, to prevent issues during code upload, such as bricking the OBD-II board.

For my money I think bricking your device should come with a more stark warning than one stuffed part way down a guide starting with "keep in mind" and continuing with "issues". Nonetheless it caught my attention as I tend to build sealed boxes that aren't sprawled in front of a keyboard ready to be rewired any time a re-flash might happen.

Is the real risk here the fact that all of the flashed data would stream past the RX pin of the UART board and potentially accidentally send a 'self-destruct' signal? (Also I'm not sure a system is really up to scratch if you can accidentally tell it to kill itself.)

Surely the programming port is not the one being borrowed by the UART hookup? On a MEGA 2560, using a different serial port, is this still a risk or is that only on boards with one serial port?

  [1]: https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide

title: Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed?

Answers: 1

body:
In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.

The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.

The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.

If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.

If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.

[**ADDED**]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the [AltSoftSerial][1] can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
I'm writing PortExtender, a library to convert an Arduino Pro Mini in a port expander and I ran into what seems to be a compatibility problem between Arduino and nodeMCU: I got different answers depending on who is the master (Arduino or nodeMCU).

This is my test configuration:

[![Test configuration][1]][1]

At the center, the Slave Arduino, with buttons, leds, and ldr for testing pin access.

I have two master, but only one is used at a time. The inactive one is powered off and disconected from the two others. The slave get its power from the master.

I compiled and ran the same Master program in the two master, while the slave remains the same. This is the Master test program:

    #include <Wire.h>
    #include <PortExtender.h>

    const int SLAVE_ADDRESS = 42;

    PortExtender port = PortExtender(SLAVE_ADDRESS);

    void setup ()
    {
      Serial.begin(9600);
      delay(1000);
      Serial.println("Master");
      Serial.println("-----");

      Wire.begin();
      int r;
      do {
        r = port.reset();
        Serial.print("Resetting Port Expander. Status=");Serial.println(r);
        delay(100);
      } while(r != SLAVE_ADDRESS);
    }

    void loop() {
    }

The test just sent a soft-reset to the slave. The slave answers with its own address (42), just to check that the command works.

**Master 1 execution**

This is the correct result from Master 1 (Arduino Pro Mini):

[![Master 1 response][2]][2]

In fact, I can run a complete test suit with no problems, testing the button, controlling the LED and reading the LDR.

**Master 2 execution**

This is the result from Master 2 (nodeMCU):

[![enter image description here][3]][3]

Response is some random value that change from run to run. Slave, however, receive the command and return the right response, as checked thru Serial Monitor connected to the slave.

Everything seems to work fine, but answer from slave looks like it changed "in the wire".

**PortExtender library code**

The relevant methods involved are:

    int PortExtender::reset() {
        return send(CMD_RESET);
    }

    int PortExtender::send(byte cmd) {
        Wire.beginTransmission(slave);
        Wire.write(cmd);
        Wire.endTransmission(false); // Also tested with true.
        return readAnswer();
    }

    int PortExtender::readAnswer() {
        short answer;

        Wire.requestFrom(slave, sizeof(answer));
        PortExtender::read((byte*) &answer, sizeof(answer));
        return (int) answer;
    }

    void PortExtender::read(byte* p, int len) {
        while (len > 0 && Wire.available() > 0) {
            *p++ = Wire.read();
            len--;
        }
    }

Arduino ints are 2 bytes, nodeMCU ints are 4 bytes. Data from slave is send as short (Arduino, 2 bytes), received as short (nodeMCU, 2 bytes) and then promoted to int (nodeMCU, 4 bytes).

**PortExtender.h**

    #ifndef PortExtender_h
    #define PortExtender_h
    /*
     *
     */
    #include <Arduino.h>
    #include <inttypes.h>

    #define NO_CMD             0
    #define CMD_DIGITAL_WRITE  1
    #define CMD_DIGITAL_READ   2
    #define CMD_ANALOG_WRITE   3
    #define CMD_ANALOG_READ    4
    #define CMD_PIN_MODE       5
    #define CMD_SET_WATCHDOG   6
    #define CMD_START_WATCHDOG 7
    #define CMD_STOP_WATCHDOG  8
    #define CMD_RESET          9
    #define CMD_PLAY          10
    #define CMD_PLAY_STEP     11
    #define CMD_DEBOUNCE      12
    #define CMD_TONE          13
    #define CMD_TONE_LEN      14
    #define CMD_NO_TONE       15

    #define ERROR_NO_RESET    -1
    #define ERROR_PARAMETER   -2

    struct PAR_TONE {
        byte pin;
        unsigned int freq;
    };

    struct PAR_TONE_LEN {
        byte pin;
        unsigned int freq;
        unsigned long len;
    };

    class PortExtender
    {
      private:
          short slave;
          int send(byte* b, int len);
          int send(byte cmd);
          int send(byte cmd, byte arg1);
          int send(byte cmd, byte arg1, byte arg2);
          int readAnswer();

      public:
          PortExtender(int slaveAddress);

          /*
           *     All same as Arduino, except as noted.
           */
          int pinMode(int pin, int mode);
          //    Set debouncer.
          int debounce(int pin, short debounce);

          int digitalWrite(int pin, int value);
          int digitalRead(int pin);
          int analogWrite(int pin, int value);
          int analogRead(int pin);
          int tone(int pin, unsigned int freq);
          int tone(int pin, unsigned int freq, unsigned long len);
          int noTone(int pin);

          /*
           * Watchdog functions
           */
          //    Designate the output pin and watchod parameters.
          int setWatchdog(int pin, unsigned long time, unsigned long pulse);
          int startWatchdog();
          int stopWatchdog();

          /*
           *    Timed switching of a pin, with a giving set of intervals.
           */
          int play(int pin, unsigned int score[]);

          /*
           *    Reset Port Extender.
           */
          int reset();
          static void read(byte*, int len);
    };

    #endif

**Slave PortExtender (Arduino Pro Mini)**

This is work in progress. Digital/Analog read/write completed, other methods (play, watchdog and tone still to be tested).

    /*
       Programable Port Extender by Look Alterno.

       Convert your Arduino in a I2C slave that extends
       the number of pin for your master Arduino.

       Your master Arduino will be able to:
       - Read/Write digital/analog pins.
       - Program one-shot pulses of any length.
       - Program PWM with arbitrary period and duty cycle.

       Applications:
       - Make timers for external appliances.
       - Implement watchdogs for resetting things.
    */

    //  ---- Change this address to a suitable value if needed ----
    #define MY_ADDRESS  42

    #include <Bounce2.h>
    #include <Wire.h>
    #include <PortExtender.h>

    //  A CMD_RESET has been received from master.
    boolean bReset = false;

    //  These port are programmables.
    struct {
      byte pin;
      byte exp;
    } pins[] = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0},
      {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}, {13, 0},
      {A0, 0}, {A1, 0}, {A2, 0}, {A3, 0}
    };

    const short nPins = sizeof(pins) / sizeof(pins[0]);

    struct {
      Bounce debouncer;
      short pin;
      short interval;
    } debouncer = {Bounce(), 0, 0};

    #define WD_NORMAL 0
    #define WD_PULSE  1

    struct {
      int pin;
      int state;
      boolean active;
      unsigned long lastBeat;
      unsigned long time;
      unsigned long pulse;
      unsigned long wait;
      unsigned long startPulse;
    } watchdog;

    #define SCORE_MAX_STEP 50
    struct {
      boolean active;
      int pin;
      unsigned long time; // start time of current step.
      int freeStep;       // for filling the array.
      int currentStep;    // for playing the array.
      unsigned int step[SCORE_MAX_STEP];
    } score;

    typedef void (*fcnptr)();

    void cmdBeat();
    void cmdDigitalWrite();
    void cmdDigitalRead();
    void cmdAnalogWrite();
    void cmdAnalogRead();
    void cmdPinMode();
    void cmdWatchdog();
    void cmdStartWatchdog();
    void cmdStopWatchdog();
    void cmdReset();
    void cmdPlay();
    void cmdPlayStep();
    void cmdDebounce();
    void cmdTone();
    void cmdToneLen();
    void cmdNoTone();

    struct {
      byte  cmd;
      fcnptr fcn;
    } commands[] = {
      { NO_CMD,             cmdBeat},
      { CMD_DIGITAL_WRITE,  cmdDigitalWrite},
      { CMD_DIGITAL_READ,   cmdDigitalRead},
      { CMD_ANALOG_WRITE,   cmdAnalogWrite},
      { CMD_ANALOG_READ,    cmdAnalogRead},
      { CMD_PIN_MODE,       cmdPinMode},
      { CMD_SET_WATCHDOG,   cmdWatchdog},
      { CMD_START_WATCHDOG, cmdStartWatchdog},
      { CMD_STOP_WATCHDOG,  cmdStopWatchdog},
      { CMD_RESET,          cmdReset},
      { CMD_PLAY,           cmdPlay},
      { CMD_PLAY_STEP,      cmdPlayStep},
      { CMD_DEBOUNCE,       cmdDebounce},
      { CMD_TONE,           cmdTone},
      { CMD_TONE_LEN,       cmdToneLen},
      { CMD_NO_TONE,        cmdNoTone}
    };

    unsigned long now = millis();
    byte  lastCommand;
    short answer;

    void setup() {
      Serial.begin(9600);
      Serial.println("--- Port Extender ---");

      initAll();
      Wire.begin(MY_ADDRESS);
      Wire.onReceive(receiveCommand);
      Wire.onRequest(sendAnswer);
    }

    void loop() {
      now = millis();

      checkDebouncer();
      checkWatchdog();
      checkPlay();
    }

    void checkDebouncer() {
      debouncer.debouncer.update();
    }

    /*
       Start playing a score on pin.
       The pin start at the last value set by master (HIGH or LOW)
    */
    void startPlay() {
      noInterrupts();
      score.active = true;
      score.time   = millis();
      score.currentStep = 0;
      digitalWrite(score.pin, !digitalRead(score.pin));
      interrupts();
    }

    void checkPlay() {
      noInterrupts();

      if (score.active) {
        unsigned long stepEnd = score.time + score.step[score.currentStep];

        if (now >= stepEnd) {
          score.currentStep++;

          if (score.currentStep >= score.freeStep) {
            score.active = false;
          } else {
            digitalWrite(score.pin, !digitalRead(score.pin));
            score.time = now;
          }
        }
      }

      interrupts();
    }

    /*
       Each if is time to reset the master.
       After resetting the master, soft-reset the slave.
    */
    void checkWatchdog() {
      if (watchdog.active) {

        switch (watchdog.state) {
          case WD_NORMAL:
            if (now - watchdog.lastBeat > watchdog.time) {
              pinMode(watchdog.pin, OUTPUT);
              digitalWrite(watchdog.pin, HIGH);
              watchdog.startPulse = now;
              watchdog.state = WD_PULSE;
            }

            break;

          case WD_PULSE :
            if (now - watchdog.startPulse > watchdog.pulse) {
              digitalWrite(watchdog.pin, LOW);
              cmdReset();
            }

            break;
        }
      }
    }

    /*
        Receive a command from Master
    */
    void receiveCommand(int howMany) {
      lastCommand = Wire.read();
      //  Serial.print("command="); Serial.println(lastCommand);
      answer = 0;

      if (!bReset && lastCommand != CMD_RESET) {
        //  The first command received must be a CMD_RESET.
        answer = ERROR_NO_RESET;
      } else {
        fcnptr f = commands[lastCommand].fcn;
        f();

        watchdog.lastBeat = now;
      }
    }

      // called by interrupt service routine when outgoing data is requested
      void sendAnswer() {
        Wire.write((byte *) &answer, sizeof(answer));
        lastCommand = NO_CMD;
      }
      void cmdBeat() {
      }

      void cmdReset() {
        //  Make a soft reset.
        initAll();
        bReset = true;
      }

      /*
         Initialize all variables and pins.
      */
      void initAll() {
        score.active = false;
        watchdog.active = false;
        debouncer.pin = -1;

        int size = sizeof(pins) / sizeof(pins[0]);

        for (int i = 0; i < size; i++) {
          int pin = pins[i].pin;
          pinMode(pin, OUTPUT);
          digitalWrite(pin, LOW);
        }

        answer = MY_ADDRESS;
      }

      void cmdPinMode() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();
          pinMode(pin, val);
        }
      }

      void cmdDebounce() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();
          debouncer.pin = pin;
          debouncer.interval = val;
          debouncer.debouncer.attach(pin);
          debouncer.debouncer.interval(val);
        }
      }

      void cmdDigitalWrite() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();

          digitalWrite(pin, val);
        }
      }

      void cmdDigitalRead() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();

          if (pin == debouncer.pin) {
            answer = debouncer.debouncer.read();
          } else {
            answer = digitalRead(pin);
          }
        }
      }

      void cmdAnalogWrite() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();

          analogWrite(pin, val);
        }
      }

      void cmdAnalogRead() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();

          answer = analogRead(pin);
        }
      }

      void cmdTone() {

      }

      void cmdToneLen() {

      }

      void cmdNoTone() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();
          noTone(pin);

        }
      }

      void cmdPlay() {
        if (Wire.available() == 1) {
          score.active = false;
          score.pin = Wire.read();
          score.freeStep = 0;
        }
      }

      void cmdPlayStep() {
        unsigned int val;

        if (Wire.available() == 2) {
          val = Wire.read() << 8 | Wire.read();

          if (val > 0) {
            Serial.print("val=");
            Serial.println(val);
            score.step[score.freeStep++] = val;
          } else {
            startPlay();
          }
        } else {
          answer = ERROR_PARAMETER;
        }
      }

      void cmdWatchdog() {
        PortExtender::read((byte *) &watchdog.pin, sizeof(watchdog.pin));
        PortExtender::read((byte *) &watchdog.time, sizeof(watchdog.time));
        PortExtender::read((byte *) &watchdog.pulse, sizeof(watchdog.pulse));
        watchdog.active = false;
      }

      void cmdStartWatchdog() {
        watchdog.active = true;
      }

      void cmdStopWatchdog() {
        watchdog.active = false;
      }

      int searchPin(int pin) {
        int i = 0;

        while (i < nPins && pins[i].pin != pin) {
          i++;
        }

        return (i < nPins) ? i : -1;
      }

**The question**

What is going wrong here?

  [1]: https://i.stack.imgur.com/ZY8sa.jpg
  [2]: https://i.stack.imgur.com/PTSVk.png
  [3]: https://i.stack.imgur.com/3kPP9.png

title: Wire library compatibility Arduino Pro Mini - nodeMCU (I2C/TWI) problem

Answers: 1

body:
**Hardware problem!**

The nodeMCU I'm using fails (mostly resets and garbage in the Serial Monitor) when inserted in the breadboard. That is. Them run OK when I let them just hanging from the USB cable.

I tested two of them in different breadboards. I also tested the breadboard for shorts and failed connections with an ohmmeter.

These are culprits:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/kAESo.jpg


body:
I am working on a project where I am taking the the key presses from a PS/2 keyboard and passing them to several pro micro boards so I can type the same commands on multiple computers at the same time. I have a master board that is a Leonardo that is connected to a keyboard. Using the TX pin I am connecting to a pro micro and trying to receive keystrokes on the micro and output them to a computer. I can get a the keyboard to work with the Leonardo connected to computer but not the pro micro. What do I have wrong about communication between these devices.(I get maybe every other key correctly on the computer but a also other keys or even function keys.)  Code for the "Master":
<!-- language-all: lang-cpp -->

    #include <PS2Keyboard.h>
    #include <Keyboard.h>

    const int DataPin = 8;
    const int IRQpin =  3;

    PS2Keyboard keyboard;

    void setup() {
      delay(1000);
      keyboard.begin(DataPin, IRQpin);
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial.println("Keyboard Test:");
    }

    void loop() {
      if (keyboard.available()) {

        // read the next key
        char c = keyboard.read();

        // check for some of the special keys
        if (c == PS2_ENTER) {
          Serial.println();
        } else if (c == PS2_TAB) {
          Serial.print("[Tab]");
        } else if (c == PS2_ESC) {
          Serial.print("[ESC]");
        } else if (c == PS2_PAGEDOWN) {
          Serial.print("[PgDn]");
        } else if (c == PS2_PAGEUP) {
          Serial.print("[PgUp]");
        } else if (c == PS2_LEFTARROW) {
          Serial.print("[Left]");
        } else if (c == PS2_RIGHTARROW) {
          Serial.print("[Right]");
        } else if (c == PS2_UPARROW) {
          Serial.print("[Up]");
        } else if (c == PS2_DOWNARROW) {
          Serial.print("[Down]");
        } else if (c == PS2_DELETE) {
          Serial.print("[Del]");
        } else if (c == PS2_F1) {
          Serial.print("[F1]");
          //Serial1.print("[F1 ]");
        } else {

          // otherwise, just print all normal characters
          Serial1.print(c);
        }
      }
    }

Code for the "Slave":

    #include <HID.h>
    #include <Keyboard.h>

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

    void loop(){
       if (Serial1.available() > 0) {
       // read incoming serial data:
       char c = Serial1.read();
       Keyboard.print(c);
      }
    }

title: PS2 Keyboard and sending keystrokes between a Leonardo and several pro micros

Answers: 0


body:
I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote.  When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:

    #include <EEPROM.h>
    #include <IRLib.h>
    #include <AFMotor.h>
    int frontlights = A1;
    int backlights = A2;
    int buzzer = A3;
    int pingPin = A4; //setup pingpin as A4

    //ir variables
    int RECV_PIN = A0;
    IRrecv My_Receiver(RECV_PIN);
    IRdecode My_Decoder;
    unsigned int Buffer[RAWBUF];

    void obstacle_avoiding(){
       while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

     motor4.setSpeed(230);
     motor3.setSpeed(230);
     motor2.setSpeed(230);
     motor1.setSpeed(230);

        long duration, inches, cm;

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      // The same pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);

      // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
      delay(90);

          if(cm>15){          // if an object is greater than 10cm move forward
          motor_forward();
          Serial.println("forward");
          digitalWrite(backlights, LOW);

          }

         else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
         {
          motor_stop();
          digitalWrite(frontlights, HIGH);
          digitalWrite(backlights, HIGH);
          digitalWrite(buzzer, HIGH);
          delay(200);
          digitalWrite(buzzer, LOW);
          delay(2000);
          motor_backward();
          digitalWrite(backlights, HIGH);
          Serial.println("backward");
          delay(500);
          motor_stop();
          digitalWrite(backlights, HIGH);
          delay(900);
          motor_right();
          digitalWrite(backlights, LOW);
          Serial.println("right");
          digitalWrite(frontlights, LOW);
          delay(400);

       }
       if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
       break;
       motor_stop();
       }
     }
    }

    void loop() {
       long duration, inches, cm;
        if (My_Receiver.GetResults(&My_Decoder)){
           //Restart the receiver so it can be capturing another code
           //while we are working on decoding this one.
           My_Receiver.resume();
           My_Decoder.decode();

        //automatic code here
                else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
                  obstacle_avoiding();

                }

              }

            }

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?

title: Infinite "while" statement

Answers: 2

body:
`My_Decoder.value` doesn't change inside `obstacle_avoiding()`. Hence, `while` is running infinitely.

I think you have to delete the `while`, and let `loop()` take care of controlling the execution.

**Addendum**

The intent of the `loop()` is to read some IR data in value. I under the impression that `getResults()` sometimes block, acording to this:

> However the IRrecvLoop is not interrupt driven and so when you call
> GetResults it sits in a tight loop and does not release control back
> to you until the complete signal has been received.

I also want to check that `value` doesn't change if `getResults()` return nothing with this `loop()`

    void loop() {
    bool r = My_Receiver.GetResults(&My_Decoder)
    Serial.print("getResults()=");
    Serial.print(r);
    Serial.print(" value=");
    Serial.println(My_Decoder.value);

    if (r) {
        //Restart the receiver so it can be capturing another code
        //while we are working on decoding this one.
        My_Receiver.resume();
        My_Decoder.decode();
    } else {
        if (My_Decoder.value == 0xFF807F && My_Decoder.value != 0xFF0AF5) {
            obstacle_avoiding();
            }
        }
    }

I hope this works!

body:
Copy/paste this part only:

    void loop() {
       long duration, inches, cm;
        if (My_Receiver.GetResults(&My_Decoder)){
           //Restart the receiver so it can be capturing another code
           //while we are working on decoding this one.
           My_Receiver.resume();
           My_Decoder.decode();
            }
        //automatic code here
               if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
                  obstacle_avoiding();

                }

              }

            }


body:
I'm relatively new at programming and many of the coding best practices I'm reading effectively state that there are very few good reasons to use a global variable (or that the best code has no globals at all).

I've done my best to keep this in mind, when writing software to make an Arduino interface with an SD card, talk to a computer and run a motor controller.

I currently have 46 globals for about 1100 lines of "beginner level," code (no line having more than one action). Is this a good ratio or should I look at reducing it more? Also what practices can I employ to reduce the number of globals further?

I'm asking this here because I'm specifically concerned with best practices for coding on Arduino products rather than computer programming in general.

title: Are global variables evil in Arduino?

Answers: 8

body:
They aren't *evil* per se, but they do tend to get overused where there is no good reason to use them.

There are plenty of times when global variables are advantageous. Especially since programming an Arduino is, under the hood, vastly different to programming a PC.

The biggest benefit to global variables is static allocation. Especially with large and complex variables such as class instances. Dynamic allocation (the use of `new` etc) is frowned upon due to lack of resources.

Also you don't get a single call tree like you do in a normal C program (single `main()` function calling other functions) - instead you effectively get two separate trees (`setup()` calling functions, then `loop()` calling functions), which means that sometimes global variables are the only way to achieve your goal (i.e., if you want to use it in both `setup()` and `loop()`).

So no, they're not evil, and on an Arduino they have more and better uses than on a PC.

body:
It's very difficult to give a definitive answer without seeing your
actual code.

Global variables are not evil, and they often make sense in an embedded
environment where you typically do a lot of hardware access. You have
only four UARTS, only one I2C port, etc. So it makes sense to use
globals for variables tied to specific hardware resources. And indeed,
the Arduino core library does that: `Serial`, `Serial1`, etc. are global
variables. Also, a variable representing the global state of the program
is typically a global.

> I currently have 46 globals for about 1100 lines of [code]. Is this a
> good ratio [...]

Is not about the numbers. The right question you should ask yourself is,
for each of these globals, whether it makes sense to have it in global
scope.

Still, 46 global seems a bit high to me. If some of these hold constant
values, qualify them as `const`: the compiler will usually optimize out
their storage. If any of those variables is only used inside a single
function, make it local. If you want its value to persist between calls
to the function, qualify it as `static`. You could also reduce the
number of “visible” globals by grouping variables together inside an
class, and having one global instance of this class. But only do so when
it makes sense to put stuff together. Making a big `GlobalStuff` class
for the sake of having only one global variable will not help make your
code clearer.

body:
As with everything (other than gotos which are truly evil) globals have their place.

e.g. If you have a debug serial port or a log file that you need be to able to write to from everywhere then it often makes sense to make it global. Similarly if you have some critical piece of system status information then making it global is often the easiest solution. There is no point in having a value that you have to pass to every single function in the program.

As others have said 46 seems a lot for only just over 1000 lines of code but without knowing the details of what you are doing it's hard to say if you are over using them or not.

However for every global ask yourself a few important questions:

Is the name clear and specific so that I don't accidentally try to use the same name somewhere else? If not change the name.

Does this need to ever change? If not then consider making it a const.

Does this need to be visible everywhere or is it only global so that the value is maintained between function calls? Is so consider making it local to the function and using the keyword static.

Will things really screw up badly if this gets changed by a piece of code when I'm not being careful? e.g. if you have two related variables, say name and ID number, that are global (see previous note on using global when you need some information almost everywhere) then if one of them gets changed without the other nasty things could happen. Yes you could just be careful but sometimes it's good to enforce carefulness a little. e.g put them in a different .c file and then define functions that set both of them at the same time and allow you to read them. You then only include the functions in the associated header file, that way the rest of your code can only access the variables through the defined functions and so can't mess things up. This is basically a pure c way of doing what a c++ class would allow but without having to learn how to define and create classes so you aren't learning too much at once.

-- update -- I just realized that you had asked about Arduino specific best practice rather than general coding and this is more of a general coding reply. But honestly there isn't much difference, good practice is good practice. The `startup()` and `loop()` structure of Arduino means that you have to use globals a little more than other platforms in some situations but that doesn't really change much, you always end up aiming for the best you can do within the limitations of the platform no matter what the platform is.

body:
Although I wouldn't use them when programming for a PC, for the Arduino they have some benefits. Most if it has already been said:

- No dynamic memory usage (creating gaps in the limited heap space of an Arduino)
- Available everywhere, thus no need to pass them as arguments (which costs stack space)

Also, in some cases, especially performance-wise it can be good to use global variables, instead of creating elements when needed:

- To decrease gaps in heap space
- Dynamically allocating and/or freeing memory can take substantial time
- Variables can be 'reused', like a list of elements of a global list that are used for multiple reasons, e.g. once as a buffer for the SD, and later as a temporary string buffer.

body:
The main issue with global variables is code maintenance. When reading a line of code, it is easy to find declaration of variables passed as parameter or declared locally. It is not so easy to find declaration of global variables (often it requires and IDE).

When you have many global variables (40 is already a lot), it becomes difficult to have an explicit name that is not too long. Using namespace is a way to clarify role of global variables.

A poor way to mimic namespaces in C is:

    static struct {
        int motor1, motor2;
        bool sensor;
    } arm;

On intel or arm processor, access to global variables is slower than other variables. It is probably the opposite on arduino.

body:
Are they evil? Maybe. The problem with globals is that they may be accessed and modified at any point in time by any function or piece of code being executed, without restrictions. This may lead to situations that are, let's say, difficult to trace back and explain. Minimizing the amount of globals, if possible bringing the amount back to zero, is therefore desirable.

Can they be avoided? Almost always yes. The problem with Arduino is, that they force you into this two function approach in which they assume you `setup()` and you `loop()`. In this particular case you have no access to the scope of the caller function of these two functions (probably `main()`). If you had, you would be able to rid yourself of all globals and use locals instead.

Picture the following:

    int main() {
      setup();

      while (true) {
        loop();
      }
      return 0;
    }

This is probably more or less what the main function of an Arduino program looks like. Variables you need in both the `setup()` and the `loop()` function would then preferably be declared inside the scope of the `main()` function rather than the global scope. They could then be made accessible to the two other functions by means of passing them as arguments (using pointers if necessary).

For example:

    int main() {
      int myVariable = 0;
      setup(&myVariable);

      while (true) {
        loop(&myVariable);
      }
      return 0;
    }

Note that in this case you also need to change the signature of both functions.

As this might not be feasible nor desirable, I see really only one way to remove most globals from an Arduino program without modifying the forced upon program structure.

If I recall correctly, you're perfectly able to use C++ while programming for Arduino, rather than C. If you're not familiar (yet) with [OOP (Object Oriented Programming)](https://en.wikipedia.org/wiki/Object-oriented_programming) or C++, it might take some getting used to and some reading.

My proposal would be to create a Program class and create a single global instance of this class. A class should be considered the blueprint for objects.

Consider the following example program:

    class Program {
    public:
      Program();

      void setup();
      void loop();

    private:
      int myFirstSampleVariable;
      int mySecondSampleVariable;
    };

    Program::Program() :
      myFirstSampleVariable(0),
      mySecondSampleVariable(0)
    {

    }

    void Program::setup() {
      // your setup code goes here
    }

    void Program::loop() {
      // your loop code goes here
    }

    Program program; // your single global

    void setup() {
      program.setup();
    }

    void loop() {
      program.loop();
    }

Voilà, we've rid ourselves of almost all globals. The functions in which you would start adding your application logic would be the `Program::setup()` and `Program::loop()` functions. These functions have access to the instance specific member variables `myFirstSampleVariable` and `mySecondSampleVariable` whereas the traditional `setup()` and `loop()` functions do not have access as these variables have been marked class private. This concept is called [data encapsulation](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)) or data hiding.

Teaching you OOP and/or C++ is a bit out of scope of the answer to this question so I'll stop here.

To summarize: globals should be avoided and it's almost always possible to drastically reduce the amount of globals. Also when you're programming for Arduino.

Most importantly I hope my answer is somewhat useful to you :)

body:
Global variables are never *evil*. A general rule against them is just a crutch to let you survive long enough to gain the experience to make better decisions.

What a global variable is, is an inherent assumption that there is only one of a thing (it doesn't matter if we're talking about a global array or map that might contain multiple things, that still contains the assumption that there is only *one* such list or mapping, and not multiple independent ones).

So before you make use of a global, you want to ask yourself: is it conceivable that I will ever want to use more than one of this thing? If it turns out to be true down the line, you will have to modify the code to un-globalize that thing, and you'll probably find out along the way that other parts of your code depend on that assumption of uniqueness, so you'll have to fix them as well, and the process becomes tedious and error-prone. "Don't use globals" is taught because usually it's a pretty small cost to avoid globals from the beginning, and it avoids the potential of having to pay a large cost later on.

But the simplifying assumptions that globals allow also make your code smaller, faster, and use less memory, because it doesn't have to pass around a notion of which thing it's using, doesn't have to do indirection, doesn't have to consider the possibility of the desired thing maybe not existing, etc. On embedded you're more likely to be constrained for code size and/or CPU time and/or memory than you are on a PC, so these savings can matter. And many embedded applications also have more rigidity in the requirements — you *know* that your chip only has one of a certain peripheral, the user can't just plug another one into a USB port or something.

Another common reason for wanting more than one of something that seems unique is testing — testing the interaction between two components is easier when you can just pass a testing instance of some component to a function, whereas trying to modify the behavior of a global component is a trickier proposition. But testing in the embedded world tends to be very different from elsewhere, so this may not apply to you. As far as I know, Arduino has no test culture whatsoever.

So go ahead and use globals when they seem worthwhile. The code police won't come and get you. Just know that the wrong choice could lead to a lot more work for you down the road, so if you're not sure...

body:
> Are Global Variables Evil in Arduino?

nothing is inherently evil, including global variables. I would characterize it as a "necessary evil" - it can make your life much easier but it should be approached with caution.

> Also what practices can I employ to reduce the number of globals further?

use wrapper functions to access your global variables. so you at least are managing it from the scope perspective.


body:
I try to change the brightness of an LED following the formular in out1. I'm pretty sure that something is going wrong because it doesn't really change its brightness and it never stops lightening. Can pleas somebody help me. It should basically do the same than a sin wave but instead of the sin I try to use my equation!

    const int LED = 11;
    const int LED1 = 10;
    const int LED2 = 9;

    void setup()
    {
    }

    void loop()
    {
    float in1, out1, out2, out3;

    for (in1 = 0; in1 < 10; in1++)
    {
    out1 = 8.8 * pow(10,-4) * pow(in1,4) - 0.0034 * pow(in1,3) +0.37* pow(in1,2) -6.7 *in1 +1.7 *pow(10,2);
    //out2 = 1.207*pow(in1,4)-0.0011*pow(in1,3)+0.16*pow(in1,2)-5.5*in1+2,0763;
    //out3 = 4.829*pow(in1,4)-0.034*pow(in1,3)+0.37*pow(in1,2)-6.7*in1+2,076;

    analogWrite(LED,out1);
    delay(10);
    //analogWrite(LED1,out2);
    //analogWrite(LED2,out3);

    }

    analogWrite(LED,LOW);

    /*analogWrite(LED,out1);
    analogWrite(LED1,out2);
    analogWrite(LED2,out3);
    //analogWrite(LED1,LOW);*/
    delay(500);

title: polynomial change of LED brightness arduino

Answers: 2

body:
Here is the proper way to implement a polynomial function. It's a direct
application of [Horner's
method](https://en.wikipedia.org/wiki/Horner's_method):

<!-- language-all: c++ -->

    // Polynomial function for output 1.
    static float f1(float x)
    {
        return (((8.8e-4 * x - 0.0034) * x + 0.37) * x - 6.7) * x + 1.7e2;
    }

You would use it like this:

    void loop()
    {
        for (int x = 0; x < 10; x++) {
            analogWrite(LED, f1(x));
            delay(10);
        }
        digitalWrite(LED, LOW);
        delay(500);
    }

body:
You should make sure that your code works with known good values for out1.

After dthat, try to make sure that your formula produce values in a valid range - check analogWrite to see what values it expects.

Then you should make sure that your code formula is what you want. Aka the code reflects your intent correctly.

edit: here is what I use to calculate polynomial functions.

    //return poly functions
    //x: independent variable
    //degree: degree of the polynomial function
    //p[]: array for the coefficients
    double poly(double x, int degree, double p[]) {
      double tmp=0;  //temp variable

      while (degree--) tmp = tmp * x + p[degree];

      return tmp;
    }

by providing different "degree" and "p[]/coef", you can calculate any polynomial function with one call to poly().

I generally use a set of macros to further simplify the calling to that function.


body:
I have two Arduino Uno and a few sets of transmitters and receivers. I followed some guide on the internet to make them work and that's what I did so far but I still get random values of 0 or 1 or 2, no matter what signals I am trasmitting.

I connected the receiver's VCC to 5v on Arduino; the receiver's data to A0 on the Arduino; the receiver's GND to the Arduino's GND.

I connected the transmitter's VCC to 5v on Arduino; the transmitter's data to  on Arduino; the transmitter's GND to the Arduino's GND.

This is the transmitter code:

    #define dataout 12
    #define ledPin 13
    unsigned int temp = 0;

    void setup() {
      pinMode(dataout, OUTPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {

      digitalWrite(dataout, HIGH);
      digitalWrite(ledPin, HIGH);
      delay(5000);
      digitalWrite(dataout,LOW);
      digitalWrite(ledPin, LOW);
      delay(5000);
    }

This is the recriver code:

    const int datain=A0;
    #define ledPin 13

    int temp = 0;
    const unsigned int upperThreshold = 500;
    const unsigned int lowerThreshold = 100;

    void setup() {
      pinMode(datain, INPUT);
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      temp=analogRead(datain);
      Serial.println(temp);
      delay(300);
      if(temp<lowerThreshold) {
        digitalWrite(ledPin, HIGH);
      }

      if(temp>upperThreshold) {
        digitalWrite(ledPin, LOW);
      }
    }

I tried to change the transmitter and receivers. I tried to change Arduino boards. I tried to change analog to digital, nothing worked...

Suggestions?

**Update:**

Here are some pictures of my gear:

[![Transmitter][1]][1]

[![Receiver][2]][2]

This is the output of the receiver when both Arduinos work near each other, there no sync between the signals transmitting and receiving.

> 0 1 0 0 0 0 1 1 0 2 1 2 1 0 1 362 0 1 1 1 1 1 0 2 0 314 2 2 1 0 0 2 1
> 0 1 2 1 1 2 0 1 1 0 1 1 2 1 0 0 0 0 2 1 0 1 0 0 1 0 1 0 1 1 1 2 2 1 1
> 2 1 1 1 1 1 0 211 2 0 2 0 0 1 2 0 0 759 1 2 1 1 2 1 2 0 1 16 0 0 1 1 0
> 0 2 1 1 0 1 2 1 2 0 2 1 0 2 0 1 2 1 1 2 2 1 2 0 0 1 0 1 1 2

This is the output when I tried to disconnect the GND and VCC from the receiver:

> 433 426 431 422 379 367 362 394 405 412 406 394 399 388 356 258 193
> 438 507 507 499 486 478 473 449 442 431 428 427 424 425 423 422 419
> 417 414 413 413 409 410

  [1]: https://i.stack.imgur.com/Dc2Ad.jpg
  [2]: https://i.stack.imgur.com/GUP5T.jpg

title: 433Mhz receiver only get values of 0, 1, 2

Answers: 1

body:
Those cheap 433 MHz RF modules require a (good) library to work. The VirtualWire/RadioHead library is the best.

The [VirtualWire][1] library it outdated, but still used.

The [RadioHead][2] library has a few bugs fixed, but uses more memory.
Use it in RH_ASK mode, see the included 'ask' examples.

[**Update: better quality**]
Most cheap 433 MHz ASK transmitters work with 3.5 to 12V. They have the longest range at 12V. About 20 meters is no problem with 5V, but if longer range is needed then transmitters that are only made for 5V are better.
The cheap 433 MHz receivers use a coil to tune the frequency. They are very sensitive and they do work well. However, when such a module is placed near metal or close to the Arduino, the frequency might change. Modules that use a crystal for the frequency are better. Sometimes a sensitivity is mentioned (for example -112dBm) but I don't know how reliable that is. When an antenna of 16 cm does not work well, try an antenna of more than a meter.

The transceivers are better for wireless data transfer, but that depends on the use.
Sparkfun has [Wireless Buying Guide][3].
[RadioHead][2] has a list of supported transceivers.

The nRF24L01+ are very cheap. I read that every one of them on Ebay or Aliexpress is counterfeit, but the counterfeit chips do work. They work at 3.3V, and are 5V tolerant.

The CC1101, CC2500 and so on are good, but not often used with an Arduino. The same for Si4432, Si4436 and so on. If you know a good library, they are very good transceiver chips.

Adafruit is using the RFM69 a lot. For example the [Feather Packet Radio board][4].

Last but not least: don't forget Wifi and Bluetooth.

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire/
  [2]: http://www.airspayce.com/mikem/arduino/RadioHead/
  [3]: https://www.sparkfun.com/pages/wireless_guide
  [4]: https://www.adafruit.com/product/3176


body:
I am trying to make a menu for a monitoring/control system.  I am not sure how to make this without interrupting my current code which needs to be monitoring my system at all times to shut off if it reads overload. It is mostly `swtich ()` and `case x:` stuff. I have looked into attachInteruupt and rotary encoder examples, but none have really helped me figure out how to display a multiple layer menu where I can select to see the system readings as well as edit outputs.

There are a lot of posts here on rotary encoders with LCDs, but I can't seem to find a good skeleton menu code that works well and uses current libraries.  My biggest problem right now is making the menu layers without interrupting my monitoring code running in the background.

title: Rotary encoder I2C LCD menu

Answers: 1

body:
you might want to consider timed routines or interrupts.

For timers https://playground.arduino.cc/Code/Timer1 or similar can help.

When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.

About menus there are several, most of them dynamic and some requiring user display + nav code.

This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

- (-) you can not change menu at runtime (however it support value fields)
- (+) requires no user code base
- (-) setup involves several parts (inputs/output)
- (+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
- (+) supports a lot of display devices, including i2c lcd
- (+) supports encoder (interrupts (PCINT) or timed driver)
- (-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.


body:
I'm currently building my own Home Automation System with a bunch of Arduinos and Relais, all of them wired to Ethernet "Shields". The casing I am printing on a 3D printer.

The Arduinos work great with those Ethernet "Shields", but the [ENC28J60][1] chip on those Ethernet boards get quite hot. I am measuring 79.5°C approx.
In the plastic casing, I expect that they reach higher temperatures (because it's closed and has no ventilation whatsoever).

[![enter image description here][2]][2]

Since I am building this as a permanent solution (House wiring is now all newly adapted and I have no way back), which lifespan can I expect from those Ethernet boards?

The datasheet of that chip is saying that it's rated up to 85°C, but what does this upper rating mean? Will it stop working at this point, or only begin to degrade it's lifetime at this point?

EDIT: I have no space to put a dissipation block on those chips, because the casing is so tight.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/39662c.pdf
  [2]: https://i.stack.imgur.com/U2I5g.jpg

title: Lifespan of a hot microchip

Answers: 1

body:
The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.

That should give you some sense as to what to expect.


body:
I've been doing some Googling for GSM shields and their prices and frankly I don't understand why they are so expensive on average.

The [official one sold by Arduino](https://store.arduino.cc/arduino-gsm-shield-2-integrated-antenna) is 71 euros for me (I live in Europe), and third party ones have similar prices.

A cheap dumb-phone is usually 30 euros and those phones have become really impressive these days, they have even a camera. When they are locked with the carrier the price can go as low as 20 euros. How is it even possible that a single part of what is supposed to make up a phone is more expensive than the phone itself? :(

Thanks in advance!

title: Why is the GSM shield so expensive?

Answers: 1

body:
If you are ready to wait a month for delivery and also giving up flexibility by restricting yourself to just sending and receiving SMS, then you can go as low as €2 for a DIY kit on [AliExpress](https://www.aliexpress.com/item/1pcs-DIY-KIT-GSM-GPRS-900-1800-MHz-Short-Message-Service-SMS-module-for-project-for/32786741769.html).

By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".


body:
I am a Python programmer and want to learn Arduino programming so want to know what are the main differences between Python and Arduino C++ programming?

Is Arduino C++ more complex than Python programming?
Are there any similarities that will help me?
Are there any formatting  restrictions like in Python?
Etc...

According to [this page(printing hello)](https://www.arduino.cc/en/Tutorial/HelloWorld), Aurdino programming looks easy to me.

title: What is the difference between python and arduino programming?

Answers: 1

body:
Arduino uses a language that is derived from Processing, which looks like C++.

Python is a different language, although both have similarities (both Object Oriented for example).

What is 'complex' depends on what your background is. C++ is in general more complex than Arduino, but most people using Arduino program in C++, so most examples can be found in C++, which makes support from other users easier.

If you are new to programming, I suggest using the 'standard' Arduino IDE.

To be complete, Arduino is not a programming language, it is a platform. In general, every language can be used to write Arduino code, but only a few have compilers for creating Arduino (machine) code.


body:
![enter image description here](https://i.stack.imgur.com/p9A7x.jpg)

As you may can I see on the picture. I try to display the word "goodbye". Yet the problem is that the cursor positions are to bright. I hooked up a 10k ohm potmeter to the Anode. To change the backlight. Is there a way to make the cursos positions less visible?

Kind Regards,

Q

title: Very bright cursos positions

Answers: 1

body:
issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).

Look at the conversation between me and Majenko to see the realisation.


body:
I'm trying to get my NodeMCU v1.0 board to read from a load cell connected to a HX711 amplifier and send the data through Wifi to Thinger.io. I managed to make the readings from HX711, works perfectly. I also managed to send data to Thinger.io separately (ran the example without problems). However putting these together just doesn't work for me, the board soft resets:

    [NETWORK] Starting connection...
    [NETWORK] Connecting to network xxxxxxx

    Soft WDT reset

    ctx: cont
    sp: 3fff0c60 end: 3fff0ec0 offset: 01b0

    >>>stack>>>
    3fff0e10:  4021e91f 00000001 3ffefe64 3ffefd48
    3fff0e20:  3fff18dc 40203d38 3ffefe64 40203f0c
    3fff0e30:  3ffe8e7f 3ffefcd8 3ffefe64 402023fc
    3fff0e40:  3ffe8e81 00000015 3ffefe64 402051c0
    3fff0e50:  00005173 3ffefcd8 3ffefe64 402051e4
    3fff0e60:  3fffdad0 3ffefcd8 3ffefe64 3ffefe90
    3fff0e70:  3fffdad0 00000001 3ffefcd8 402034b9
    3fff0e80:  feefeffe 3ffefcd8 3ffefe88 40203768
    3fff0e90:  3fffdad0 00000000 3ffefe88 402037e0
    3fff0ea0:  feefeffe feefeffe feefeffe 40205824
    3fff0eb0:  feefeffe feefeffe 3ffefea0 40100718
    <<<stack<<<

     ets Jan  8 2013,rst cause:2, boot mode:(1,6)

     ets Jan  8 2013,rst cause:4, boot mode:(1,6)

    wdt reset

And if I wrap the thing.handle(); with

      ESP.wdtDisable();
      thing.handle();
      ESP.wdtEnable(0);

Then I get hard reset after few seconds.

This is minimal code where I reproduce the issue:

    #define _DEBUG_

    #include <HX711.h>
    #include <ESP8266WiFi.h>
    #include <ThingerESP8266.h>

    #define USERNAME "zink"
    #define DEVICE_ID "xxxxxxxx"
    #define DEVICE_CREDENTIAL "xxxxxxxxx"

    #define SSID "xxxxx"
    #define PASSWORD "xxxxxx"

    ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

    HX711 scale;

    void setup() {
      // put your setup code here, to run once:
      thing.add_wifi(SSID, PASSWORD);
      scale.begin(D6, D5);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      thing.handle();
    }

While this sketch works perfectly:

    #define _DEBUG_

    #include <ESP8266WiFi.h>
    #include <ThingerESP8266.h>

    #define USERNAME "zink"
    #define DEVICE_ID "xxxxxx"
    #define DEVICE_CREDENTIAL "xxxxxxx"

    #define SSID "xxxxxxx"
    #define PASSWORD "xxxxxxx"

    ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

    void setup() {
      // put your setup code here, to run once:
      thing.add_wifi(SSID, PASSWORD);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      thing.handle();
    }

And also this one:

    #include <HX711.h>

    HX711 scale;

    void setup() {
      // put your setup code here, to run once:
      scale.begin(D6, D5);
    }

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

But combining them triggers a soft reset. What am I doing wrong here?

title: Using Thinger.io Wifi together with HX711 library soft resets ESP8266 (NodeMCU)

Answers: 1

body:
When an ESP resets its usually a segmentation fault.  The first area I would look at is string manipulation, but you aren't doing any.  So maybe reversing the order of:

    thing.add_wifi(SSID, PASSWORD);
    scale.begin(D6, D5);

might stop it, but it will only be temporary.

If it isn't you, and I can't see anything in your code that would cause it, then it must be the libraries.  I think you will have to sit down and look at those two functions and see if you can see any string manipulation that might be causing it.

My money (£1) is on the `add_wifi` function and the cause being because it wants variables passing to it rather than `#defines`, but that's just a pure guess.