text:
Arduino Mega, 6 push buttons for each analog input (A0-A9) - closing one results in reading by other
On day to day basis I'm more of a high level programmer, with little electronics knowledge, apologies in advance if I lack some nomenclature or basics. I communicate with my Arduino Mega via firmata, so won't really bother with code as I believe my issue is 100% hardware issue (if proven wrong I'll share details surely)
I'm creating a 'keyboard' with 60 arcade style push buttons (2pin), and I distinguish them by different resistance when circuit closes with A0-A9 (10 analog pins, 6 buttons each), and I need the rest of the pins for other functionalities.
I've created a circuit similar to this fritzting schema:

So my issue is: when press button A0/button 1, pins A1 & A2 also read the same value. If I press A0/button 2, I get a different value and can determine which button in A0 was pressed, but again - A1 & A2 also read this, even though I didn't press them.
I suspect I might've taken a different approach or even out of the box "keyboard" chips, but this is the route I've taken.

How do I make it so when I press A0/button 1, A1/A2 doesn't read the value? Do I need separate V5? Or I simply need to put the wires differently somehow?
Update: as per chrisl comment
I've updated the circuit by adding a resistor for each button group:

And that has solved my issue.

why are you using analog inputs?

To be able to use a single pin for multiple button press detection, and I do it so by reading analog value. Each button will show different value upon press because it has a different amount of resistors. Overall very similar to this: https://www.youtube.com/watch?v=Y23vMfynUJ0&ab_channel=MichaelKlements

your approach does not allow multiple buttons to be pressed simultaneously

yes, I'm aware of that caveat but this is not a concern for me, I don't really need this functionality

Of course all three analog inputs show the same value. You have literally connected them to each other. Each green wire is connected to a red wire, which leads to the resistor at the bottom. Thus all three inputs are tied together.
You can fix this by using one bottom resistor for each group of 2 buttons, each connected between 5V and the analog input/button system.
And when using analog inputs for multiple buttons the binary resistor latter is an interesting concept, which might give you more buttons per analog input (depending on the noise in your environment). Though the typical way to read so many buttons would be using an additional chip/microcontroller to scan the buttons in a matrix style arrangement. With your current circuit you still need 30 analog inputs.

I'll try to add a resistor between each analog input and 5v as suggested - thanks! This is where my lack of knowledge peaks. Will
come back later and update. The fritzting circuit is simplified - I have 6 buttons connected to each analog input, and I'm using 10 of those - so I would expect to cover 60 (10x6)? Or is that not the case? And thanks for sharing the usual go-to way of handling those kind of challenges.

I've updated my answer with the latest fritzting / source file as well. I pontetially missed the point or have some other issue, but even with resistor in between each of A0-A2 and 5V the result is still the same. Appreciate your time nonetheless.

@wopolow Your circuit looks correct, except for the rightmost two buttons. They aren't connected as the others. Are you sure, that your real life circuit is correct? And have you tested if measuring on analog input via firmata works as expected? You could use a multimeter to test the voltage on each analog input manually to check, if the circuit works as expected. Maybe it would be good to first build a test circuit on a breadboard instead of directly going to the real project setup.

Thanks, I did, I just failed at execution on a later stage. Having separate resistors was the answer to my question. Thank you sir.


text:
Erratic behavior in String based functions
I've been working on a cipher based project, and I wanted to prep the encrypted string for use with the RF24 library. Since the payload size for the RF24 module is 32 bytes, I wanted to stick with that size permanently. The key number (against which the encryption keys are stored) has to be embedded at the end of the char array, and I was converting it to a char to embed. To make the message up to 31 bytes if it was smaller than 31 bytes, I am padding with zeroes.
The cipher functions themselves (namely loadInput(), cipherText() and originalText()), work perfectly; I have tested these by themselves numerous times.
However, the other two functions I wrote for padding and de-padding are behaving erratically.
My code:
const String keys[] = {
"TTZUZRZJHP",
"SUENIFKGAT",
"CEXGWKMCVQ",
"SIACAKRFM",
"CSMKSWSNLH",
"IPIJWROJBB",
"SZSGAMYJGJ",
"BIHLBNUIJS",
"UTFGSQAISS",
"SSPXJXURJV",
"XPDRYPOFAC",
"DROIFANPZE",
"DKTZXUQLAM",
"UDHAWMAJTG",
"HKTQMEPWXS",
"IRUQAHZSBP",
"ZHZAAGTMTN",
"EHORTISSLQ",
"NYZZQALWTP",
"PEEGDJLQLQ",
"UNQGHTXFSG",
"NOBSTVFLAX",
"GQJYEVUNCX",
"UTJDNOCLSP",
"XQNGBDOBEN",
"FURHLIZSIN",
"AAAPEIGRHI",
"QWQFCCVFPV",
"KZEFJHUJWB",
"NDJNLHURJO"
};

char readyToSend[32]; //global array, which is to be transmitted via RF24
char recieved[32]; // global array, which is to be recieved via RF24
int keyRecieved; //global key number, which is to be embedded as the last char recieved[]

String loadInput() { //this functions takes the input string and checks it's validity
  bool isValid = true;
  String(inputStr);
  do {
    Serial.println("Enter valid input. Only enter ALPHABETIC characters. ONLY 31 CHARS MAX.");
    Serial.println("Whitespaces are valid but commas and fullstops are not");
    while (Serial.available () == 0) {}
    inputStr = Serial.readString();
    int inputLength = inputStr.length();

    for (int i=0; i<inputLength; i++) {
      if (inputLength>31) {
        Serial.println("Input longer than 31 chars.");
        isValid = false;
        break;
      } else if (inputStr[i] > 95 && inputStr[i] < 123) {
        inputStr[i] -= 32;
      } else if (isWhitespace(inputStr[i])) {
      } else if (!isAlpha(inputStr[i])) {
        isValid = false;
        break;
      }
    }
  } while (isValid == true);

  inputStr.remove((inputStr.length()-2), 2);
  return inputStr;
}

String cipherText(String str,const String key) { //this function encrypts the message, and returns the encrypted version
  String cipher_text;
  for (int i=0; i<str.length(); i++) {
    if (isWhitespace(str[i])) {
      cipher_text += ' ';
    } else {
      char x = (str[i] + key[i%key.length()]) %26;
      x += 'A';
      cipher_text += x;
    }
  }
  Serial.println(cipher_text);
  return cipher_text;
}

String originalText( String cipher_text,const String key) { //this function decrypts the message, and returns the decrypted version
  String orig_text;

  for (int i=0 ; i<cipher_text.length(); i++) {
    if (isWhitespace(cipher_text[i])) {
      orig_text += ' ';
    } else {
      // converting in range 0-25
      char x = (cipher_text[i] - key[i%key.length()] + 26) %26;
      // convert into alphabets(ASCII)
      x += 'A';
      orig_text += x;
    }
  }
  return orig_text;
}

void prepForTransmit(String input, int keyNumber) { //this function makes pads the string upto 31 with '0', then embeds key
  input.toCharArray(readyToSend, 32);
  int zeroesStart = input.length();

  for (int i=zeroesStart; i<32; i++) {
    readyToSend[i] = '0';
  }

  char keyNumberAsChar = (char)(keyNumber + 65);
  readyToSend[31] = keyNumberAsChar;
  return;
}

String PrepForDecode() { //this function makes exctracts key, then removes padding
  keyRecieved = (recieved[31] - 65);
  String toEdit = String(recieved);
  toEdit.remove(31, 1);

  if (toEdit.indexOf('0') != -1) {
    toEdit.remove(toEdit.indexOf('0'), (31-toEdit.indexOf('0')));
  } else {
  }
  return toEdit;
}

void setup() { // TEST CODE
  Serial.begin(9600);
  randomSeed(analogRead(A0)); //SEED RANDOM FUNCTION
  String(text) = loadInput(); //GET INPUT
  Serial.println(text); //PRINT INPUT      <--------------------------------------
  int keynumber = random(25); //              |
  String encrypted_message = cipherText( text, keys[keynumber]);  //ENCRYPT THIs _|
  Serial.println("Using key number ");
  Serial.println(keynumber);

  prepForTransmit(encrypted_message, keynumber); // PADDING AND ADD KEYNUMBER
  Serial.println("Message to trasmit through radio is: ");
  Serial.println(readyToSend);  // PRINT PREPPED CHAR ARRAY
  for (int i=0; i<32; i++) {
    recieved[i] = readyToSend[i]; // COPY PREPPED ARRAY TO EMULATE RECEPTION FROM RADIO
  }
  String toDecode = PrepForDecode(); // PREP RECIEVED STRING FOR DECODING (REMOVE PADDING, EXTRACT KEY)

  Serial.println(originalText( toDecode , keys[keyRecieved])); // PRINT DECODED STRING
}

void loop() { //main program

My serial output:
22:18:59.596 -> Whitespaces are valid but commas and fullstops are not
22:19:08.255 -> THIS PROJECT IS A MESS
22:19:08.290 -> LPIU ZITVWKT IC F EMSU
22:19:08.325 -> Using key number
22:19:08.325 -> 3
22:19:08.325 -> Message to trasmit through radio is:
22:19:08.393 -> LPIU ZITVWKT IC F EMSU000000000D⸮!
22:19:08.428 -> THIS PROJECT IS A MESSLFRP HATTWAC WK F ECBP>8BJHJ@9ER:3

"LPIU ZITVWKT IC F EMSU000000000D⸮!" is very unexpected, since there should only be 32 chars, and here there are 34.
Furthermore, the behavior here: "THIS PROJECT IS A MESSLFRP HATTWAC WK F ECBP>8BJHJ@9ER:3" is something I absolutely cannot understand.
I am baffled, and I would really appreciate help. I apologize in advance if the error is something small or stupid, but I cannot understand what's going on here.

Two words: "Null termination". You haven't terminated your strings properly.

@Majenko I thought converting from char array to String meant it was automatically null terminated? And the reason I have been using char arrays is to not have to deal with the null termination char.

@Majenko You were right! Apparently the String constructor doesn't handle the null termination with a char array input. Null terminating the string fixed the problem! Thank you!

Well, there isn't actually a String constructor for an array of char. There's one for a pointer to const char, which is completely unaware of the size of the array that the pointer was formed from.

@timemage I didn't know that. Thank you! I'm sure someone else who's found himself in a corner like me will find this useful!

why store literals as String classes instead of cstrings? seems unnecessary....

source: Stack Exchange

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

sort: votes


text:
Where is the digitalPinToInterrupt macro defined
I am new to Arduino, and it's confusing to me how you can just write code in the IDE and use functions or macros such as #define ISR() in the avr-libc library without having to include the header file in the Arduino sketch.
I was trying to find where digitalPinToInterrupt() is defined, but had no luck. Any idea?

Looked at Arduino.h?

https://arduino.github.io/arduino-cli/latest/sketch-build-process/

Generally, if you want to find identifiers in your Arduino board support, you can run the ctags program on the libc and Arduino core files.  ctags is used as part of the build process in its effort to generate C++ declarations for you.  So it is generally available to you as an Arduino user.  You should find ctags or ctags.exe in:

/path/to/arduino15/builtin/tools/ctags/version-number/

This can be run against your board support in:

/path/to/arduino15/packages/vendor/hardware/architecture/version-number/

And your standard libraries found under directories in the form of:

/path/to/arduino15/packages/vendor/tools/compiler-tool/version-number/

If you're wondering what /path/to/arduino15/ would be on your system, it's documented here in terms of where the preferences file is stored.  The relevant paths containing and version numbers and architecture names should show in the verify/compile output when verbose mode is turned on in preferences.
Specific example
On my linux system with reasonably current versions of UNO-related things, my command-line would look like:
~/.arduino15/packages/builtin/tools/ctags/5.8-arduino11/ctags \
    -f /tmp/output-file \
    -R \
     ~/.arduino15/packages/arduino/hardware/avr/1.8.3/ \
    ~/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/avr/include/

The resulting tag file can then greped or just opened and the following entries can be found, showing the filenames and line numbers to investigate:
DigitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/circuitplay32u4/pins_arduino.h   138;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/ethernet/pins_arduino.h  79;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/gemma/pins_arduino.h 64;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/leonardo/pins_arduino.h  160;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/mega/pins_arduino.h  110;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_control/pins_arduino.h 120;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_motor/pins_arduino.h   115;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/standard/pins_arduino.h  79;"    d

In the case of an UNO the standard variant is the significant declaration.

There are different implementations of ctags.  The one used by the Arduino support files is Exuberant CTAGS and you may want to read its documentation, to learn how to control the program to display differently to only search for specific identifiers, etc.  It is also typically used with editors that have some special support for the resulting tags file, to jump to definitions, like an IDE would.

By the way, I just noticed your atmega2560 tag.  The generic instructions should cover this anyway, but: You'd be looking at the mega variant, which indicates this file and line.

If you like to tinker with the files. Than platformio is great option to go with. It provides auto completion and much more advance functionality.
You can easy see where some function/mecro is defined, by just right click on the function than click on the "Go to definition" option.

The file that contains the definition will be opened in the new tab. As for your current Macro check the image below

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


text:
Adafruit OLED 7-pin display - Abbreviations
I can't remember for the life of me how exactly I set up this screen in previous models, partially because the references I'm using in my code have different names from the pins on the Adafruit display.
My code identifies the following digital pins for the following display pins:
OLED_MOSI = 12
OLED_CLK = 11
OLED_DC = 10
OLED_CS = 8
OLED_RESET = 9

My Arduino is then attached from the following pins to those labelled on the OLED display as:
12 -> SDA
11 -> SCK
10 -> DC
8 -> CS
9 -> RES
5V -> VDD
GND -> GND

In other words, I am interpreting the following as being equivalent:
RES = RESET
SCK = SCK
MOSI = SDA

Is there anything within the information I've provided that is wrong or may cause the screen to malfunction?

From what I can see, your code expects an SPI display but your display has an I2C pinout. You should either use I2C in your code or convert your OLED display to SPI (some displays allow that with relatively simple modifications). Otherwise, it's probably not going to work.

@StarCat It is common for chinese displays to use SCK and SDA for "4 wire" serial's Clock and Data (SPI SCK and MOSI). The presence of DC attests to that.

@Majenko, you’re probably right (and I might have seen these confusingly labeled displays myself) but the display in question is from Adafruit which I kind of hold to a higher standard. The documentation should make it clear.

If it's SSD1306 then that's what the documentation calls them.

@Tyler Wallentine: why don't you give us the Adafruit product number of this display? @ Majenko: the SSD1306 can be 'programmed' to any of 5 different interfaces/protocols: I2C, 6800 parallel, 8080 parallel, 3 wire serial and 4 wire serial (datasheet: https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf).

DC selects between Data and Commands.
CS is the Chip Select
SDA is the Serial DAta.
SCL is the Serial CLock.

These four together form what the documentation calls the "4-wire serial interface". It's not quite like SPI, owing to the presence of the DC pin (which is why it doesn't use SPI terminology), but close enough that SPI can be used to communicate with it.
In SPI the pin that sends data from the Arduino to the slave is known as the MOSI - Master Out Slave In.  Some microcontrollers also call this SDO - Serial Data Out, where it's "out from the master's perspective".


text:
How to implementing timer interrupt with a sensor device using A0 and A1 pins
I was wondering if there is a way to program a timer interrupt to collect sensor data at a specific sampling rate?
I want to attach two strain gauge sensors to A0 and A1 pins and collect the data at a 20Hz sampling frequency using a timer interupt on an Arduino Uno. Please, let me know if this is possible, or if there is something else I can do.

you could just watch millis(), and read A0 and A1 when 20 ms elapses  ... if you still want to use an interrupt, then set a flag in the ISR ... check the flag in loop() and take readings when flag is set ... both ways are very similar

see the BlinkWithoutDelay example and convert it to 'ReadWithoutDelay'

If you need cycle-accurate timings, you can configure the ADC to be triggered by a timer event (not an interrupt, just the event). Then you would use the ADC interrupt to retrieve the result. This requires studying the datasheet and diving into the intricate details of the hardware. If you do not care about sub-millisecond inaccuracies, timing with micros() à la “Blink without delay” will be good enough and way easier.

Do the two reading need to be at (almost) the same time, or is it also acceptable to sample a 40Hz, and alternate between A0 and A1?

Thanks to all of you for the respond,


text:
ESP8266: system_adc_read_fast() always gives 1024 as output
I need to use system_adc_read_fast (uint16 *adc_addr, uint16 adc_num, uint8 adc_clk_div) to get a sampling rate close to 100 ksps. I am able to achieve that using adc_clk_div = 32.
However, when I print out the values stored in adc_addr, I always get 1024. Why is this?
I have a NodeMCU v3. I have connected an electret microphone to it. The +ve terminal is connected to 3.3 V through 10 kΩ; GND is connected to GND. The +ve terminal is connected to A0 on NodeMCU.

simulate this circuit – Schematic created using CircuitLab
It works fine when I use system_adc_read() (except the sampling rate is then 10 ksps which is not desirable).
Sketch:
// Expose Espressif SDK functionality - wrapped in ifdef so that it still
// compiles on other platforms
#ifdef ESP8266
    extern "C" {
        #include "user_interface.h"
    }
#endif

ADC_MODE(ADC_TOUT);

#define num_samples 512
uint16_t adc_addr[num_samples]; // point to the address of ADC continuously fast sampling output
uint16_t adc_num = num_samples; // sampling number of ADC continuously fast sampling, range [1, 65535]
uint8_t adc_clk_div = 32; // ADC working clock = 80M/adc_clk_div, range [8, 32], the recommended value is 8

int i = 0;
unsigned long start = 0;
unsigned long total = 0;
unsigned long tim = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
}

void loop() {
    // put your main code here, to run repeatedly:
    #ifdef ESP8266
        // Serial.println(system_get_sdk_version());

        wifi_set_opmode(NULL_MODE);
        system_soft_wdt_stop();
        ets_intr_lock( ); //close interrupt
        noInterrupts();

        start = micros();

        // Serial.println(system_adc_read());
        system_adc_read_fast(adc_addr, adc_num, adc_clk_div);

        unsigned int tot = micros() - start;

        interrupts();
        ets_intr_unlock(); //open interrupt
        system_soft_wdt_restart();

        tim += tot;
        total += num_samples * 1000000.0 / tot;
        i++;

        for (int j=0; j<adc_num;  j++) {
            Serial.println(adc_addr[j]);
        }

        if (i == 100) {
            // Serial.print("Sampling rate: ");
            // Serial.println(total / 100);
            // Serial.print("It lasted: ");
            // Serial.println(tim / 100);

            i = 0;
            tim = 0;
            total = 0;
        }
    #endif
}

Please add a schematic of your wiring: the behaviour you are describing doesn't look correct

the analog pin input range is 0-1.0v - perhaps your circuit results in voltage always > 1?

The ADC works fine when I use system_adc_read(). So, I'm sure the voltage is < 1.

max value of adc_clk_div is 23

I created a test circuit using an AC transformer to produce a 50 cycles / second sine wave signal and tried a number of variations on the system_adc_read_fast sample program in the Espressif SDK manual "2C-ESP8266_Non_OS_SDK_API_Reference__EN".
The ESP8266 ADC returned realistic values for adc_clk_div = 8 and 16, but, as you found, the values returned were always 1024 when I tried 32.
I found that the ADC unit was capable of performing ADC conversions in about 6-10 microseconds...
In a test program to collect data for a 40 millisecond period (ie two complete sine waves - I used a diode to chop off the negative halves) I called the system_adc_read_fast function 40 times collecting 116 samples in each call (using "number of samples" = 116).
I collected all the readings in a two-dimensional array before printing any values because the Serial.print function causes long delays between calls to the ADC converter. The "gaps" in the chart represent the changes in the sine wave signal between successive calls to the ADC read function.

Wow! Thanks dude. This is awesome. I've been able to verify this myself. Don't know why I missed this in the first place!? Again, thank you so much.

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


text:
CH34x board fails with avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 Atemel Mega328P AU1640
I have been given a board(Atmel ATmega328P-AU 1640) to program. I googled and found category of board Arduino Uno/ CH34x-based clone.
But when I program an empty program:
void setup() {
  // put your setup code here, to run once:

}

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

}

I get this error:
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

These are all the ports that are available to me. I have connected my Arduino with one of the USB ports on my Macbook running MacOS Sierra

Because I was told @PeterJ I might be wrong

that's the only port available. Hey, I see this is Atmel's board....Do I need Atmel Software to code it? I'm not an electronics guy. Please fix(edit) this question if wrong

yes I can edit the question

check now @uhours

Why do you have the ICSP header coming off the bottom of the board?

The board is an Arduino Nano clone, not an Uno.

Plug the Nano's USB cable into your computer.
Download and install the CH340 driver from here: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
In the Arduino IDE, select the port of your Nano from the Tools > Port menu.
Tools > Board > Arduino Nano
Sketch > Upload

If the port of your Nano doesn't appear in the Tools > Port menu (and no, dev/cu.Bluetooth-Incoming-Port is not the correct port) then you may have a damaged or charge-only USB cable. Try using a known-good cable or verify that your cable works for data on another device. If you have it plugged into a USB 3.0 port on your computer then try a USB 2.0 port instead.

Yes usb 3.0 doesn't work I'll try with 2.0

You have an Arduino nano clone using a CH340G chip for serial communication. You to down load and install a driver for your computer to recognize it. I don't use OSX, so there's not one I can recommend.

tell me for Windows

I also have windows installed in Bootcamp

I have installed both CH340G & CH341G but still, no other USB ports are showing except Bluetooth one

Sorry, I use Linux, and have the driver built in. If it's still not showing up, you either did it wrong, or the device is damaged.

That looks like a clone of an Arduino Nano to me, with a CH340G chip as the USB interface chip.  You need to:

Install the CH340G drivers
Ensure that the ATMega328PU chip has a bootloader installed on it

The last Nano I bought from China didn't have a bootloader installed. There are many tutorials online for teaching you how to install the bootloader using another Arduino as the programmer.

can you post some links how to fix bootloader on MacOS? Also I have already installed CH340G. I saw a youtube video but it's still no showing me other ports. Please confirm what board category should I select thanks :)

how to check if bootloader installed on it or not....please provide me with some direction. I've no experience with electronics & Arduino stuff @Majenko

The led L should blink rapidly a few times when you press the reset button.

Try this instructions from install driver. https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
Installation with Homebrew-Cask.
Then try this, and all work fine  ;)
http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/

Please don't post URL answers, write the gist of it and refer to the URL.

Remove the old driver by issuing one of the following commands (depending on your installation):

sudo rm -rf /System/Library/Extensions/usb.kext
sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.
Install with Homebrew-Cask
Install the driver by the following commands

brew tap mengbo/ch340g-ch34g-ch34x-mac-os-x-driver https://github.com/mengbo/ch340g-ch34g-ch34x-mac-os-x-driver
brew cask install wch-ch34x-usb-serial-driver

Restart your Mac.
Try upload some code in your Arduino.
In some cases the board might still not work.
This is because there is no bootloader installed on the Atmel microcontroller ship. To solve this problem we need a working Arduino and the clone Arduino we want to fix.
![Make an ISP Programmer From Your Working Arduino
]1
First we connect the working Arduino to our computer and open the Arduino IDE.
We go to File -> Examples and click ArduinoISP and upload this to the Arduino. Ones uploaded disconnect the Arduino.
**
Connecting the Wires
**

Next we connect the wires from the working Arduino to the clone as follows.
Without 10 uF capacitor.
Go to Tools -> Board and select the chinese board that is not working. in my case it's an Arduino Genius/Uno
Next we go to Tools again -> Programmer and select Arduino as ISP.
Go to Tools again and select "Burn Bootloader".
Go back to Tools -> Programmer and set back to ArduinoISP.
Your clone should work just fine now. ;)


text:
Reading analog signal from digital pin #6
Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?
According to the ATMega datasheet, this should be possible.
If yes how is it done ? (pin configuration)

That is not possible. AIN0 is an input to the analog comparator, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.

Maybe. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega) and the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega).
As you can see in the image below the pin PD6 is not an analog input. To be an analog pin it should be write ADCx, like the PC0..5.

So, if you are not using and Arduino Uno you can't use PD6 as analog input but you can use PC0..5.
To read an analog value using analogRead() method you can do like this:
int analogPin = 3;
int val = 0;           // variable to store the value read

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

void loop()
{
  val = analogRead(analogPin);    // read the input pin

  Serial.println(val);             // debug value
}

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


text:
MPU6050 or GY521/HMC5883 chips are burnt for no reason
I been trying to interface MPU6050 and HMC5883 with an Arduino Pro Mini/Nano. I²C scanner works just fine and identifies the device with no issues. I let the I²C scanner run like for 5 minutes and I see fumes coming out of the chips and sometimes the Arduino itself is burnt. I tried pull up resistors 2.2k, 7k without any luck. Has anyone got any inputs to this issue. Really frustrating to spend a weekend on this :(
To rule out the possibility of 5V supply causing the burn out I tried 3.3V from Nano and made promini 3.3V from 5V. Please see the pictures below.
Arduino Nano 3.3v was used to power up the I²C.
.
.
Pro Mini jumper was desoldered from 5V to 3.3V to see if the I²C chips are saved from being burnt. In both these setup voltage accross the I²C chip was measured and it was 3.3V.
Still no luck!
If you guys are to make the same circuit how would you do it and where would you get the components from? I must be doing something wrong and hope we together can figure it out.
Components are bought from eBay and the links are here.
GY521 = goo.gl/Y4aDph
HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI
PROMINI = goo.gl/79PVOM
This is some background of why this issue resolution is so important to me:
Just give you a backgroud of why I am doing this: I am building a quadcopter myself. Infact built one using GY80, but the module was expensive also it eventually got burnt out for the same reason mentioned above. Here is the first successful test flight of my first quadcopter goo.gl/rn6xWG (add https:// since I am rookie there is limitation on how many links I can post). If I can make the same thing work using GY521 and HMC5883 it would be awesome and cheaper.
Update on 08/11 @12:45 PM CST
I think it is because of the Pro Mini, I²C chips are getting fried. When using Nano, I think it is because of the voltage level difference between the SDA/SCL lines causing the problem. With Pro Mini tripped for 3.3V, I was not able to see any serial data from the chip too. To end all these I placed an order for 3.3V 8 MHz Pro Mini from amazon goo.gl/FjgTGj Let see how that goes.

Please post your wiring, or a photo of what you are doing, or both. Certainly the chips should not let out smoke.

burnt for no reason - chips don't burn for "no reason". There is a reason, you just haven't found it yet.

Arduino Nano/PROMINI, A4->SDA, A5->SCL, VCC to VCC, GND -> GND. Simple wiring on a bread board. I will send the picture later once i set up the circuit again.

The MPU6050 is a 3.3v device. Make sure you don't power it using 5v. Also make sure you don't connect the pull-ups to 5v, but to 3.3v. Also make sure there are no other breakouts on the I2C line that have pull-up resistors to 5v. Also disable the internal pull-ups inside the arduino

Here is the diagram db.tt/4ocbNOYW. Without pullup resistors and trying the GY521 or HMC5883 alone is burning the chip. GY521 or HMC5883 I am using is a 3-5V variant should have been working just fine. GY521 = goo.gl/Y4aDph HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI PROMINI = goo.gl/79PVOM –  Mohamed 2 mins ago   edit

Also @Gerben thanks for the info. I will try disabling the pullup resistors and see if it is working without any issues. Wonder how many more Arduinos/GY521 are left to try this out. Will Keep you posted.

That won't do much good if you are powering the devices with 5v like you show in the (tiny) diagram.

so If the promini is made 3.3v 8MHz from the 5V 16MHz, should it just work fine? or if I power the I2C devices from the 3.3v pin of the the Nano? I will try both ways and let you know. @Gerben I am reverting the pullup resistor changes from the wire library for now then.

It shouldn't be getting hot if you are only using 3.3 V. Can you please measure the Vcc into the HMC5883 and check it is 3.3 V?

I checked that it was 3.3V. No chip was getting hot like real hot but i can see fumes at times from the HMC5883 or GY521 for that matter. This last test i did no fumes happened but it fried the chips. If you masters are to make such a circuit how would you do it and where would you get the components from?

If I were in your shoes I would use my multimeter to measure the current going into the accelerometer. It should only be a few milliamps.

Now that the chip is burnt I need to solder up a new HMC5883 and see the current.  Will get back by tomorrow once I am back from work.  So if the current is higher what does it mean and what should be the conclusion.

Chips don't burn for no reason. Incorrect wiring could be one. Incorrect resistors. Voltage too high. And if the current was high I would be wondering why it is high.

Okay.  Let's think simple here.  5V Arduino powering the chip from 3.3v pin, why would you expect it to burn up.  I tried more than 10 Arduinos and i2c chips. Whole point of this open source chips is that it is plug and play.  May be because these are cheap knock off Arduinos and i2c chips one reason for this unpredictability.

Do the chips even tolerate 5V logic??

@Avamander Even used 3.3V power supply but it was still burning up the chips.

@Mohamed I did not ask about power supply. Do the I²C chips tolerate 5V I²C? Try dividing the voltage so that the chip gets 3.3V power and 3.3V logic.

@Avamander But how is it different from dedicated 3.3V for both Arduino and I²C?

@Mohamed I²C is a digital communication protocol. That means as digital data is 0 and 1s, 0 is 0V and 1 is the supply voltage, for 5V Arduino it is 5V. If you communicate with a chip that does not tolerate higher voltage logic, chips burn. That means 5V has to be turned into 3V in all places it could go in.

Fixed the issue with a dedicated 3.3V power supply.  I2C scanner is running for 30 minutes with no issues so far.


text:
From Strings to int problem
I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.
Arduino code:
String br;

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

void loop()
{
   while (Serial.available()>0)
 {
    br = Serial.readString();
    analogWrite(9, br.toInt());
    Serial.println(br.toInt());
 }
}

Qt code:
void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
{
   this->sendMessageToDevice(QString::number(position) + "n");
   qDebug() << "Grip: " << QString::number(position);
}

void MainWindow::sendMessageToDevice(QString message)
{
   if(this->device->isOpen() && this->device->isWritable())
   {
       //this->addToLogs("Sending information to the device " + message);
       this->device->write(message.toStdString().c_str());
   }
   else
   {
       this->addToLogs("I can not send a message. The port is not open!");
   }
}

Serial.readString() is deeply flawed and should be avoided. Read this: https://majenko.co.uk/blog/reading-serial-arduino

And I am sure you meant to add \n to your outgoing messages, not n...

when debugging a problem such as yours put Serial.println(br); before the analogWrite() to see what is being received

As Majenko wrote in his comment, your problem lies with Serial.readString(). It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. String.toInt() will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the n, that you send). It stops there and returns the already converted value.
This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.
Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.
The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character n is ok here. But mostly the newline character \n is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use \n.
As an example of this serial code, you can take the readline() function from Majenko's blog post:
char buf[80];

int readline(int readch, char *buffer, int len) {
    static int pos = 0;
    int rpos;

    if (readch > 0) {
        switch (readch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = readch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

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

void loop() {
    if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
    }
}

You can convert the character buffer to an int with atoi() in the if statement in void loop() and use it for ´analogWrite()`.


text:
Arduino Power Consumption
I am pairing an Arduino Uno along with both a HC-05 bluetooth module and a sensor circuit.
Show below is the circuit conditions as well as the circuit.

As far as powering up the system, I am planning to use a 9 Volt battery(550 ampere) to connect to the Arduino which draws in 45 mA and the sensor circuit which takes in a total of 28 mA. I calculated the total life of one of the batteries to be 7.53 hours by (550/(28+45)). Can someone help me with the total power consumed by the system?
UPDATE:
I read on the sensor data sheet that there are two parameters which heater power as well as sensor consumption. Heater Power consumers approximately 140 mW and the sensor consumes approximately 10 mW. I believe the Arduino will consume 405 mW because of (9 volts * 45 mA)  and the bluetooth module will consume 26.5 mW because (3.3 volts * 8). Therefore, the total power consumption is 571.5 mW. Is this correct??? Also will the 9 volt battery be able to support the total power?

550 ampere - What does it mean? Short circut current? Must be some kind of car battery

Your calculations are not totally right. I did not check the data you provided, so I'm just using the numbers you put.
The arduino draws up 45mA @5V.
The sensor has a power of 150 mW and is powered at 5V, which means a current of 30mA.
The bluetooth module gets 8mA (are you really sure? it seems too low) @3.3V.
Now, the battery gives you 9V. So you need to convert them to the proper (5V and 3.3V) voltages required by the devices.
You have mainly two options:

you use a linear regulator
you use a switching regulator

(Please note that if you use the regulators already present on the UNO board - the 1117 and the LP2985 - you will use the first approach)
In the linear case, the regulator will drop the voltage by dissipating the excess power through heat. In this case, you will need to sum the currents:
Total current = 45mA + 30mA + 8mA = 83mA. Please note that if using a 9V battery, the 5V regulator will need to dissipate (9-5) * 83mA = 332mW of power (or slightly less if the 3.3V regulator directly interfaces to the 9V battery).
Now, according to the first datasheet I stumbled upon on google, this kind of battery have a capacity rated at 10mA, but at 100mA it loses about 40% of it. In fact, batteries tend to last less when the current increases (if you double the current you will get less than half of the time).
Considering so a mere 30% of loss at 83mA, your battery will last slightly above 4 hours and a half (550mAh*70%/83mA)
Now, if you use a switching regulator to get 5V from the 9V (and then a linear one to get the 3.3V), you will have to generate 83mA at 5V. This means that, considering an efficiency of 85%, your battery will have to provide roughly 54mA (83mA*5V/9V/85%).
According to the datasheet of the battery, this lower current reduces the degradation of the capacity to about 25%. The total uptime is consequently 7 hours and a half (550mAh*75%/54mA).
If you put a second switching regulator to get the 3.3V, you will have
- 75mA at 5V, which with a 85% efficiency will become 49mA
- 8mA at 3.3V, and with a lower efficiency due to the very low current (let's say 75%) become 4.4mA
Total current from battery: 53.4mA (which can be considered equal to the case with just one switching converter.
Just one last note: please consider that a heated sensor like the one you have is not engineered for battery-powered devices, since a lot of power becomes heat. When you want to develop a real battery-powered sensor, you will need to go with a lower-power solution for both the microcontroller (and the board) and the sensor


text:
Why does it skip the first index - shift register issue
So, I wrote this code myself and I'm a noob on the issue. I did get my code working, but cannot understand why it has to be the way it is.
int counter;
int ledValue[] = {
  1,0,1,1,1,1,1,1
};

void setup()
{
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop(){
  digitalWrite(5, HIGH);
  for (counter = 8; counter >= 0; --counter) {
  // turn the pin on:
    digitalWrite(2, ledValue[counter - 1]);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    delay(100);
  // turn the pin off:
  }
  delay(1000);
  digitalWrite(5, LOW);
}

Now, I am puzzled by both the counter = 8 and the [counter -1]. To me it looks like I am loop-ing this 9 times, though I only got 8 items in the array
A. If I make it counter = 7 and [counter -1] my output is 10111110. This loops 8 times (I think), but gives me 7 leds.
B. If I make it counter = 7 and [counter] my output is 01111110. This loops 8 times (I think), gives me 7 leds but also an extra led burning up front, hence braking the prescribed pattern.
C. If I make it counter = 7; counter >= -1 my output is 10111111.(as it should). But how can it be -1?
My guess is that I am doing something wrong at the beginnen, but I can't find what. Tried several tutorials and explanations, but it still puzzles me why the correct running code is that way.
Just to be sure, I am familiar with an array being 0-indexed.
Please helpt me understand my code  ;-)
Edit:
Small addition:

pin 2 is connected to ShiftRegister pin 14
pin 3 is connected to ShiftRegister pin 12
pin 4 is connected to ShiftRegister pin 11
pin 5 is connected to ShiftRegister pin 10

Thanks for the feedback. My lack of understanding does not concern the loop or array. What I can't get my head around is why the shift registers outputs the loop as it does. Would a picture of the setup help?

What do you mean by "expected output"? Most of the LEDs are set to fixed values, so are you saying that the LED on pin 2 should show the pattern 10111111? Since you are going through the array backwards (8 down to 0) I would expect to see 11111101.

But how can it be -1? - an integer can be -1. What do you mean by "how can it be"?

@NickGammon; I meant; How can the index of an array be -1? Since it does work if it counts until (including) -1. And expected output; because with the shift register, the first value put in, is the last value in the row. So, if I want it to replicate a given pattern in LED's I should process backwards. That is, for as far as I do understand shift registers now.

The problem is in the directions the ShiftRegister gets.
This way, it works
...
digitalWrite(2, ledValue[counter - 1]);
digitalWrite(4, 1); //clock pin high
digitalWrite(4, 0);
digitalWrite(3, 1); //latch pin high
digitalWrite(3, 0);
digitalWrite(2, 0);
...

The clock and latch have to be low again before switching the signal back to 0.
In the upgraded version I put the clock and latch in a function.

The correct way to loop through an array of length 8 is:
for (int counter = 0; counter < 8; ++counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

If you want to loop through the array backwards, then:
for (int counter = 7; counter >= 0; --counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

This loop will visit, in this order, the indices 7, 6, 5... 1 and 0.
For extra clarity, you could define a constant that holds the length of
the array, then replace the numbers 8 and 7 above by VALUES_COUNT
and VALUES_COUNT-1 respectively.
You wrote:

If I make it [...] my output is [...]

Not sure what you mean by that. This code should not have much visible
output, as the LEDs are turned off only microseconds after being turned
on. How do you determine what the program's "output" is? Maybe there is
an issue with the way you are trying to diagnose the problem.

S/he has a delay in the loop, Edgar.

@NickGammon: I saw that delay but, in order to see the pattern, another one would be needed right before digitalWrite(2, 0);.

Oh yeah, good point.

Make the problem as small as possible. For example:
void setup() {
  Serial.begin(9600);

  for( int i=8; i>=0; --i) {
    Serial.println(i);
  }
}

void loop() {
}

The output is:
8
7
6
5
4
3
2
1
0

Those are indeed nine numbers. An array in c++ starts at zero. Your array is from ledValue[0] up to (inclusive) ledValue[7]. See the answer by Edgar Bonet how the for-statements are used.


text:
Why does my 23,032 byte Arduino sketch take 36.32 sec to upload via ISP to an Atmega328p on a breadboard w/code verification disabled?
"Sketch uses 23032 bytes (71%) of program storage space. Maximum is 32256 bytes.
Global variables use 1342 bytes (65%) of dynamic memory, leaving 706 bytes for local variables. Maximum is 2048 bytes."
I have "verify code after upload" disabled. With this enabled, it takes an additional 20 sec to upload for a total of 56 sec.
Using Sparkfun's avr programmer with USBtinyISP, win 10, arduino ide, minicore library. Code is utilizing several libraries from Mozzi. External 16mhz crystal. Have set fuse bits on the chip to use the external clock using the following command: "avrdude -c usbtiny-p m328p -U lfuse:w:0xFF:m"
Seems like it should be faster if truly uploading at 115200 bits / sec. But maybe I'm missing something in how this works.
Thanks !!

ISP programmers typically default to low ISP clock rates.  Often something like 10khz, sometimes slower, probably to just work by default with very slowly clocked AVR chips.  The ISP clock rate must be about one eigth that of the AVR's clock.  For example, by defaulting to a low rate like 10Khz, the programmer will successfully communicate with an AVR clocked at 125KHz with some margin.   Around 4 KHz would work with a 32.768 KHz watch crystal.
Look in avrdude documentation for the -B option.  Note uppercase 'B', this is the option for changing the ISP speed, not lowercase -b which is for the PC to programmer (or bootloader) baud rate.   Not all programmers support -B, but many do.
UPDATE
Well, I dug around the USBtinyISP code and in avrdude and it looks like the default value for -B is 10.  So 10uS.  The way this value is used in the USBtinyISP code is for high or low period, rather than total clock period.  So it's about 20uS per bit, or 50kHz.  If that's your rate, then the plain clocking of the SPI data only accounts for about 3.7 seconds.  So that does cast doubt on this idea.
But, it still may be worth double checking that it is operating with the value 10 and not something larger.  Just to put this in perspective: the maximum -B value is apparently 250, which would result in 2kHz ISP clock rate and about a minute and a half to clock out your roughly 23 KByte.
More findings: Per byte SPI overhead
Each byte of the flash pages is being delivered into the ISP interface by way of 4-byte long SPI commands.  The firmware for the programmer has the following code in it for writing a page in its spi/main.c file where you can see it calling spi( cmd, res, 4 ) :
extern  void    usb_out ( byte_t* data, byte_t len )
{
    byte_t  i;
    uint_t  usec;
    byte_t  r;

    for ( i = 0; i < len; i++ )
    {
        cmd[3] = data[i];
        spi_rw();
        cmd[0] ^= 0x60; // turn write into read
        for ( usec = 0; usec < timeout; usec += 32 * sck_period )
        {   // when timeout > 0, poll until byte is written
          spi( cmd, res, 4 );
            r = res[3];
            if  ( r == cmd[3] && r != poll1 && r != poll2 )
            {
                break;
            }
        }
    }
}

This code is used to deliver data to the flash page buffer during ISP programming.
You can see a comment in avrdude's code explaining that each byte becomes a 4-byte SPI transaction as an aid to explaining their calculation for a communications timeout with the programmer.  The following is in avrdude's usbtiny.c file for the usbtiny_paged_write function.
if (usb_out(pgm,
            function,       // Flash or EEPROM
            delay,          // How much to wait between each byte
            addr,           // Address in memory
            m->buf + addr,  // Pointer to data
            chunk,          // Number of bytes to write
            32 * PDATA(pgm)->sck_period + delay  // each byte gets turned into a
                                 // 4-byte SPI cmd  usb_out() multiplies
                                 // this per byte. Then add the cmd-delay
            ) < 0) {
  return -1;
}

To be clear, these two functions have the same name but are in fact two different functions; the former running in the programmer the later is running in avrdude.
So there is in fact substantial SPI transaction overhead in just delivering data into the page buffer.  Beyond that there's a second USB and SPI transaction to commit the page buffer to flash.

Great info, thank you. I looked into my output and found:
"avrdude: Using SCK period of 10 usec"
So it appears to be set to the default of 10uS.

I went into the avrdude.conf file and changed the "default_bitclock" value to 1. Code now uploads in 10 seconds and executes fine on the chip.
This is a 66% improvement but still seems like it ought to upload faster based on the math.

Or.... maybe this is about right. If we're estimating about 3.5 seconds of spi data and the bitclock is set to pause for 2uS for each bit ... if each bit took about 1uS to write wouldn't that approximately triple the total time it takes? Although I have no idea how much time it actually is taking to write one bit...

@codyblanchard, see expanded findings.   The "the plain clocking of the SPI data" probably should have been written to say "of the program data".  What I was trying to do (and probably failing at) was being conservative in saying rough 3.7 seconds for the irreducible (barring compression) SPI timing associated with program data itself.  Beyond what I've just mentioned in the update, I'm sure there are more delays.  Though they'll probably be diminishing returns.

I have a description of the uploading process which, if you extrapolate out from the 1082 bytes being uploaded in about 0.15 seconds (plus some overhead) should mean that you would get 23032 bytes uploaded in 23032 / 1082 * 0.15 seconds, namely about 3 seconds, including verification.
The fact that you are not achieving that would suggest (as Gil mentioned in their answer) that there is a problem with your PC actually sending data that fast down the USB port.
If you were to hook up a logic analyzer and watch what actually arrives, then you might find that there are bigger gaps between bytes (or batches of bytes) than you would expect.

It sounds like the bandwidth is limited. I have no idea how much delay the ISP is adding but it has to add some. The best would be via the USB at 115200 baud or faster if you can get it.


text:
Why Arduino Pro IDE is not open source?
I just found the alpha version of Arduino Pro IDE and I was wondering why this project is not open source as the classic IDE.
I didn't found anything about that online.

https://github.com/arduino/arduino-pro-ide/blob/master/README.md#user-feedback-and-issue-report

It appears that they intend to open-source the project but that the developers may not have reached the point where they believe that would be useful.  If you are wanting to contribute to the project you might send them a request.


text:
ESP-32 Upload Files to SPIFFS via browser
I am using ESPAsyncWebServer Library in a ESP32 DevKit. I want to make a form in the browser in order to upload files in SPIFFS.
I have to notice that the whole device works perfectly. I connect to Wi-Fi, it uploads files via IDE etc.
Through searching in the net, I found this part of code that does not work.
server.on("/upload-file", HTTP_GET, [](AsyncWebServerRequest* request) {
    String html = "
<form method='post' action='/upload-file'><input type='file'><button>Send</button></form>
";
    request->send(200, "text/html", html);
    });

server.on("/upload-file", HTTP_POST, [](AsyncWebServerRequest* request) {
    AsyncWebServerResponse* response = request->beginResponse(200, "text/html", "hello world");
    response->addHeader("Connection", "close");
    request->send(response);
    }, handleUpload);
server.onFileUpload(handleUpload);

The handleUpload function:
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
}
if (len) {
    request->_tempFile.write(data, len);
}
if (final) {
    request->_tempFile.close();
    request->redirect("/files");
}
}

It shows the form but the file doesn't upload.
Is there any idea on how can I make it work?

how far along does it get? Does the browser re-direct after upload? I would add Serial.println("saw1") (and 2 and 3, etc) statements to each function to trace the flow.  If it makes it all the way through, or in the last working part's code, start logging the function's arguments to see where things are not as expected.

I had the same problem and thanks to you, I did solve the problem!
Here is the full code,
My html code for the upload page, the form is in the  tag:

<!DOCTYPE html>

  <title>File Upload Example</title>

File Upload Example

<form method="POST" action="/upload" enctype="multipart/form-data" target="iframe"><input type="file" name="upload"><input type="submit" value="Upload"></form>

code for ESP:

void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
    Serial.println("1");
}
if (len) {
    request->_tempFile.write(data, len);
     Serial.println("2");
}
if (final) {
   Serial.println("3");
    request->_tempFile.close();
    request->redirect("/");
}
}

 controlserver.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        request->send(200); }, handleUpload);

  controlserver.on("/UPL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", upl);
  });

  readFile(SPIFFS, "/11.txt"); // show the content of the uploaded file, obviously you should know the name of the uploaded file!

you can write a function like this to make sure the file was delivered:
  readFile(fs::FS &fs, const char * path){
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if(!file || file.isDirectory()){
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while(file.available()){
    fileContent+=String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);

}


text:
Weather station project Transmitter not communicating with Receiver
I am building a weather station that contains a transmitter and a receiver and the data at the receiver's serial monitor shows either ovf, nan, 0.00 or some crazy number for the outside data (transmitter) so I'm hoping someone can take a quick look at the code and see if I missed something because I am out of ideas
The Receiver consists of an Arduino DUE, NRF24L01 transmitter, and a DHT 22 temp sensor
The Transmitter consists of an Arduino NANO, NRF24L01 transmitter, and a DHT 22 temp sensor
Thank you for any help or advice
// Transmitter
#include "DHT.h"
#include <SPI.h>
#include "RF24.h"

#define DHTPIN 4
#define DHTTYPE DHT22

RF24 myRadio (7, 8);
byte addresses[][6] = {"0"};

struct package
{
  float temperature ;
  float humidity ;
};
typedef struct package Package;
Package data;

DHT dht(DHTPIN, DHTTYPE);

void setup()
{
    Serial.begin(9600);
    delay(1000);
    dht.begin();
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate( RF24_250KBPS ) ;
    myRadio.openWritingPipe( addresses[0]);
    delay(1000);
}

void loop()
{
  readSensor();
    myRadio.write(&data, sizeof(data));
  Serial.println(data.humidity);
  Serial.println(data.temperature);
  delay(1000);
}
void readSensor()
{
 data.humidity = dht.readHumidity();
 data.temperature = dht.readTemperature();
}

// Reciever
#include <SPI.h>
#include "RF24.h"
#include <DHT.h>

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

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

RF24 myRadio (51,49); // CE, CSN
struct package
{
  float temperature ;
  float humidity ;
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
  Serial.begin(9600);
  dht.begin();
  delay(1000);
  myRadio.begin();
  myRadio.setChannel(115);
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate( RF24_250KBPS ) ;
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();
}

void loop()
{

  if ( myRadio.available())
  {
    while (myRadio.available())
    {
    myRadio.read( &data, sizeof(data) );
    }
    Serial.print("Outside Temperature: ");
    Serial.print(data.temperature);
    Serial.print(" C |");
    Serial.print("  Outside Humidity: ");
    Serial.print(data.humidity);
    Serial.println (" %");

  //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Inside Temperature: ");
    Serial.print(temp);
    Serial.print(" C |");
    Serial.print("Inside Humidity: ");
    Serial.print(hum);
    Serial.println (" %");
    Serial.println("----------------------------------------------------");
    delay(2000); //Delay 2 sec.

  }
}

Serial Monitor
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: nan %
Inside Temperature: 20.50 C |Inside Humidity: 49.70 %
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: nan %
Inside Temperature: 20.50 C |Inside Humidity: 49.70 %
----------------------------------------------------
Outside Temperature: ovf C |  Outside Humidity: -8.00 %
Inside Temperature: 20.50 C |Inside Humidity: 49.80 %
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: ovf %
Inside Temperature: 20.50 C |Inside Humidity: 49.80

Nothing wrong with your code. nRF24L01 consumed quite some power during transmission, the 3.3v regulators on your Due and Nano might not be able provide the surge current it needs, try to add a large cap (10uF or above) to both of nRF24L01 3.3v pins to see if it help, or use a 3.3v that can delivery 200mA+ current.

Thank you!! It worked like a charm.


text:
Changing address of MPU 9250 connected to ESP32
Can I change the I2C address of a device (MPU9250) connected to ESP 32 using int pin. I understand that in arduino board if we connect the int pin to A0 the default I2C address of MPU 9250 changes from 0x68 to 0x69. Is something similar possible with ESP 32? Which Pin I should connect to?

you are misunderstanding how A0 pin is used ... if it is connected to GND then the address is 0x68 ... if it is connected to Vcc then the address is 0x69 .... your question is not about the arduino, so it is off topic here

You have only two choices with this device on an I2C bus.  As stated in the datasheet:

So it's either:

0b1101000
0b1101001

The AD0 pin selects which of these two addresses are used.
The complete datasheet can be viewed at the following link as well as other places:
Datasheet


text:
Arduino Pro micro Serial communication problem with Node MCU
I recently bought an ATmega32U4 based Arduino Pro micro. I am using the Keyboard library and interfacing with my PC via USB.
I am trying to create a serial communication between the Arduino Pro micro and a NodeMCU via Rx, Tx pins (0, 1), but it isn't working i.e. not giving any output with the code below on the Pro micro:
#include <Keyboard.h>

int incomingByte;
unsigned long lastTime;

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

void loop() {
  if (Serial.available() > 0) {
    lastTime = millis();
    String payload = "";

    while (1) {
      if (millis() - lastTime > 1000)
        break;

      incomingByte = Serial.read();
      Serial.println(incomingByte);
    }
  }

On the NodeMCU there is a simple script flashed which only writes on serial some characters in a delayed loop.
When using the SoftwareSerial library with the Pro micro, it is working fine i.e. I can read data sent by the NodeMCU on custom Rx, Tx pins (9, 10). I tried this because I thought since Pro micro is communicating with a PC, the original Rx and Tx pins are busy. But after some research I got to know that unlike other Arduino boards like the UNO, the Pro micro doesn't use those for communication over USB.
Although custom serial using SoftwareSerial library is working, it is too slow and unreliable i.e. it takes 2-3 seconds to pass a string of length 10. Also its unreliable because on sending bigger length strings, the strings arrive incomplete or sometimes the data gets corrupted (characters shuffle).
Again this is not my main concern, if I can use original Rx, Tx pins as usual on any other Arduino boards, it solves my issue.
This is my circuit diagram:

The problem is your janky serial reading method. You're assuming there's data to read when there isn't. Read this: https://majenko.co.uk/blog/reading-serial-arduino

I probably missed something but: why are you using SoftwareSerial on the pro micro at all?

@timemage Yes, you missed that. He explained why - he assumed pins 0/1 were taken with the USB, then found out otherwise, and now is attempting to use those with Serial instead of SoftwareSerial.

The Serial device is usually the USB serial connection, whether or not that is controlled by pins 0/1. For pins 0/1 with a native USB connection you need to use Serial1. I think. It's been a while since I used an Arduino with native USB...

I'm not confused about how Serial and Serial1 work on the 32u4 based Arduinos.  I don't see any indication that anything other than SoftwareSerial is being used.

@Majenko thanks, replacing Serial with Serial1 worked out for me.

RX and TX pin of Arduino Micro are Serial1. Replace Serial in your sketch with Serial1 to communicate with esp8266 over RX and TX pin.

Luckily I found out that last night and that worked too. Thanks for your inputs @Juraj.
The Rx and Tx (0 and 1) pins on Arduino Pro Micro are defined with Serial1 so replacing Serial with Serial1 worked out for me. Thanks to all for your interest.


text:
Array of Functions
I'm new to C++. How to make a menu without if() {} else {} & switch() case?
I made a menu on an array, but for some reason it doesn't compile. How to correct it?
typedef void (*cbd)(uint8_t, uint8_t);
typedef void (*cbt)(uint8_t, uint8_t);
typedef void (*cba)(uint8_t, uint8_t);
typedef void (*MenuFunction) (int8_t);

class Menu {
public:
    Menu() {
        updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes};
    }

    static void Setup(cbd display, cbt setTime, cba setAlarm, uint8_t alarmHours, uint8_t alarmMinutes) {
        cbDisplay = display;
        cbSetTime = setTime;
        cbSetAlarms = setAlarm;
        alarmHours = alarmHours;
        alarmMinutes = alarmMinutes;
        cbSetAlarms(alarmHours, alarmMinutes);
    }
    // Used for menu.UpDown(dir) callback
    static void UpDown(int8_t direction) {
        updownFn(direction);
    }
    // Used for menu.Tab() callback
    static void Tab() {
        updownFnNum++;
        updownFn = updownFns[updownFnNum % 5];
    }

private:

    static void updownNone(int8_t direction) { }

    static void updownAlarmHours(int8_t direction) {
        alarmHours += direction;
        cbDisplay(alarmHours, alarmMinutes);
        cbSetAlarms(alarmHours, alarmMinutes);
    }

    static void updownAlarmMinutes(int8_t direction) {
        alarmMinutes += direction;
        cbDisplay(alarmHours, alarmMinutes);
        cbSetAlarms(alarmHours, alarmMinutes);
    }

    static void updownTimeHours(int8_t direction) {
        timeHours += direction;
        cbSetTime(timeHours, timeMinutes);
        cbDisplay(timeHours, timeMinutes);
    }

    static void updownTimeMinutes(int8_t direction) {
        timeMinutes += direction;
        cbSetTime(timeHours, timeMinutes);
        cbDisplay(timeHours, timeMinutes);
    }

    static uint8_t alarmHours, alarmMinutes, timeHours, timeMinutes;
    static uint8_t updownFnNum; // 0-None, 1-AlarmH, 2-AlarmM, 3-TimeH, 4-TimeM
    static cbd cbDisplay;
    static cbt cbSetTime;
    static cba cbSetAlarms;
    static MenuFunction updownFns[5];
    static MenuFunction updownFn;
};

uint8_t Menu::alarmHours = 0;
uint8_t Menu::alarmMinutes = 0;
uint8_t Menu::timeHours = 0;
uint8_t Menu::timeMinutes = 0;
uint8_t Menu::updownFnNum = 0;
cbd Menu::cbDisplay = NULL;
cbt Menu::cbSetTime = NULL;
cba Menu::cbSetAlarms = NULL;
MenuFunction Menu::updownFn = NULL;

Output:
In file included from app.ino:7:0:
menu.h: In constructor 'Menu::Menu()':
menu.h:9:109: error: cannot convert '<brace-enclosed initializer list>' to 'MenuFunction {aka void (*)(signed char)}' in assignment
updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes};

Thank you!

The C++ language makes a distinction between an initialization and an
assignment. An initialization is the initial value you give to a
variable at the point where you are defining it. An assignment is the
use of the = operator anywhere else. Also, the language does not allow
assigning the contents of an array as a whole. You can initialize an
array though.
This:
Menu() {
    updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes,
        updownTimeHours, updownTimeMinutes};
}

is an attempt to assign a whole array. It cannot work. If you want to
initialize the array, do it at the point where it is being defined,
outside of the class definition:
MenuFunction Menu::updownFns[5] = {updownNone, updownAlarmHours,
    updownAlarmMinutes, updownTimeHours, updownTimeMinutes};

First, your updownFns[5] can be contain 5 variable. And the last variable index can be 4 not 5 because of array index starts from 0.
Here is the code :
typedef void (*cbd)(uint8_t, uint8_t);
typedef void (*cbt)(uint8_t, uint8_t);
typedef void (*cba)(uint8_t, uint8_t, uint8_t);
typedef void (*MenuFunction) (int8_t);

class Menu {
public:
    Menu() {
        updownFns[0] = updownNone;
        updownFns[1] = updownAlarmHours;
        updownFns[2] = updownAlarmMinutes;
        updownFns[3] = updownTimeHours;
        updownFns[4] = updownTimeMinutes;
    }

    static void Setup(cbd display, cbt setTime, cba setAlarm, uint8_t alarmHours, uint8_t alarmMinutes) {
        cbDisplay = display;
        cbSetTime = setTime;
        cbSetAlarms = setAlarm;
        alarmHours = alarmHours;
        alarmMinutes = alarmMinutes;
        cbSetAlarms(alarmHours, alarmMinutes);
    }
    // Used for menu.UpDown(dir) callback
    static void UpDown(int8_t direction) {
        updownFn(direction);
    }
    // Used for menu.Tab() callback
    static void Tab() {
        updownFnNum++;
        updownFn = updownFns[updownFnNum % 5];
    }

private:

    static void updownNone(int8_t direction) { }

    static void updownAlarmHours(int8_t direction) {
        alarmHours += direction;
        cbDisplay(alarmHours, alarmMinutes);
        cbSetAlarms(alarmHours, alarmMinutes);
    }

    static void updownAlarmMinutes(int8_t direction) {
        alarmMinutes += direction;
        cbDisplay(alarmHours, alarmMinutes);
        cbSetAlarms(alarmHours, alarmMinutes);
    }

    static void updownTimeHours(int8_t direction) {
        timeHours += direction;
        cbSetTime(timeHours, timeMinutes);
        cbDisplay(timeHours, timeMinutes);
    }

    static void updownTimeMinutes(int8_t direction) {
        timeMinutes += direction;
        cbSetTime(timeHours, timeMinutes);
        cbDisplay(timeHours, timeMinutes);
    }

    static uint8_t alarmHours, alarmMinutes, timeHours, timeMinutes;
    static uint8_t updownFnNum; // 0-None, 1-AlarmH, 2-AlarmM, 3-TimeH, 4-TimeM
    static cbd cbDisplay;
    static cbt cbSetTime;
    static cba cbSetAlarms;
    static MenuFunction updownFns[5];
    static MenuFunction updownFn;
};

uint8_t Menu::alarmHours = 0;
uint8_t Menu::alarmMinutes = 0;
uint8_t Menu::timeHours = 0;
uint8_t Menu::timeMinutes = 0;
uint8_t Menu::updownFnNum = 0;
cbd Menu::cbDisplay = NULL;
cbt Menu::cbSetTime = NULL;
cba Menu::cbSetAlarms = NULL;
MenuFunction Menu::updownFn = NULL;
// MenuFunction Menu::updownFns = {};

But still code is not correct. if you look at the signature of this definition
typedef void (*cba)(uint8_t, uint8_t, uint8_t);

it takes 3 parameters. But inside the code, you give 2 parameter to the function
cbSetAlarms(alarmHours, alarmMinutes)

It's a typo, I've corrected it. But the error is the same. typedef void (*cba)(uint8_t, uint8_t);

It's not typo, typo means something different.
if you change typedef void (*cba)(uint8_t, uint8_t, uint8_t); to typedef void (*cba)(uint8_t, uint8_t);
Code wil compile without errors

updownFns[0] = updownNone; It gave:
/tmp/cc3MHoSt.ltrans0.ltrans.o: In function global constructors keyed to 65535_0_app.ino.cpp.o.4201': <artificial>:(.text.startup+0x144): undefined reference to Menu::updownFns'
:(.text.startup+0x148): undefined reference to `Menu::updownFns'
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Pro or Pro Mini.

There are several issue with your code. You can use like this
Remove initilization from ctor and init static variable outside.
MenuFunction Menu::updownFns[] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes };
But when you want to use updownFns it will give errors because of the function is private within this context also.

I initialized the array outside of the class definition. No errors. I then used updownFns and no errors.

Yes, i already said about it :)


text:
Call functions of one class from another class - Callback
I am new to C++ & I need to call functions of one class from another class. And so that the classes do not know anything about each other. How to do it in Arduino environment?
class Encoder {
  using CallBack2 = void( * )(const int, const int);
  using CallBack0 = void( * )();
  private:
    CallBack2 callbackUpDown;
    CallBack0 callbackTab;
    CallBack0 callbackLongPress;
  public:
    Encoder() {}

  void Setup(CallBack2 updown, CallBack0 tab, CallBack0 cbLongPress) {
    callbackUpDown = updown;
    callbackTab = tab;
    callbackLongPress = cbLongPress;
  }

  void Loop() {
    if (true) {
      callbackUpDown(-1, 300);
      callbackTab();
      callbackLongPress();
    }
  }
};

class Menu {
  public:
    void UpDown(const int direction,
      const int count) {}
      void Tab() {}
};

class RTC {
  public:
    void Setup() {}
    void Toggle() {}
};

class Display {
  public:
    void Toggle() {}
};

Encoder encoder = Encoder();
RTC rtc = RTC();
Menu menu = Menu();
Display display = Display();

void setup() {
  rtc.Setup();
  encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle();rtc.Toggle();});
}

void loop() {
  encoder.Loop();
}

Output:
In file included from sun.ino:47:0:
callback.h: In function 'void setup()':
callback.h:52:75: error: invalid use of non-static member function 'void Menu::UpDown(int, int)'
   encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle(); rtc.Toggle();});
                                                                           ^
callback.h:28:7: note: declared here
  void UpDown(const int direction, const int count) {}
       ^~~~~~

Thank you!

Classes are designed to be self contained.  If you really need to use a function in a different class consider refactoring your code so as to avoid this.  Alternatively you could put the function in question into a new class which both existing classes inherit from.  Thereby giving access to that function from both existing classes.

pass an object of that class. https://arduino.stackexchange.com/questions/90329/invalid-use-of-non-static-member-function/90336#90336

Are there no interfaces in C++ to Inject Dependencies, Dependency Inversion?

What you are doing here
encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle();rtc.Toggle();});

is not only passing a function pointer. You are passing a member function pointer. This is 2 levels more difficult than function pointers on their own.

The syntax of declaring a member function pointer is different. You need to include the class name in the function pointer declaration. It would look like
using CallBack2 = void( Menu::* )(const int, const int);

When calling a member function pointer, you need an object to call the function on.

Unfortunately, this is so hard that I can't turn your code into a working example. If you want to be able to read your code in 3 months or if you want others to be able to read your code, stick to normal function pointers. They are hard enough.
Suggestion: implement free functions that do what you want:
void menuUpDown(const int dir, const int count)
{
  menu.UpDown(dir, count);
}
void menuTab()
{
  menu.Tab();
}

void setup() {
  rtc.Setup();
  encoder.Setup(menuUpDown, menuTab, []{display.Toggle();rtc.Toggle();});
}

Or, since you're already using lambdas (are you aware of that?), you can also
void setup() {
  rtc.Setup();
  encoder.Setup(
    [](const int dir, const int count){menu.UpDown(dir, count);},
    []{menu.Tab();},
    []{display.Toggle();rtc.Toggle();}
  );
}

Note that pupils and students might not have been introduced to the concept of lambdas. If you publish such code online, people might not be able to change it themselves because they don't understand it.

Nice answer! Thank you

@Andre: you're welcome. Once you have tried the suggestion and tested that it actually works for you, you may mark this question as solved by checking the checkmark beneath an answer so that others know they don't need to spend time on this any more. No need to hurry, take your time to check that it's really the answer you need.

@Andre: your design looks more like a C# or Java design. Be careful with that on Arduino. You may run out of memory if your designs are very sophisticated and your code is too PC-like.

What is wrong with my design and how can I improve it? I can make classes static singleton and/or use pointers. I don't need multiple instances of the same class. Actually I need one instance of each class. How to get rid of the out of memory?

@Andre: regarding OOM, I don't have much advise. Mainly avoid new (which I see you don't use, that's great). Next, avoid copies. Encoder encoder = Encoder(); could just be Encoder encoder;. (Yes, we have guaranteed copy elision in modern C++, but nobody really knows what C++ version Android actually supports)

@Andre: for the singletons, don't design singletons. Maybe someone really wants to create another object. I would try to do something similar as has been done for Serial. Instead of creating your own instance of Serial, there is just Serial, Serial1, Serial2 as predefined objects (don't exactly know how they did that)

Also, Using Static Methods Or Non-Member Functions (C-Style)
class MyClass {
  public:
    static void onMsg(int num1, int num2) {
      // NOTE: Can't call any non-static method functions here!
    }
};

class LibraryClass {
  using CallBack = void( * )(int, int);
  private:
    CallBack callBack;
  public:
    void Setup(CallBack callBackFunc) {
      callBack = callBackFunc;
    }
    void Loop() {
      callBack(1, 2);
    }
};

MyClass myClass;
LibraryClass libraryClass;

void setup() {
  libraryClass.Setup(&myClass.onMsg); // Provide the instance and function to call
}

void loop() {
  libraryClass.Loop();
}

Is there a difference between &myClass.onMsg and MyClass::onMsg? I don't think this provides an instance for the function to call. Otherwise you could call member functions and it needn't be static. (Side note: myClass with lower case m is not a class, it's an object; same for libraryClass)


text:
Logic level converter 12v to 5v
What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.
I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on ebay . Will it work like I want? Offer DIY solutions as well.

You're asking for an oxymoron there - "cheapest and best"? You can have the cheapest or you can have the best - which do you want? You can't have both. I think you mean "which is the best low-cost method"

And what in the car are you trying to connect to? To do what?

@Majenko, or something cost effective. Though, in this case it either works, or not. So any working low-cost method will do? But, this is more of a shopping question in this state. I believe anyone could/should make the call for himself when buying something. Your second point is spot on.

Use a car phone-charger. Especially if you plan to use it in a car, as the voltage in a car can fluctuate, and have huge spikes.

It would help us to know if your goal is to power the Arduino or to condition signals from the car so that they can be read by the Arduino. Since you're asking about a "logic level converter" I'm assuming it is the later. This could be a good question, please come back and clarify / add more information.

Well do you really want a logic level converter. Because a logic level converter can only handle not too much current.

Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

Power If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance here is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.
Get status If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you
Set status If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points

simulate this circuit – Schematic created using CircuitLab
Just one very big WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be only some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)

And... only after spending a lot of time I noticed that this question was from 2 years ago, and the reason why the question popped up is just because the OP did not accept an answer...

Your safest option is to use an opto-isolator. Connect the LED side in parallel with the load with a suitable resistor, then the transistor side becomes, effectively, a button connected to the Arduino.
As far as the car is concerned you have just connected an LED. As far as the Arduino is concerned you have a button connecting to ground.
It provides complete isolation of the car's electrics from your Arduino.

This is a good answer for a "logical shifter" as asked in the question.

Use LM7805 linear voltage regulator to regulate to 5 v , it's all about 2-4$, you need LM chip and 2 capacitors, that's all :) and if you need 3.3 just search for linear voltage regulator

Don't forget a big-ass heat sink. Running from a car (up to 15V) you'll be dissipating a lot of heat.  The 7805 is not a good choice for car use.  Also he asked for "logic level converter" - though I don't think he knows what he wants ;)

I think too :) but let's explain to man :) and it doesn't need a big heatsink if he is powering only arduino from 12 volts, but i don't even know why he asks for that, cuz it's integrated into arduino board, and if he looked how to build standalone atmega328 he would know what he has to use

Direct connection is not the best idea. During certain moments there may be huge voltage spikes.

Well not really if he's connecting it to car's battery because a lot of addon devices operate on 7805 and i've never seen one that had problems with 7805 burning out or something :) it might be, but it's pretty rear :)

This might be what you need — a multi-channel level shifter with input and output voltage ranging from 3.3V to 18V:
https://www.ezsbc.com/index.php/featured-products-list-home-page/ls2.html#.WqmSZ2aZNGU
It's no bi-directional: you'll need a couple of boards if you want inputs and outputs from an Arduino to 12V.

What are you trying to achieve?
It's simply unclear if you want to run the Arduino on 12v of the car battery. Or if you want to control the car-windows by hooking into them? Or if you want to read out your car using the arduino.
I'll go with the later since otherwise the question would be stated a little different.
Also, you're looking for something good/cheap.
You don't tell what type of car you want to connect to.
But I think this might help you out: https://www.sparkfun.com/products/13262
25€ isn't that pricey, compared to the car you're fiddling with... So you should go with a little quality (also, you don't need them in batch?).
While a bit subjective, sparkfun could be considered a better vendor than most e-bay suppliers. Both in documentation and support. And in this case, their price isn't that bad. (I'm not affiliated with sparkfun, I actually never bought stuff of them, since e-bay works well for me. There may be hundreds of other good/better suppliers, but this one popped up first on google)
Also, "hacking" your car can have serious safety risks.


text:
Small, Power-Efficient wireless communication with ATTiny85
For a project that I'm working on I need an extremely small, power efficient wireless device (could be radio, or some other interface) to network between a series of ATTiny85s and a larger Arduino. The communication range only needs to be about 1 foot, max. I'm currently using wired I2C, so it would be excellent if someone could suggest a radio or another device that can use the two digital pins previously occupied by the SCK and SDA lines on the ATTiny. I have those two, along with one extra digital pin available for use.
This device needs to be extremely small - this common NRF24L01 package is too big and its SPI interface uses too many pins.
Thanks for your help.

There are ways to interface with a NRF24L01 with ATTiny85 with reduced pin usage plus you could use a ceramic antenna and cut off the large SPI header. It is possible to turn a NRF24L01 really small.

An RF kit like this one. It's a 2-part kit, Tx and Rx separately -- each needing Vcc, GND and one pin. You need both on each ATTiny to be able to transmit and receive.

A similar product but a lot smaller would be the SYN115 and SYN480R based modules. These are however dumb devices, so you need to implement a protocol for them, and handle/prevent collisions, have some data integrity protection, etc.

Definitely. And that will eat up precious memory -- more code...

Link is dead.  Instead of saying something "this one" can you give a model number that can be searched?

I've also had good results with using the Mchr3k - Arduino Manchester Encoding library with those 315mhz RF kits. It has support for ATTiny85 as well.


text:
A simple login page on Arduino Uno
I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

What have you already tried? In order for other people to help you, you need to show effort in doing so yourself.

That is easy to break. Have you considered checking the client MAC address?

I seen some tutorials, a simple webpage with buttons can control "things" connected to relay.

At Atmega based Arduino is the wrong choice to start with.

@Mikael, "Have you considered checking the client MAC address?" Eh, why? How's a MAC address more secure than a username and good password? Are you referring to lack of HTTPS in the question? Also, unless using IPv6 without privacy addressing, MAC addresses don't make it beyond the first network router, so would limit control. And when within that same network, a simple arp -a will show MAC addresses of other devices, and that can easily be spoofed... MAC filtering is not secure at all.

Arduino Uno based security is not security at all. Only something that keeps honest people honest is possible.

I have a page about a tiny web server for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are some limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.
You could put the data to be display into PROGMEM (more information here) or onto an SD card as someone suggested.
The login and password could be stored in EEPROM.

I would also suggest making your UI a "one page" Javascript application. This means all the UI is loaded into the browser up front and all further interactions with your Arduino can be made with simple GET/POST requests eg AJAX/RESTful requests. This approach also has the advantage of allowing you to pre-compress the JS/CSS application code with GZip (just add a Content-Encoding: gzip header) greatly reducing the amount of flash required and overhead of streaming content from flash to the browser.
The main point here being push as much processing as possible into the browser.

Arduino cannot run a web server so it is not possible to do what you want with just using an Arduino board?.
It seems we can run a web server, look at the answer by @Nick Gammon below.
By using a wifi shield and connecting to a local or public web server where your page is hosted you should be able to to do it.
Don't expect to load a full fledged page on an Arduino you have to try posting a few post and get requests to get this working. It will look like a terminal based login.
What is the control page you are trying to do?
If you are ok with spending more money try using a Raspberry pi + Arduino combination.

A ESP8266 would be the cheapest and easiest to use solution. Then you could run the webserver, connect the SD card and the sensors to one device without much hassle.

It is possible to do web servers (even with the Ethernet Shield). Here are a few examples; https://github.com/mikaelpatel/Cosa-HTTP/blob/master/examples/CosaPinWebServer/CosaPinWebServer.ino, https://github.com/mikaelpatel/Cosa-HTTP/blob/master/examples/CosaSDWebServer/CosaSDWebServer.ino and https://github.com/mikaelpatel/Cosa-Shell/blob/master/examples/CosaShellWebServer/CosaShellWebServer.ino

@Avamander ESP8266 wifi shield gives Arduino the ability to connect to a network not to run a webserver. Still we has to depend on other devices to get this working.

@Mr.X Using an ESP8266 as a shield is a total waste, it's like attaching a mortar to a golf cart. ESP itself can handle a web server and much more at once. (Plenty of examples on the web)

Have you tried to change Arduino Uno board to Arduino Yun board?
Yun has a Linux distribution onboard and you can easy configure a web page to control physical objects.
Here some examples:
http://scuola.arduino.cc/lesson/b4EoRkV/Arduino_Yn_Intro_to_web_server
https://github.com/mat-lo/yun-examples

I guess you could do it with Javascript and HTML, and put the pages in the micro SD card.
But it will make it harder (if not impossible) to make the automation.

I read a tutorial, in which Node.js was use for automation, stored in SD card, if that can be done, then login?

here you can found some help (but only with html)
How to make a login form using HTML that connects to the next page
though with nodejs it would be awesome

That's a good help

but it will make it harder (if not impossible) to make the automatization - why? Your answer will be more helpful if you explain your thinking here.

@Fabian W. the link u provided is a very good resource, thank you

Make simple webpage and put it in sd card. If it's just one page with few buttons and bit js even flash memory of controller would suffice.
In arduino code add lines that can detect click on particular button of webpage and control relay/motor etc.
Knowledge of basic post request using js can help. You can't implement php page in arduino as it needs complex processing at arduino side

How exactly would this process you described work? What tools are needed? Currently your answer needs more information, if you improve your answer you'll definitely get a few upvotes.


text:
The most effective way to format numbers on Arduino
I made a big search about how to Format Numbers with the Arduino. I want to format unsigned Longs into a String in this format: "23,854,972".
The most of the snippets I found work only with the standard C / C++ Libraries. They dont work on the Arduino until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.
For my Application it is very important that the solution uses the minimum Flash, SRAM and is fast.
Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is more effective in the sense of speed.
Incoming Number: 23854972
Arduino Program Output: 23,854,972

Have you tried writing a function that does what you're asking?

Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like
digit = '0' + val % 10;
val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:
/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

pre-filling the string with spaces (for padding)
calling the function above
using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.
Here is a simple test program:
unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i < COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}

The most effective way to format numbers on Arduino

If "effective way" is minimum effort you could hack the avr-libc source code for ltoa and do something like below:
char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
{
  int c;

  if (val >= radix)
    s = ultos_recursive(val / radix, s, radix, pos+1);
  c = val % radix;
  c += (c < 10 ? '0' : 'a' - 10);
  *s++ = c;
  if (pos % 3 == 0) *s++ = ',';
  return s;
}

char *ltos(long val, char *s, int radix)
{
  if (radix < 2 || radix > 36) {
    s[0] = 0;
  } else {
    char *p = s;
    if (radix == 10 && val < 0) {
      val = -val;
      *p++ = '-';
    }
    p = ultos_recursive(val, p, radix, 0) - 1;
    *p = 0;
  }
  return s;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  char buf[32];
  Serial.println(ltos(12345678, buf, 10));
  Serial.println(ltos(-12345678, buf, 10));
}

void loop()
{
}

Gives the output:
12,345,678
-12,345,678

Cheers!
PS: Please see the table driven, non-recursive, number conversion in Cosa (source and benchmark) for a lean and faster implementation.

How would I check which answer/solution gives the faster result? I always print delta-micros() but is there a better way?

The above solution is slow. This is a fast hack to show that you do not need all the libraries mentioned in your original question. See @EdgarBonet's answer for a solution that runs much faster. It can be improved with table lookup to avoid division/modulo. That is what the Cosa version does.

Thank you very much. But how you know if this one or the other one is faster? How to determine it?

Estimate the algorithms complexity and behavior. Read the generated assembly code and calculate the number of clock cycles. Write a test program and verify.


text:
Arduino pins vs Esp8266MOD
I had used Arduino Uno & RFID but now i want to run same code in Esp8266MOD.
i have installed all the drivers and everything else to run esp8266 in Arduino IDE but i dont know how to connect rfid in esp8266. Can someone please compare which arduino pin & esp8266 pin are similar
 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             ?
 * SPI SS      SDA(SS)      10            ?
 * SPI MOSI    MOSI         11 / ICSP-4   ?
 * SPI MISO    MISO         12 / ICSP-1   ?
 * SPI SCK     SCK          13 / ICSP-3   ?

table filled
 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             any, recommended 5
 * SPI SS      SDA(SS)      10            any, recommended 4, possible 15
 * SPI MOSI    MOSI         11 / ICSP-4   13
 * SPI MISO    MISO         12 / ICSP-1   12
 * SPI SCK     SCK          13 / ICSP-3   14

io 15 is SS if esp8266 is slave. but this pin must be LOW at boot. you can use it as SS if SS pin of reader doesn't pull-up.
io 4 and io 5 are untroubled pins.
io 0 and io 2 are with io 15 boot configuration pins and can be used only if they don't change the required boot state.
io 1 and io 3 are Serial interface
io 16 is RTC pin and is used for wake up from deep slepp
warning: does the reader work with 3.3 V?