text:
Arduino Pro Mini maximal and recommended current per pin
In Arduino Pro Mini (3.3V) specs indicated the maximal and recommended current per pin, 40mA and 20mA respectively. Does these values means input current (i.e. safe input current Arduino can handle) or output current?

It is the amount of current the pin can source or sink when in OUTPUT mode.
That is, the amount of current that can flow from the pin to ground, or can flow from VCC into the pin.
You can understand it better if you learn how a GPIO pin works.

So, basically, there's no needs in current limiting resistors to protect the external processor connected to Arduino?

It can be good to include a small series resistance when connecting microcontrollers together in case both have their pins set to output and one is high and the other low.

Will the 100 Ohm 1/4 Watt resistors directly soldered on the wires quite adequate for this? While this resistors protects the buffer from being damaged, it also limits the drive strength of the buffer, that may
result in degraded operation.

100 ohm is pretty much perfect. The drive strength reduction is minimal. You are only driving one gate pair at a few (tens of) pF. It would take many times that to affect the kind of frequency signals an Arduino can produce.

Incidentally that is exactly what the Arduino uses between the 328p and the 16u2.

In datasheet, paragraph 32.1 is stated:
DC Current per I/O Pin 40.0mA

See comments below about the implication. (I will not delete this questions because of the useful comments below from Majenko and Milliways, unless downvoted).
See:

No, it implies both source and sink which are different to input (high impedance) and output (sources and sinks current).

@Majenko ... where can that be found in the data sheet?

Input current is not specified (except for pull-up current). DC Input current would be negligible (of the order of nA). Of more significance in a practical circuit would be the input capacitance ~10pF.

Well. I mainly worry about max current, mA that will be applied from Arduino output to digital input pins of external chip to which Arduino connected to.

In that case the following table will be sufficient (and more useful in general with the remarks of Majenko and Milliways

Does these values means input current (i.e. safe input current Arduino can handle) or output current?

Depending on your definition of input.
The numbers are the max current that an output pin can provide , either flowing in or out of the pin.
The max current you can force into or out of an input pin is mostly determined by the clamp diodes. Typical a few ma.

The clamp diodes start working at 0.5V above VCC and 0.5V below GND. There is a Application Note AVR182 that mentions that a maximum of 1mA is allowed to push into or pull from an input put of an AVR microcontroller. I use this 1 mA to calculate the maximum input voltage for a voltage divider with two resistors.


text:
is it possible to program an arduino with usb/ttl adapter
i want to upload sketch into arduino uno using usb/ttl adapter.i tried searching for it, but found about programming arduino using another. can anyone help me.

This may be obvious to you, but may not be to us.  What are you connecting to each end of the USB to TTL adapter cable?

I'm trying to understand your question, why can't you just program it by plugging a USB lead between a PC and the board.  Are you doing something special?

The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).
And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;
Arduino  - USB/TTL
Tx       - Rx
Rx       - Tx

And to get the Arduino inte "programming" mode:

Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
Manual way, press the reset button when the Arduino IDE starts to upload the code.

The Uno is normally programmed by its on-board USB adapter.
The Pro Mini does not have an on-board adapter, and is normally programmed with an external USB/serial adapter. This should also be possible with Uno.

source: Stack Exchange

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

sort: votes


text:
Using all ten capacitive touch inputs on the ESP32
I am using a Wemos Pro ESP32 development board and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

Running this code on my board produces no difference in reading for T1...
#define numTouchPins 10
byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
byte touch[10] = {};

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

void loop() {
    for( byte pin = 0; pin < numTouchPins; ++ pin ) {
        touch[pin] = touchRead( touchPins[pin] );
    }
    for( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print( "\t" );
    }
    Serial.println();
}

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, is there a way to change the pinmode from digital-in to touch-in once normal boot has completed? Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?

is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.
You cannot have touch inputs connected to anything else.  The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.

Ok. So you can't use Touch1 on GPIO0 because of this hardware setup ... but can you set it to be usable on another pin? In this hackaday article they talk about an internal multiplexer allowing you to map one pin's functionality to another's  ... Any idea how that would be done?

No clue whatsoever. Probably not possible with analog pins - that kind of functionality is usually only for moving things like UART, SPI, etc.

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


text:
How to burn the bootloader onto a bare chip without using an Arduino board
How do I burn the UNO bootloader onto ATMEGA328P-PU without using an Arduino Uno board. That is burn directly from my PC or Android device??
I've tried nothing, I don't know a thing about microcontrollers ☺

Start by using an AVR programmer (ex: USBasp from Ebay for a few bucks)  to burn the bootloader to an Arduino Uno or Nano first--so you can see the expected process and outcome, then try the standalone tutorial posted by MatsK.

The short answer is, you need a AVR programmer
It is a tutorial on the Arduino website:
https://www.arduino.cc/en/Main/Standalone
And the section Bootloading your chips OPTIONAL will answer the question.

A AVR programmer is aka ISP programmer


text:
Duplicate libraries while compiling for ESP32 in the Arduino IDE
I have just added the ESP32 toolchain to the Arduino IDE (v1.8.0) on Windows 10.  To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" (Yes my C drive is called D, its a long story)
I managed to compile and run Blink and after several minutes of celebration I tried the ESP32 Example Wifi->WifiScan.  It failed to compile because
WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'
In file included from D:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\spi_drv.cpp:21:0:

D:\Program Files (x86)\Arduino\libraries\SPI/SPI.h:16:26: fatal error: avr/pgmspace.h: No such file or directory

compilation terminated.

Multiple libraries were found for "WiFi.h"
 Used: D:\Program Files (x86)\Arduino\libraries\WiFi
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\WiFi
Multiple libraries were found for "SPI.h"
 Used: D:\Program Files (x86)\Arduino\libraries\SPI
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\SPI
exit status 1
Error compiling for board ESP32 Dev Module.

If I am reading this correctly, there are a couple of duplicate libraries, Arduino versions and ESP32 versions and the IDE picked the Arduino versions.
Is there a way of telling the IDE to prefer the ESP32 libraries rather than Arduino ones?  I suspect all I need to do is change the order of the -I and -L commands, but I don't have a clue how, or if that's the right thing to do.

Why do you have WiFi and SPI libraries in your contributed libraries folder...?!?!

In an attempt to rename the directory I found that the espresiif\ESP32 directory is locked by a system process PID:4 which is holding handles on 10 of the files within those directories.  I uninstalled the drivers for the esp32, no joy, logged on as admin and ran as admin, but no joy.  I had to alter the security permissions so that System couldn't access that directory reboot and then delete espressif\esp32.    At this point I also unistalled Arduino IDE and re-installed a fresh copy of 1.8.3. [continued]

I followed the installation instructions (without using GIT) and 'installed' the esp32 pack to D:\Users\***\Documents\Arduino\hardware\espressif\esp32 and again, the same result the IDE does not pick up the ESP32 boards, but does pick up the esp8266 boards.    If I move the libraries to D:\Program Files (x86)\Arduino\hardware then the IDE detects the boards and when I compile the example I get a duplicate WIFI.h BUT it now picks the esp32 version.  I think the problem is why doesn't it work when the esp32 folder is in My document?

"I think the problem is why doesn't it work when the esp32 folder is in My document". Probably because you have a different sketchbook folder configured (see File > Preferences > Sketchbook location).

"when I compile the example I get a duplicate WIFI.h BUT it now picks the esp32 version". OK so you correctly named the architecture folder and it solved the problem, just as I said in my answer, so why didn't you accept it?

Please don't delete your question after someone has taken the trouble to answer it. I have undeleted it.

#include "filename.h" will look in the sketch folder
#include <filename.h> will look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path

So the system library path (-L) is defined in perferances.txt, thanks for that.

#include <filename.h> will only look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path this is wrong. The libraries subfolder of the sketchbook is only one of 6 folders in the include path in a standard hardware package, none of which are configured in preferences.txt. There is no need to edit preferences.txt, you can just do File > Preferences > Sketchbook location. Also, take a second to actually view your answer before submitting it to see how the markdown is being rendered.

The problem is that you have incorrectly installed the ESP32 hardware package. If you look at the official installation instructions:
https://github.com/espressif/arduino-esp32/blob/master/README.md#installation-instructions
you'll see that the architecture folder should be named esp32, not ESP32 as you have named your folder.
When multiple libraries contain a header file of the same name, one of the factors the Arduino IDE uses to decide which gets precedence is architecture matching. The architecture of the selected board is determined by the name of the architecture folder of the hardware package of that board. So because you named your architecture folder ESP32, that's the architecture value of the selected board. The architecture of the library is determined by the architectures property value found in the library.properties file of the library. In this case that value is set to esp32:
architectures=esp32

So because the architecture value of the library in the ESP32 hardware package doesn't match the architecture of the selected board, the SPI library found in the Arduino IDE installation folder is used instead.
If you rename the architecture folder to esp32 the correct library will be used.
A few other notes:
For some reason you have put a copy of the SPI library at D:\Program Files (x86)\Arduino\libraries\SPI. This makes no sense because that library is architecture specific. Each hardware package has its own version of the SPI library bundled.
In addition to using the incorrect architecture folder name in your installation of the ESP32 hardware package, you installed it to the Arduino IDE installation folder instead of the sketchbook folder, as recommended in the instructions.
You seem to have a bad habit of messing with your Arduino IDE installation folder. You should never modify or add files to the Arduino IDE installation folder. The reason is that all changes you make to that location will be lost anytime you upgrade to a new version of the Arduino IDE and it also makes troubleshooting more difficult since you are working with a non-standard installation. Instead you should always install libraries and hardware packages to the sketchbook folder where they will persist through IDE updates. I recommend you to move any customized files out of the Arduino IDE installation folder and then reinstall the IDE to make sure you are working with a stock installation.

per1234, I'm sorry but you are wrong.  I have never altered anything in the Arduino install folder.  Everything that is in there was installed in there by the installer or the board manager.

To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" "D:\Program Files(x86)\Arduino\hardware" is your Arduino IDE installation folder, correct?

Then where do you have the Arduino IDE installed?


text:
LED Webserver control not working
I've got an Arduino Uno and Ethernet shield, trying to test it out with a simple on off switch for the on-board LED.
My Code is this
// FILENAME = LED2.ino
// SOURCE= http://www.instructables.com/id/Control-an-LED-over-the-internet-using-the-Arduino/
// Control an LED over the internet using the Arduino Ethernet Shield and Transistor
// http://www.instructables.com/id/Control-an-LED-over-the-internet-using-the-Arduino/
// code SOURCE= http://pastebin.com/CZ6J62qJ

#include <SPI.h>
#include <Ethernet.h>

#include <Servo.h>
Servo myservo; // create servo object to control a servo

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 177 }; // fixed IP addr in LAN
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port

String readString;
//////////////////////
void setup()
{
    pinMode(6, OUTPUT); //pin selected to control LED
    pinMode(13, OUTPUT);
    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
    //the pin for the servo co
    //enable serial data print
    Serial.begin(9600);
    Serial.println("server LED test 1.0 ---- FILENAME = LED2.ino "); // so I can keep track
}

void loop()
{
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();

                //read char by char HTTP request
                if (readString.length() < 100) {

                    //store characters to string
                    readString += c;
                    //Serial.print(c);
                }

                //if HTTP request has ended
                if (c == '\n') {

                    ///////////////
                    Serial.println(readString); //print to serial monitor for debuging
                    client.println("HTTP/1.1 200 OK"); //send new page
                    client.println("Content-Type: text/html");
                    client.println();
                    client.println("");
                    client.println("");
                    client.println("<TITLE>Home Automation</TITLE>");
                    client.println("");
                    client.println("");
                    client.println("
Home Automation
");
                    client.println("
");
                    client.println("
");

                    client.println("Turn On Light");
                    client.println("Turn Off Light
");

                    client.println("");
                    client.println("");

                    delay(1);
                    //stopping client
                    client.stop();

                    ///////////////////// control arduino pin
                    if (readString.indexOf("?lighton") > 0) //checks for on
                    {
                        digitalWrite(13, HIGH); // set pin 6 high
                        Serial.println("LED On");
                    }
                    else {
                        if (readString.indexOf("?lightoff") > 0) //checks for off
                        {
                            digitalWrite(13, LOW); // set pin 6 low
                            Serial.println("LED Off");
                        }
                    }
                    readString = ""; //clearing string for next read
                }
            }
        }
    }
}

The problem is that when I click a button (either on or off)  the LED will blink twice, and then remain off.
My serial monitor also shows 2 HTTP requests, I'm not sure if this is usual or not?
server LED test 1.0 ---- FILENAME = LED2.ino
GET /?lighton HTTP/1.1

LED On
GET /favicon.ico HTTP/1.1

GET /?lighton HTTP/1.1

LED On
GET /?lighton HTTP/1.1

LED On
GET /favicon.ico HTTP/1.1

GET /?lighton HTTP/1.1

LED On
GET /favicon.ico HTTP/1.1

GET /?lightoff HTTP/1.1

LED Off
GET /favicon.ico HTTP/1.1

Would appreciate any help!

What button? What is pin 6 used for?

Might need to reconsider using pin 6 for the LED as pin 13 is used by the Ethernet shield for SPI clock (SCK).

@lookalterno It's the button on the webserver control  (html button) if you view my code

Good problem. You only test and switch the LED after a "\n" and then clear the readString variable.

@LookAlterno OK.. So how could I rectify this issue?

How do you display the web page the first time? I don't see a GET /favicon.ico inmediatly before the first GET /?lighton. Can you edit your trace to indicate where you press the HTML button?


text:
How can my library source code instantiate an object from another library?
I'm having trouble explaining my issue. What I'm doing is creating a library to work easily with the RFID reader/writer RC522 module. I need to create an object of the library MFRC522 in my .cpp file to be able to communticate with the module itself. I want my constructor end up like this:UltimateRFID rfid(53, 5);, the parameters being the slave select and the reset pins, respectively.
The problem is that I don't know how to make my constructor so that it is within the scope of the functions that require the MFRC522 object to be called. Below's my code.
#include "Arduino.h"
#include "UltimateRFID.h"
#include <MFRC522.h>

MFRC522::MIFARE_Key key;

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

void UltimateRFID::initialize() //sample of a function that uses the MFRC522 object
{
  //digitalWrite(49, HIGH);
  digitalWrite(2, LOW);
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  mfrc522.PCD_Init();
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

}

Now comes my header file, although I'm not sure it matters much.
#ifndef UltimateRFID_h
#define UltimateRFID_h

#include "Arduino.h"
#include <MFRC522.h>

class UltimateRFID
{
  public:
    UltimateRFID(int ss, int rst);
    void initialize();
  private:
    MFRC522::MIFARE_Key key;
};

#endif

Please be patient, it's my first library.

Why not have your class just extend the MFRC522 class?
#include <MFRC522.h>

class UltimateRFID : public MFRC522 {
    private:
        MIFARE_Key key;

    public:
        UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
        // your other methods
        void initialize();
};

void UltimateRFID::initialize() {
    //digitalWrite(49, HIGH);
    digitalWrite(2, LOW);
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    PCD_Init();
    if ( ! PICC_IsNewCardPresent()) {
        return;
    }
    if ( ! PICC_ReadCardSerial()) {
        return;
    }
}

UltimateRFID rfid(53, 5);

void setup() {
    rfid.initialize();
}

void loop() {}

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.
Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.

And I don't need a constructor in my source file? Only in the header?

You can have a constructor if you want. There is an empty one in the header at the moment (the {}). No content is needed since the initialisation list calls the parent constructor for you.

I did just that and I get a compilation error: collect2.exe: error: ld returned 5 exit status.

Did you copy and paste my code? I just noticed a typo in the initialisation list. I am not at my computer at the moment (1:48am here) so cannot test it right now.

I did copy it, fixed the typos (MFRC522 instead of MRFC22/MRFC622) but the error appears anyway.

Strange. It compiles for me. You are including the MRFC522.h in both the library and sketch, aren't you?

To be sure I have updated my example into an SSCCE.

Still get that error, and now it appears in every sketch. But that's for another day. Thanks for your answer.

While @Majenko's answer is probably best (I +1'd it), for completeness, here's how to construct a member variable with parameters:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) : mfrc522(ss, rst) {}

    protected:
    MFRC522 mfrc522;
};

"placement new" is another option:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        new (&mfrc522) MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

However, this method calls the default ctor - which may or may not be an issue. This is usually reserved for re-initializing an existing object.
There's also assignment:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        mfrc522 = MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

This also calls the default ctor and works best if the class provides operator=.

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

As you note, that instance would go out of scope immediately. The simplest thing would be to put a pointer to the other class in your class definition. Then in your init function do a new to create the instance of the class, passing the appropriate parameters.

In init and in all other functions that use MFRC522 objects?

No, you only do a new once (for a particular instance). Read up on new/delete in C++ tutorials.


text:
Connecting Arduino to PC through Slimline SATA instead of USB?
I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.
The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)
Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?

No, there is no way of connecting an Arduino to a SATA port. You require USB or UART. SATA is a specific dedicated port, whereas USB is, as the name suggests, Universal. So USB can become SATA but SATA can never become USB.

Ok, that must be the case. Why else are there no available products? Is it so because the protocol used in SATA does not support what USB supports?

SATA supports SATA and only SATA. Because SATA is SATA. It is, as its name suggests, Serial ATA. Nothing more, nothing less. USB is a UNIVERSAL Serial Bus. It's like a piece of wire. SATA is the metal down the middle, and USB is the plastic round the outside. The plastic can contain the metal, but the metal cannot contain the plastic. The plastic could also contain a fibre optic instead of the metal. Or it could contain water. Or air. Or any other number of things. The metal will always be the metal though.

There is a USB port right next to the CD drive. I think i could solder those USB pins with 2 switches to connect / disconnect data with the arduino. That way if no device is connected to that usb port, i could connect it to the arduino.

Doable, sure. You may also find another USB port inside the computer somewhere. Maybe there is an SD card slot that is connected through USB you could sacrifice, for example.


text:
Arduıno button problem
I did a project with a fingerprint sensor. You can do the fingerprinting process by typing down 4 on the serial port, but in the same time i want to do this process with pressing another button.Can someone help me?

code  http://www.heypasteit.com/clip/0IIQ6G
> #define  VB

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>

SoftwareSerial mySerial(10, 11);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

char data;
unsigned int p;
uint8_t id;

void setup()
{
  Serial.begin(9600);
  finger.begin(57600);
  Serial.println("Sensore baglaniyor!");
  if(finger.verifyPassword())
  {
    Serial.println("Baglanti basarili!");
  }
  else
  {
    Serial.println("Sensor bulunamadi ");
    while (1);
  }
}

void loop()
{
  delay(100);

  if(Serial.available()>0)
  {
    data=Serial.read();

    if(data=='1')
    {
      Serial.println("Delete all ID records");
      finger.emptyDatabase();
      delay(50);
      EEPROM.write(0,-1);    //reset ID counter
    }
    else if(data=='3')
    {
      id = EEPROM.read(0) + 1;    //get next available ID
      Serial.print("Enrolling ID #");
      Serial.println(id);
      getFingerprintEnroll(id);
      delay(50);
      EEPROM.write(0, id);        //save current ID
    }

    while (data=='4')
    {
      getFingerprintID();
      delay(50);

    }
  }
}

uint8_t getFingerprintEnroll(uint8_t id)
{
  uint8_t p = -1;
  Serial.println("Waiting for valid finger to enroll");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(1);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  }

  Serial.println("Remove finger");
  delay(1000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER)
  {
    p = finger.getImage();
  }

  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(2);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return p;
  }

  p = finger.createModel();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Prints matched!");
    break;
  case FINGERPRINT_ENROLLMISMATCH:
    Serial.println("Fingerprints did not match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  p = finger.storeModel(id);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Stored!");
    break;
  default:
    Serial.println("Unknown error");
    return p;
    break;

  }
}

int getFingerprintID()
{
  p = -1;
  Serial.println("Waiting for registered ID");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return -1;
  }

  p = finger.fingerFastSearch();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Found a print match!");
    break;
  case FINGERPRINT_NOTFOUND:
    Serial.println("Did not find a match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  digitalWrite(A1, HIGH);
  delay(500);
  digitalWrite(A1, LOW);
  delay(2000);

  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with accuracy value of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

If you want to use 2 to get the finger print then change the line while (data=='4') to while (data=='2').  If you want to use 4 or 2 then change it to while (data=='4' || data=='2').  Is that what you mean?

@Look Alterno Thanks, but it’s not what I mean. I  mean doing the process with pressing random button.
Note:Serial port working

while (data=='4') will loop forever once the user enters 4, since you never modify data once you enter that loop. Is that the desired behavior?

Why is “Can someone help me?” not an actual question?

Take a look at the Button sketch in the examples menu in the Arduino IDE. That is the simplest example of how to use a button in Arduino.
Circuit
This is the test circuit. When you press the button, the built LED turns on/off.  The circuit is applicable to any Arduino Uno, Mini, etc. The two wires at right are not really needed, but it doesn't hurt if you put them in the breadboard).
Note: What follows is an excerpt from https://www.arduino.cc/en/Tutorial/Button.

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.
When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH.
You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.
If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.
Code
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

Replace digitalWrite(ledPin, HIGH); with getFingerprintID(); that will start the getFingerprintID(); when the button is pressed.

@MatsK I do not know enough code , So I do not understand what you said , If you give the code example

The code example is above! Look for digitalWrite(ledPin, HIGH);


text:
Send a polymorphic object over serial
I am sending a polymorphic object over serial between two Arduinos. The transmission should be fine, indeed if on the receiver side I static_cast the pointer to the Derived class it works properly. On the other hand if I try to call virtual functions on the Base pointer, Arduino resets. What is causing this behaviour?
Some samples of the code follows.
Sender:
RS485_Serial bus;
void loop ()
{
  Random r(1); //targeting device 1 in the bus
  if (r.request(bus)) { blink(r.val); } //make a request for a random number
                                        //blink the led the given number of times

  delay(1000);
}

Receiver:
RS485_Serial bus;
bus.set_address(1);
void loop ()
{
  listen(bus);
}

Selected common parts:
struct Action {
  byte target_address;

  Action(byte addr): target_address(addr) {}
  virtual ~Action() {}

  virtual size_t size() const { return sizeof(*this); }
  virtual int  vrequest(RS485_Serial &) = 0;
  virtual void vrespond(RS485_Serial &) = 0;

  int request(RS485_Serial & bus) {
    bus.write(reinterpret_cast<byte*>(this), size());
    return vrequest(bus);
  }
  void respond(RS485_Serial & bus) {
    vrespond(bus); // <--- This virtual call makes the sender reset
  }
};

struct Random: Action {
  size_t size() const override { return sizeof(*this); }
  int val;
  Random(byte address): Action(address) {}

  int vrequest(RS485_Serial & bus) override {
    return bus.read(val);
  }
  void vrespond(RS485_Serial & bus) override {
    bus.write(static_cast<decltype(val)>(random(2,5)));
  }
};

void listen(RS485_Serial & bus) {
  byte * data = nullptr;
  byte length = 0;
  if ( bus.read(data, length) ){
    Action & a = *(reinterpret_cast<Action*>(data));
    if (a.size() == length) blink(3);
    if (a.target_address == bus.address) {
      a.respond(bus);
      //static_cast<Random*>(&a)->vrespond(); works but it has no point
    }
  }
}

My doubt is that if the vtable is stored in different positions, than the vtable pointer in the object obtained by the receiver will be off, causing the crash.

I'm voting to close this question as off-topic because this is general C++ programming, not specific to Arduino (other that the incidental use of a serial link).

Please edit your question to include complete, minimal sketches that demonstrate the issue.

@LookAlterno could this be moved to stackexchange?

You are accessing a Null pointer and getting a segmentation fault.  Suggest you test you code under Visual Studio or Linux equivalent and see where the debugger flags the fault.

@LookAlterno - I agree and disagree, because there is some element of hardware (serial) that could be causing the issues, most likely because the data is being sent as binary and read as text or similar.

I think you're going to have to show your code for both sender and receiver for us to have any clue what is or might be going on.

Action::vrespond is PV and can't be called. Only Random::vrespond can be called.

@Majenko it is supposed to be like that: the call should be resolved to Random::vrespond. If it was like you said it shouldn't even compile.

How can it be resolved to Random::vrespond if it's cast to Action?

If you have super-class A that is the parent of both classes X and Y, and foo is a PV interface in A and implemented in both X and Y, and you cast an object to A, how does it know where foo is implemented? It could be in either X or Y. It can't know that kind of thing. You have to cast it to the right class to access the functions in that class.

@Majenko The point of polymorphic pointers is to avoid that cast by means of virtual functions. See: http://coliru.stacked-crooked.com/a/a5ffb8ecab28708a

@Majenko The compiler creates some machinery for that to work (vpointer and vtable) which I suspect is not created on the receiver or at least it doesn't match with the sender. I may have to write them myself to ensure that they match on both sides.

I do not agree that this question would suit StackOverflow better, this is quite Arduino specific for multitude of reasons for ex. Harvard architecture and serial implementation, just to name a few.

I think http://stackoverflow.com is the correct forum for your question. Your problem is how to serialize/deserialize correctly an object in C++.
An easy way to do it is simply send the values (not the object) and recreate the object at the other side. So, now your problem is reduced to send and receive a bunch of int's, float's, string's, whatever.
Why you want/need to do that?

The object is serialised fine, but I think that there might be inconsistencies between the vtables allocated on the two boards. The aim is to have an arduino launching functions on another one which I planned to do encapsulating lambdas inside polymorphic objects. I may just fall back to a plain old switch statement.

I looks like you want to send some code (as opposed some data) to be executed at the other Arduino. Arduino uses Harvard architecture, so you can't put code in RAM and execute it. I'm curious about what are you trying to do.

Also take in mind sometimes on different CPUs int values from 2 to 4 bytes can be stored differently (it's called little/big endian).

@DarioP the point is that you can't serialize the methods of an object between machines of this type; you can only serialize the data which uniquely specifies of object of the class.  You need to have a compatible class on the receiving side, and inflate an instance of it with a constructor taking the serialized data.

I suspect then that the object contains a pointer to the code for vrespond, which is at a specific (and differing from program to program) location in flash memory. An object in C++ isn't a single atomic item, it is a collection of data and pointers to functions. On a Harvard architecture system the data is in RAM and the code is in Flash (you cannot typically execute code from RAM). The compiler chooses where to place the code in Flash when it compiles (well, the linker does). That won't be the same address in different programs. All you are doing is sending over the addresses in flash that the code resides at - and those addresses are incorrect. By specifically casting it to a type that has code available you are also telling it where that code resides. Without that manual cast you are having to rely on the (incorrect) function pointers.
It is a bad idea to transfer objects like that from one system to another. It is better to transfer just the data and feed that data into an existing object created on the receiver. How you send and receive that data and feed it into the object is up to you.


text:
What to use instead of a USB to serial converter
The usb to serial converter i found was $4 .maybe i could use something less expensive,like jus a port.I need serious help ,the serial port was about $1

To do what? You need to elaborate a bit more, this is to fussy!

To upload a sketch.....I don't want to use up cash without knowing what I'm doing.I've lost a lot of cash on experiments.

Any USB to Serial converter works. The only culprit is DTR, if that exist on the USB Serial, then you can program the arduino without any manual interventions, if it is missing, then you have to press the reset button before the Arduino IDE starts to upload the program, this will put your arduino in to "programming mode".

Here is a example on how a programming without DTR, https://www.youtube.com/watch?v=TFARDFn8fs0

Oh by the way there isn't a cheaper way than a USB to serial converter. If you have a Arduino UNO laying around, you could use the USB to serial converter in that one, but you have to pull out the 328 chip first. Ref.: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

You don't lost cash in experiments; you gain experience and knowledge, and have a wonderful time playing with things.

You can buy a CH340 adapter board with the standard "FTDI header" pinout (including DTR/CTS for auto-reset) on eBay for $1.46 with free shipping. You can get them as low as $0.67 on Aliexpress without DTR/CTS broken out.

"the serial port was about $1" What does that mean?

May I suggest RS232 connection? It is an ancient tech but it might work for you. I am adding a tutorial. Also a component from eBay, which is 0.99 US dolar.

The usb to serial converter i found was $4 .

you can find old Nokia data cable (a form of usb/ttl converter) for less than a dollar, or free if you happen to have one.
alternaively, usbasp programmers are very simple / inexpensive.
diy is possible but you need to count your time. tools need to be reliable so i tend to rule that out.


text:
Can the WiFi on ESP8266 be disabled?
I've been reading a lot on the ESP8266, but still my understanding is shaky. I have the Arduino IDE running on a PC, which uses wires to connect to the ESP8266 via a USB device (Device Manager > Ports (COM & LPT) > Silicon Labs CP210x USB to UART Bridge). This is how I uploaded a simple sketch to the ESP8266.
It works and has been installed in the wall. I'm happy and relieved to complete the project... except for one small thing: I noticed that it shows up on WiFi. I can connect to it without a password, with a "Limited" connection. After that I'm lost, but I wonder if someone who knows what they are doing can use this unsecured connection to hack my install. I'd like to disable the WiFi, if possible, since I'm not using it.
The worst part is my learning curve now starts over. I thought that when my sketch gets uploaded, it replaces the original firmware. Now "firmware" is an elusive concept. I keep thinking that it shows up on WiFi because of something running in firmware. My sketch hasn't any code for WiFi. What am I missing/do I have wrong?

Please post the code (sketch) you are running. And to turn of the WiFi use WiFi.forceSleepBegin();

@ MatsK I use the Arduino IDE to flash my esp8266, and tried adding "WiFi.forceSleepBegin();"  in the "void setup () {" section, but uploading gave an error about not being in the "scope".  So I tried Sketch > Include Library > Contributed Libraries > WiFi This time the uploading error was "'class WiFiClass' has no member named 'forceSleepBegin'" I don't know how to post the code I'm running, but I'm trying to learn how. When I do, I will post the code as per your request. Thanks

Did you #include <ESP8266WiFi.h> ?

@ Jaromanda X  Thanks so much, I had included the wrong library because I forgot to change from "Arduino Pro Mini" to  "Generic ESP8266 Module". After selecting the right board, the code uploaded without error and this seems to have solved my problem since I no longer see the esp8266 in the list of available WiFi connections. I'm still very confused as to how the WiFi got turned on in the first place, and about the question of firmware. I think I will post another question about this subject.

@ MatsK Since I  can now disable the WiFi, I don't think there is any point in posting the code. However, if you could help with my confusion about firmware I mentioned in my question, it would be most appreciated

@Ray71 It is also god if you click the up arrow to the left of the comment, that will give me credits, and that is what gives you score and motivation to answer more ;-)

To turn of the WiFi add the WiFi library and use WiFi.forceSleepBegin();

Firmware is the program/sketch that controls a MicroController Unit aka MCU (and in this case a Arduino).
Best explanation I know is here: https://en.wikipedia.org/wiki/Firmware

Many esp8266 devices by default start in (WIFI_AP) SoftAP mode, and will appear as a wifi network access point, waiting for stations to connect.
User code in any sketch, should explicitly set wifi to the appropriate mode. If you do not need wifi, set the wifi mode off. To do this with the Arduino IDE, an esp8266 must run a sketch at least once that includes the wifi class to use its .mode() method.
#include <ESP8266WiFi.h>

void setup() {
   Serial.begin(115200);
   WiFi.mode(WIFI_OFF);
   if (WiFi.getMode() == WIFI_OFF)
      Serial.println(F("\nWifi mode is WIFI_OFF, until it is explicitly changed"));
}

The mode setting persists across power on and restart/reset cycles, until user code specifies a different mode. So once run on the esp8266, the all the lines above (except setup()) could optionally be removed from subsequent sketches uploaded to the esp8266, and the wifi will remain off.
Firmware is lower-level software that runs between the hardware and your higher-level sketch. Many esp8266 came with Espressif firmware and a sketch installed.
If you are concerned about energy consumption, investigate waking up the esp8266 with the radio disabled, eg.
ESP.deepSleepInstant (microseconds, WAKE_RF_DISABLED);

You control WiFi using wifi.setmode().
ESP8266's WiFi is very versatil. You can be a client and/or an access point. You can get your IP from DHCP or static.
Per default, ESP8266 start in STATIONAP mode (as client and access point).
This is the pertinent part from the official page
wifi.setmode()
Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network
Access point (AP) mode, where it creates its own network that others can join
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network
WiFi off

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.
Note
WiFi configuration will be retained until changed even if device is turned off.
Syntax
wifi.setmode(mode[, save])

Parameters
mode value should be one of
    wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
    wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
    wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
    wifi.NULLMODE changing WiFi mode to NULL_MODE will put wifi into a low power state similar to MODEM_SLEEP, provided wifi.nullmodesleep(false) has not been called.

save choose whether or not to save wifi mode to flash
    true WiFi mode configuration will be retained through power cycle. (Default)
    false WiFi mode configuration will not be retained through power cycle.

Returns
current mode after setup
Example
wifi.setmode(wifi.STATION);

See also
wifi.getmode() wifi.getdefaultmode()

Note: this answer refers to NodeMCU Lua code. The ideas can be used by Arduino ESP8266, but method names must be modified.

This is the best solution I have found so far (source: GitHub gist)
The two functions below are all you need to toggle your WiFi chip. The huge advantage of using these is that they work without having to invoke an ESP.deepsleep() call.
Mind you, if you have already done an ESP.deepsleep(time, WAKE_RF_DISABLED) that means that your WiFi chip has been disabled altogether, and calling WiFiOn() will NOT be able to toggle it back ON. In this case you MUST do ESP.deepsleep(time, WAKE_RF_DEFAULT). But once you WiFi chip has been re-enabled, you can call WiFiOn() and WiFiOff() as many times as you please, they will work fine.
extern "C" {
    #include "user_interface.h"  // Required for wifi_station_connect() to work
}

#include <Arduino.h>
#include <ESP8266WiFi.h>

#define FPM_SLEEP_MAX_TIME 0xFFFFFFF

void WiFiOn();
void WiFiOff();

//------------------------------------------------------------------------------

void setup() {

    WiFiOn();
    delay(5000);
    WiFiOff();
    delay(5000);
    ESP.deepSleep(1e6 * 10, WAKE_RF_DEFAULT); // sleep 10 seconds

}

void loop() {
    ;
}
//------------------------------------------------------------------------------

void WiFiOn() {

    wifi_fpm_do_wakeup();
    wifi_fpm_close();

    //Serial.println("Reconnecting");
    wifi_set_opmode(STATION_MODE);
    wifi_station_connect();
}

void WiFiOff() {

    //Serial.println("diconnecting client and wifi");
    //client.disconnect();
    wifi_station_disconnect();
    wifi_set_opmode(NULL_MODE);
    wifi_set_sleep_type(MODEM_SLEEP_T);
    wifi_fpm_open();
    wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);

}

WiFiOff caused a crash for me. I called it from the program loop once, and it triggered a Soft WDT reset.

Note: the code in this answer relies on SDK functions, which may be unfamiliar and confusing to Arduino IDE users, especially early in their learning, like the OP. Better to focus on one system or the other first.

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


text:
Arduino nano does not draw enough power
I am trying to run a sensor from my switch using POE. I have created a temp/humidity sensor using the MySensors directions https://www.mysensors.org/about/arduino.  I decided to use a nano due to the USB connector. I have connected this to my switch via a TP-Link POE splitter set to 5 volt output.
When connected, the switch provides power for a second or two then turns off for 10 seconds or so before coming on again. I believe the Switch is testing the circuit not detecting enough power being drawn and shuts down. It then goes through the cycle again. Note: both the power LED on the switch and the nano LEDS light up while power is supplied. I believe the nano itself only uses about 20mA
I have tested with another device that requires 9volts (hand held phone) via the splitter and it works fine with power provided consistently.
I was wondering if there is some circuitry I can add before the Arduino that will draw a little more current but still provide a constant 5V to the nano.
Additional information. The switch is a Linksys LGS124P. I have tried to find more detail regarding the required power but can only find this datasheet that does not provide that level of detail
http://downloads.linksys.com/downloads/datasheet/1224699456700/25685_LINKSYS_unmanaged_POE_switches_PROD_Revised.pdf

First you need to work out exactly how much current needs to be drawn in order to make it stable. For that you really want an adjustable dummy load with current display. When you know how much current you can calculate the right size of resistor to use across the supply to draw the amount of current without wasting current or overheating and burning.

You may alternatively find the specification in the manual for the switch, but since you don't tell us what the switch is we can't help you there. Also this is not an Arduino question but a general electronics question. It should be on EE.SE.

A resistor or a light bulb in parallel with the Arduino will increase the power consumption.

Combination of this and Majenko's comments give me the answer I need. thanks


text:
Arduino Leonardo as keyboard for an iPad
I'm trying to make a Arduino Leonardo as a Keyboard for an iPad. I was successful with an Arduino UNO. However I'm hoping to use an ATmega 32U4 because of the better HID functionalities and smaller boards like the Beetle.
The problem I'm having is that when I connect the Leonardo to my iPad, the iPad shows an alert saying that the Leonardo is using too much power.

Tried running the board with an external power source. Then I get a different alert: Device not Supported.

At this point I believe that the problem is not necessarily power, but the fact that the Leonardo is announcing itself to the iPad and the iPad does not like it. In the UNO project, through re-flashing, the board acts only as a HID.
Is there a way to make the Leonardo (or other ATmega 32U4 based board) to not advertise itself on the USB port while allowing the HID functionality to operate?

If indeed the descriptor is the problem then yes you can change it.
In the core file USBCore.h is the line:
#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

Just change the 500 to something smaller (it has to be an even number).
However it may be that the Leonardo isn't programmed to support the Boot Protocol for HID. In which case that would require bigger changes to the USB and HID stacks in the core.

Thanks! To deploy that change into a board, do I need to reprogram the bootlode

No, just reupload your sketch.

So when reduced from 500 to 100, the iPad does not complain about too much power anymore. Also, now it works like a keyboard!  But still will say 'device not supported' alert.

Probably needs a boot protocol compatible device then.

I'm considering just disabling the "Arduino Leonardo" USB device and just keeping the HID. If possible,

Not sure it'd be that easy to disable the CDC/ACM function of the device.

I am trying to get this to work on my iPhone with a adapter that supports both data and power. But the chip don’t even start up

i will stress now that i haven't tested this, and if it doesn't work you may have to reflash the bootloader in order to program the arduino again.
in the arduino install directory we are looking for the following file:
Arduino\hardware\arduino\avr\cores\arduino\main.cpp

at line 40 (i'm using 1.6.9) we have:
#if defined(USBCON)
    USBDevice.attach();
#endif

in theory if you comment this out the serial port may not be ennumerated, however i don't know if the keyboard functions will still work.
if it does work you should wrap it in an if block so that the serial port shows if a certain pin is pulled high/low whatever your preference. this would enable you to program it as normal.

Commenting that line did stop the device from enumerating the Arduino, but the Keyboard does not work anymore. And as you mentioned, the Arduino  needs re-flashing after to come back to life. Thanks!

I have found the solution - your USB > Lightning adapter must has the option for charging.
For example i use Arduino Leonardo connected to IPhone 6 by USB to adapter who has USB nest and charging nest. IPhone shows me info that "This device is not supported.", but all works fine and I can control IPhone by Arduino Leonardo.

@Majenko's solves the power issue. For me the "This device is not supported" is still a problem. That alter interrupts the initial Keyboard-iPad communication.


text:
CRC usage when ack disabled in nRF24L01
In the documentation of the nRF24L01 library I use (library), the CRC state (on/off) and length can be set or get. It seems to be used for auto ack, but when I switch auto ack off, what is the use of CRC? Can I somehow read the CRC value or use it somehow in a useful way?
The reason is, I get sometimes wrong values and would like the CRC for that, but otherwise I need to implement my own CRC byte(s) in the payload.
(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages).

The chip itself deals with CRC calculation and discards any that fail the check, you don't get to see the CRC. You get faulty packets when connection between Arduino and the nRF is finicky or when power to the module isn't the most table, use better wires (definitely not a ribbon cable) and decoupling capacitors. See the datasheet for more details about special cases of using CRC (Enchanced Shockburst and so on).

@Avamandar ... I use an adapter which afaik already contains the capacitors (also there wouldn't be a possibility to add these manual close to VCC/GND anyway). I use 5V (and the adapter converts it into 3.3V).
I would have to check the special cases regarding enhanced shockburst (I don't want to use the ack-mechanism).

You don't have to use auto-ack to keep CRC enabled, if my memory serves me correctly.

@Avamandar True, it seems different options, but since there is no way to use CRC directly, the only possibility it's used internally in the chip. However, I assume it does not start resending by itself in case of an incorrect CRC and I cannot know the CRC value, so a CRC without an ack does not seem very useful.

@Avamandar ... the default way afaik is to use dupont cables, I assume you don't consider those ribbon cables?

Dupont cables should work fine. Resending, auto-ack and CRC are all separate features that work almost individually. The library has functions for changing that too.

I use dupont and seems to work fine so far indeed, I never used flat cable. I guess I need to do some testing to see how much the CRC influences correct transfers.

(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages). - You may have your gain set too high or your modules too close together and the signal is distorting through too much power (saturating the receiver). Your finger is attenuating the signal. Or the other way around and there's not enough signal and your finger is acting as a crude ground plane for the dipole.

@Majenko that might be the case (too close together, like 5-15 cm and MAX PA level). I will try to decrease it.... however, what if I don't know the distance while in use? In a real situation some slaves might be close, others might be further away... I cannot select it per slave device/port.

If they are just slaves to a single master then it's the distance from the slaves to the master that you need to worry about, not the distance between slaves. Anything further than about 1m you don't really need to worry I think. Experiment. See what PA level gives the best results over the distance range you are expecting. Maybe give a "LOW" and "HIGH" power switch on the unit.

@Majenko ... yes that is what I meant (I mean some slaves will be close to the master, some might be close to the master). So I guess it's best to have at least some distance between all slaves to the master ... or maybe in case two are close together, I might go for a wired solution for one of them.


text:
Powering Multiple Servos From One Battery- What is my circuit missing?
I'm working on a robotics project right now and my limited DIYer knowledge of electrical circuits is failing me. I need to power 7 Rage Standard Metal Gear Servos (RGRS104-16-6vm) and 4 RadioShack Micro Servos using a Tenergy 6V 3300mAh NiMH Battery Pack. I've made a diagram of the circuit I'd like to make, but I feel like there's more to this type of circuit than I've planned for. There are only 9 servo connections because two pairs of Rage Servos will be wired together to share the same battery and signal connection. I'm also open to using a different battery if that's what it takes to make the robot run smoothly (It has to use a rechargeable battery though; It's meant to be portable.) Also, the Arduino has it's own battery, so no worries there.
Would you please point out what I need to add to my circuit to make sure it works properly?
Thanks in advance!

More Info:
Rage Standard Metal Gear Servo RGRS104-16-6vm
Dimensions: 40.8 × 20.1 × 38 mm
Weight: 56 g
Operating Speed: 0.18sec/60degree (4.8V), 0.16sec/60degree (6V)
Stall Torque: 9kg.cm/125.2oz.in(4.8V), 10.2kg.cm/141.9oz.in(6V)
Operating Voltage: 4.8V~6V
Control System: Analog
Direction: CCW
Operating Angle: 180degree
Required Pulse: 500us-2500us
Bearing Type: 2BB
Gear Type: Metal
Motor Type: Carbon
Connector Wire Length: 30 cm.
RadioShack Micro Servo
Voltage: 4.8~6.0V
Torque: 1.5kg/cm at 4.8V; 1.8kg/cm at 6.0V
Speed: 0.12/60ТА at 4.8V; 0.10/60ТА at 6.0V
Size: 23x11.5x24mm
Weight: 8.6 g
Use Angle: <=160ТА
Tenergy 6V 3300mAh NiMH Battery Pack
Chemistry: Ni-MH
Cell Size: Sub-C
Nominal Voltage (V): 6
Capacity (mAh): 3300
Max Continuous Discharge Current: 6A
Battery Charging Current:
Standard: 1A
Weight: 10oz.
Dimensions: 112 x 46 x 23mm (LxWxT)
Connector: Hitech
Link to Diagram: https://i.stack.imgur.com/L4GtP.jpg

Servo's can draw spike currents, so you theoretically need a big capacitor to be able to supply such power needs. It may also help to use a battery type that has a higher maximal discharge current (but I believe internal resistance of a battery may rise over time).

Also, paint is a nice program to draw, but for drawing circuit boards you should try Fritzing, cadsoft eagle or something like easyeda. Fritzing has a board view that resembles your drawing, but with pre-made components.

I'm voting to close this question as off-topic because it is entirely about RC servos and not at all in any way about Arduino.  Try an RC hobby site for the best advice, in particular, in figuring out if your pack is four or five cell, and in the case of the latter if it is or is not appropriate to use directly.

One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?
If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)
Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV

the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. - Actually that's not true (and it took me by surprise too when I found out): The Arduino uses timer interrupts not PWM in the servo library. It's set to drive 12 servos per timer, and the '328P has 1 timer allocated to it, so can directly drive 12 servos on any pins of your choice no problem.

No, the Arduino is powered by a separate battery.


text:
Changing parameters of pulseIn() to sense different materials
I have a ultrasonic sensor and in order to get the distance I use the pulseIn() function included in the arduino library, and then change it to distance. As the ultrasounds does not work equally in different materials as i have seen in Performance comparison of Infrared and Ultrasonic sensors for
obstacles of different materials in vehicle/ robot navigation
applications. My question is if there is a way of changing the pulseIn() to have different materials, function:
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    // convert the timeout from microseconds to a number of times through
    // the initial loop; it takes approximately 16 clock cycles per iteration
    unsigned long maxloops = microsecondsToClockCycles(timeout)/16;

    unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops);

    // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out
    if (width)
        return clockCyclesToMicroseconds(width * 16 + 16);
    else
        return 0;
}

or the countPulseASM, which I translate from the asembled code, which can have some errors) as:
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
{
        if (--maxloops == 0)
        {
           return 0;
        }
}

// wait for the pulse to start
 while ((*port & bit) != stateMask)
{
    if (--maxloops == 0)
    {
       return 0;
    }
}

// wait for the pulse to stop
 while ((*port & bit) == stateMask)
 {
    if (++width == maxloops)
    {
        return 0;
    }
 }
return width;

Another way of doing that is having a correction factor while changing the time into the distance, but for that I shold have the differences of all the materials.

pulseIn just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.
Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.
That is down to your sketch to do that calculation using the time provided by pulseIn and your own adjustment values.


text:
AtTiny85 and MMA8452Q accelerometer cannot connect using i2c
I am trying to connect the MMA8452Q with AtTiny85 using the TinyWireM library.
I made the proper hardware setup with  pull-ups on  SCL and SDA pins - tested it on Arduino
Uno and it works, however when i connect the Tiny I cannot even get the handshake.
The following code produces output 13 instead of 42 (0x2A)
HARDWARE SETUP
MMA8452 Breakout ------------AtTiny85
3.3V -------voltage regulator------ 5V
SDA -----------^^(330)^^----------- PB0 (on attiny programmer marked as 5)
SCL -----------^^(330)^^----------- PB3 (on attiny programmer marked as 2)
GND --------------------------------- GND
(I also tried different pins with no luck)
CODE
//---bluetooth console communication stuff---//
#include <SoftwareSerial.h>
#define rxPin 1 //not important - needed for initialization
#define txPin A2
SoftwareSerial blueTooth(rxPin, txPin);
//      ---     //

#include "TinyWireM.h" // Used for I2C

// The SparkFun breakout board defaults to 1, set to 0 if SA0 jumper on the bottom of the board is set
#define MMA8452_ADDRESS 0x1D  // 0x1D if SA0 is high, 0x1C if low

#define WHO_AM_I   0x0D

void setup() {

  blueTooth.begin(9600);
  delay(1000);
  TinyWireM.begin(); //Join the bus as a master
  delay(1000);
 }

void loop() {
   byte c =0;
   c = readRegister(WHO_AM_I);
   blueTooth.println(c);
   delay(1000);
  }

 // Read a single byte from addressToRead and return it as a byte
byte readRegister(byte addressToRead) {
  TinyWireM.beginTransmission(MMA8452_ADDRESS);
  TinyWireM.send(addressToRead);
  TinyWireM.endTransmission(); //endTransmission but keep the connection active

  TinyWireM.requestFrom(MMA8452_ADDRESS, 1); //Ask for 1 byte, once done, bus is released by default

  while(!TinyWireM.available()) ; //Wait for the data to come back
  return TinyWireM.receive(); //Return this one byte
}

Would anyone know how to get it right?

I2C pullup resistors are 4.7 kohm to Vcc (at 5V). SCL is PB2 (chip pin 7) and SDA is PB0 (chip pin 5).

changed the resistors. still getting the same output

On an ATtiny85 pin 5 (PB0) is SDA and pin 7 (PB2) is SCL for the I2C interface.  You're using the wrong pin for SCL.
Additionally, your pull-up resistors are too strong.  Somewhere between 4.7K Ohm and 10K Ohm are recommended for pull-up's on the SDA and SCL lines.

using the TinyWireM library.

Make sure the i2c actually works. Arduino libraries are generally of poor quality and just because someone wrote it doesn't mean it actually works. Get a logic analyzer or scope on the bus and see what's going on.
Once you can confirm that, get a datasheet for the 8452 and see how it works and code to it.

i tried doing  what you suggested and also tried pluging i2c  attiny as slave to uno as master. did not work either.
Generally what i get on oscillator is some mess different than what i get when plugging uno.  On uno i get nice square waves on clock and digital signals on sda. i ran some tests and used the pb0 and pb2 and pb3 pins on attiny for serial communication so the pins work (i guess?). Could it still be the chip problem? It seems that  many folks succeed with using TinyWireM as i2c library... i dont know where to go from here

i scanned for i2c devices and it detects an i2c device at each address it scans... so weird


text:
Unreliable serial communication from Arduino Mega
I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:
bool foo(int A, int B)
//...
//Const global int to byte 1&2
//Math on int A and int B to make bytes 3-8
//...
  unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
  while(rep)
  {
    for (int i=0; i< 8; i++)
    {
      Serial2.write(cmd[i]);   // Send C string
    }
    if(Serial2.available())
    {
      //device echoed == command recieved
      rep=false;
    }
  }

The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.

I still need an RS485 module

In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

Looping the Serial2.write()

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

I'm Not supporting a tri-state the transmit buffer

I was rereading the device's manual and found this line:

The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?

Additional things of note:

I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?
I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:
digitalWrite(DE_PIN, HIGH);
Serial2.write(cmd, 8);
Serial2.flush();
digitalWrite(DE_PIN, LOW);

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.
Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a maximum length for any buffers you have.

I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:
while(rep)
{
  for (int i=0; i< 8; i++)
  {
    Serial2.write(cmd[i]);   // Send C string
  }
  if(Serial2.available())
  {
    //device echoed == command recieved
    rep=false;
  }
}

is completely wrong. You are sending a command and then immediately looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.
Instead it should be:

Send the command.
Look for some response data
If some data has arrived then add it to the response buffer
If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".

Ok, I'll add the module back in. If they're electrically incompatible, any idea why it works sometimes? Is this the CS equlivlant to a stopped clock being right twice per day?

@ATE-ENGE Pretty much ;) Without the module you're connecting a differential pair to a single-ended TX / RX pair. The module is needed to convert single ended into differential and back again.


text:
Arduino port relocation (PORTD to PORTB)
So I'm trying to connect the chip with an 8-bit data bus. All works good, but...
Arduino Uno uses D0 and D1 for serial TX/RX (USB connection with PC). When I try to open a serial connection (on serial.begin stage) ports D0 and D1 blocks and the chip stops working. This is a problem.
I think I should relocate pins D0 and D1 to another port. But the chip uses 8 pins (8bit chip). So I need to relocate the first pin (D0) and the second pin (D1) to port b. Maybe I can use B4 and B3?
But I don't know how to use PORTD[PD2, PD3, PD4, PD5, PD6, PD7] and PORTB[PB4, PB3] in one time like:
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
portX = data;

My code:
#include <avr/io.h>     // For I/O and other AVR registers
#include <util/delay.h> // For timing

/* Pinmap (Arduino UNO compatible) */
#define YM_IC (5) // PC5 (= pin A5 for Arduino UNO)
#define YM_CS (4) // PC4 (= pin A4 for Arduino UNO)
#define YM_WR (3) // PC3 (= pin A3 for Arduino UNO)
#define YM_RD (2) // PC2 (= pin A2 for Arduino UNO)
#define YM_A0 (1) // PC1 (= pin A1 for Arduino UNO)
#define YM_A1 (0) // PC0 (= pin A0 for Arduino UNO)
#define YM_CTRL_DDR DDRC
#define YM_CTRL_PORT PORTC
#define YM_DATA_DDR DDRD

#define YD0 (0)(= pin D0 for Arduino UNO)
#define YD1 (1)(= pin D1 for Arduino UNO)
#define YD2 (2)(= pin D2 for Arduino UNO)
#define YD3 (3)(= pin D3 for Arduino UNO)
#define YD4 (4)(= pin D4 for Arduino UNO)
#define YD5 (5)(= pin D5 for Arduino UNO)
#define YD6 (6)(= pin D6 for Arduino UNO)
#define YD7 (7)(= pin D7 for Arduino UNO)

#define YM_DATA_PORT PORTD // Whole PORT D for data bus (= pins D0 to D7 for Arduino UNO)
#define YM_MCLOCK (1) // PB1 = OC1A (= pin D9 for Arduino UNO)
#define YM_MCLOCK_DDR DDRB

extern uint8_t chflash[6];
uint8_t dacflash;
#define NOTEONFLASH 4
#define VGMWAIT 15

static void write_ym(uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_CS); // CS LOW
  YM_DATA_PORT = data;
  _delay_us(1);
  YM_CTRL_PORT &= ~_BV(YM_WR); // Write data
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_WR);
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_CS); // CS HIGH
}

/**
 * Write data into a specific register of the YM2612
 *
 * @author Furrtek
 * @param reg Destination register address
 * @param data Data to write
 */
static void setreg(uint8_t reg, uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_A0); // A0 low (select register)
  write_ym(reg);
  YM_CTRL_PORT |= _BV(YM_A0);  // A0 high (write register)
  write_ym(data);
}

void call() {
  setreg(0x28, 0xF0); // Key on
  _delay_ms(1000);
  setreg(0x28, 0x00); // Key off
}

uint8_t getfilebyte() {
  return Serial.read();
}

int main() {
  init();

  //Serial.begin(9600);
  /* Pins setup */
  YM_CTRL_DDR |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD) | _BV(YM_A0) | _BV(YM_A1);
  YM_DATA_DDR |= _BV(YD0) | _BV(YD1) | _BV(YD2) | _BV(YD3) | _BV(YD4) | _BV(YD5) | _BV(YD6) | _BV(YD7);
  YM_MCLOCK_DDR |= _BV(YM_MCLOCK);
  YM_CTRL_PORT |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD); /* IC, CS, WR and RD HIGH by default */
  YM_CTRL_PORT &= ~(_BV(YM_A0) | _BV(YM_A1)); /* A0 and A1 LOW by default */

  /* F_CPU / 2 clock generation */
  TCCR1A = _BV(COM1A0);            /* Toggle OCA1 on compare match */
  TCCR1B = _BV(WGM12) | _BV(CS10); /* CTC mode with prescaler /1 */
  TCCR1C = 0;                      /* Flag reset */
  TCNT1 = 0;                       /* Counter reset */
  OCR1A = 0;                       /* Divide base clock by two */

  /* Reset YM2612 */
  YM_CTRL_PORT &= ~_BV(YM_IC);
  _delay_ms(10);
  YM_CTRL_PORT |= _BV(YM_IC);
  _delay_ms(10);

  /* YM2612 Test code */
  setreg(0x22, 0x00); // LFO off
  setreg(0x27, 0x00); // Note off (channel 0)
  setreg(0x28, 0x01); // Note off (channel 1)
  setreg(0x28, 0x02); // Note off (channel 2)
  setreg(0x28, 0x04); // Note off (channel 3)
  setreg(0x28, 0x05); // Note off (channel 4)
  setreg(0x28, 0x06); // Note off (channel 5)
  setreg(0x2B, 0x00); // DAC off
  setreg(0x30, 0x71); //
  setreg(0x34, 0x0D); //
  setreg(0x38, 0x33); //
  setreg(0x3C, 0x01); // DT1/MUL
  setreg(0x40, 0x23); //
  setreg(0x44, 0x2D); //
  setreg(0x48, 0x26); //
  setreg(0x4C, 0x00); // Total level
  setreg(0x50, 0x5F); //
  setreg(0x54, 0x99); //
  setreg(0x58, 0x5F); //
  setreg(0x5C, 0x94); // RS/AR
  setreg(0x60, 0x05); //
  setreg(0x64, 0x05); //
  setreg(0x68, 0x05); //
  setreg(0x6C, 0x07); // AM/D1R
  setreg(0x70, 0x02); //
  setreg(0x74, 0x02); //
  setreg(0x78, 0x02); //
  setreg(0x7C, 0x02); // D2R
  setreg(0x80, 0x11); //
  setreg(0x84, 0x11); //
  setreg(0x88, 0x11); //
  setreg(0x8C, 0xA6); // D1L/RR
  setreg(0x90, 0x00); //
  setreg(0x94, 0x00); //
  setreg(0x98, 0x00); //
  setreg(0x9C, 0x00); // Proprietary
  setreg(0xB0, 0x32); // Feedback/algorithm
  setreg(0xB4, 0xC0); // Both speakers on
  setreg(0x28, 0x00); // Key off
  setreg(0xA4, 0x22); //
  setreg(0xA0, 0x69); // Set frequency

  call();

  while(1000) {
    if (Serial.available() > 0) {
      _delay_ms(1000);
      call();
      _delay_ms(1000);
      char var = getfilebyte();
      Serial.print("Yeah: ");
      Serial.println(var);
    } else {
      Serial.print("Nooo: ");
      Serial.println(Serial.available());
      call();
    }
  }
  while(1);
}

Consider a Leonardo type (ATmega32u4) board which does not rely on the hardware UART pins for host communication, or consider a different platform entirely.

You cannot set pin states in multiple ports simultaneously, if that's what you're asking.
At the instruction set level, setting pin states is a single that writes to an 8-bit register which corresponds to the 8 pins in a port. There is no way to write to two different registers in the same instruction, so if you need all eight bits to change exactly at the same time you're out of luck. However, if you can tolerate a little bit of time between 6 bits in one port changing state and 2 bits in another port changing state, then you can simply write a wrapper function.
PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
void set_ym_ctrl_port(uint8_t data) {
    PORTD &= ~(0x3f<<2);
    PORTB &= ~(0x3<<3);
    PORTD |= (data & (0x3f<<2));
    PORTB |= (data & 0x3)<<3;
}

Or something like that. If you need even less delay and you think you can do better than the compiler, inline assembly can be helpful.
As an aside, syntax like
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];

is not valid for a number of reasons.

Thanks a lot! Maybe i can test my luck in fast serial.begin and .end.

@ThaneKrios no, that simply will not work.  You either use the hardware UART pins as a hardware UART or you don't - you have no practical hope of coordinating changing their role on the chip side with changing the electrical connection to the pins, without horribly breaking things.

Adding to what @uint128_t said, if you really need to change the state of many pins at the same time, you can add some external latched shift registers as a SIPO (serial-in/parallel-out) interface towards the outer world.
The price you pay is that you have to load the entire register with the data you want to send before you can update the output pin states. This requires a clock cycle for each loaded bit (here I'm speaking of the clock of the external register, not Arduino's) and thus may add too much latency in your system, depending on what you are trying to do.
The 74HC595 is a classic (8-bit shift register with output latches), and can be cascaded to obtain a register of the desired width.
Here is an excerpt from the datasheet of TI's 74HC595 (yellow emphasis mine):

It's also sold in 16-pin DIP package, very convenient for breadboarding, in case you need it (common need for people that play with Arduinos).
The internal logic diagram is the following (from the same datasheet):

It is so common in the Arduino world that there are also open libraries do drive it, for example this. But even without pre-written libraries, it is not difficult to drive it from an Arduino, if you have a little experience in digital logic and can understand the timing requirements stated in its datasheet (the table in section 7.6 is fairly easy to understand, once you know what setup and hold times are).

This is intended as a complement to uint128_t's answer. I would like to
point out that the code in that answer changes the outputs in four
steps:

set to LOW the pins of PORTD that need to be LOW
set to LOW the pins of PORTB that need to be LOW
set to HIGH the pins of PORTD that need to be HIGH
set to HIGH the pins of PORTB that need to be HIGH

I compiled it on my system (with gcc 5.4.0): the generated assembly
shows that the whole process takes 18 CPU cycles. I.e. during
1.125 µs the outputs can be in an inconsistent state.
I then tried this alternative version:
void set_ym_ctrl_port(uint8_t data) {
    uint8_t new_portd = PORTD & ~(0x3f<<2) | (data & (0x3f<<2)),
            new_portb = PORTB & ~(0x03<<3) | (data & 0x03)<<3;
    cli();
    PORTD = new_portd;
    PORTB = new_portb;
    sei();
}

This changes the outputs on two steps:

update PORTD
update PORTB

The generated assembly showed that the updates are only one CPU cycle
apart. I.e. the outputs are inconsistent during only 62.5 ns.
Your mileage may vary. In case of doubt check the generated assembly.


text:
Arduino motor and motor driver
I have a little problem. I have a motor driver (L298N). When I engage in electricity, my 2 motors start and after 5 second stop. Then they stop for about 2 seconds, and then start and in a moment (0.5 second) turn off. This make still around (go about 0.5 s, stop for 2 seconds...). And my motor driver is very hot after 1 minute.
Is it possible that it is because of weak voltage? (The motor driver is for 6-35 V, and I have a 6 V battery).

L298n:
enter image description here
There is my code on Arduino:
const int motorPin1  = 9;
const int motorPin2  = 10;
const int motorPin3  = 6;
const int motorPin4  = 5;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void loop() {
  forw(3000);
  back(3000);
}

int fast = 255;

void forw(int timer) {
  analogWrite(motorPin1, 0);
  analogWrite(motorPin2, fast);
  analogWrite(motorPin3, 0);
  analogWrite(motorPin4, fast);
  delay(timer);
}

void back(int timer) {
  analogWrite(motorPin1, fast);
  analogWrite(motorPin2, 0);
  analogWrite(motorPin3, fast);
  analogWrite(motorPin4, 0);
  delay(timer);
}

Could you please recheck the wiring, the driver getting hot may be due to incorrect wiring or heavy load usually. the code seems correct as far as I know. if you suspect low voltage go for a 9v battery and check the delay issue.

Show how you have things wired.  The 2 seconds off sounds like the board is resetting and you're waiting through the bootloader.

Also what is the current draw of the motors?  Do you have a part number or datasheet?  The driver getting hot suggests that you're running too much current through it.  These little drivers cannot route much current.

I add 9V battery and it go good, but after first back() function stop, and after 2 second back() again, but slowly. There is scheme: link

And there is chassis: link

Please do not vandalize your post. Contributions to Stack Exchanges are subject to the SE Terms Of Service. This includes "You agree that all Subscriber Content that You contribute to the Network is perpetually and irrevocably licensed to Stack Exchange under the Creative Commons Attribution Share Alike license.". Since people have taken the trouble to answer your question, deleting or vandalizing the question is impolite.

I ran the code on my arduino(kinda old), when I checked with my multimeter I noticed that the 5th PWM pin didnt osciallate every 3 seconds, could you please try the below code where I changed the 5th pin to 3rd PWM pin, also please change the connections on the l298 board.
const int motorPin1  = 9;
const int motorPin2  = 10;
const int motorPin3  = 6;
const int motorPin4  = 3;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void loop() {
  forw(3000);
  back(3000);
}

int fast = 255;

void forw(int timer) {
  analogWrite(motorPin1, 0);
  analogWrite(motorPin2, fast);
  analogWrite(motorPin3, 0);
  analogWrite(motorPin4, fast);
  delay(timer);
}

void back(int timer) {
  analogWrite(motorPin1, fast);
  analogWrite(motorPin2, 0);
  analogWrite(motorPin3, fast);
  analogWrite(motorPin4, 0);
  delay(timer);
}

The L298 is a very old, obsolete design based on bipolar transistors, which means it has a lot of internal losses.
The energy consumed in those losses shows up as heat.
It also has some degree of overload or overtemperature protection, so what you are observing is an automatic shutdown.  Or perhaps, your motor is causing the battery voltage to sag and resetting your Arduino at which point the sketch resumes after a bootloader delay.  6v is really too low an input voltage to the Arduino's regulator, but too high for direct input without the regulator.
You need to make sure that the current draw of your motors is reasonable, and you likely want to replace the terrible L298 with a more modern, low less FET driver.  You will need to select one rated for the actual current draw of your motor: you should consider not only free rotation of the motor, but the increased current draw if it is mechanically stalled.


text:
Using ESP8266 Adapter with Temperature/Humidity Sensor
Good Day. I am currently following a project where I can send data to my firebase database using an ESP8266-ESP01 wifi module and DHT11 temp/hum sensor.
I am using this adapter to enter the boot mode already with a program. Everything seems fine.

When I need to upload a program I am just tweaking the adapter using jumper cables to put the GPIO0 to GND and It works fine. My problem now is I have to use the DHT11 Sensor which is supposed to be connected to GPIO2. I tried to go to bootmode so  I connected DHT11(data) directly to the ESP8266(GPIO2) leaving the slot in the adapter empty in which I cant enter the boot mode for some reason.
But when I plug ESP8266(GPIO2) to the adapter slot, I can enter bootmode. Currently confused on how to tweak the adapter to be able to use the GPI02 to the DHT11. Any tips would really help. thanks!

Possible duplicate of NodeMCU does not boot up when GPIO pin is high

it's a little vauge how you're wiring it up, but does it boot with the DHT outside of the adapter?

Please provide information how you're wiring up the DHT to the ESP. Reviewers please hold a bit with the duplicate votes, the question just needs clarification at the moment.

@Avamander The question clearly states he's using GPIO2. GPIO2 is one of the "special boot mode" GPIOs as detailed in the duplicate question. What further clarification can you want?

DHT has four (three different) pins, is he powering it correctly? And would a DHT really pull GPIO2 low for the ESP to not boot properly?

@Avamander: you mean LOW right? regardless, since the data pin uses a PULLUP, i don't see how a DHT11 would prevent normal booting as described, if it's wired correctly.

@dandavis Yes. Fixed.

Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.
For those who would like to use this specific adapter with DHT11 attached in boot mode.
-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.
-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.
Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.

Accept your own response to close your question.


text:
Arduino library not working, can't find header
I have fair experience with C/C++ so I decided to have a go at writing my first simple Arduino library. I wrote the code which seems to be fine to me except that it keeps complaining about the header file not found during compilation:
/home/me/sketchbook/libraries/SegDisplay/SegDisplay.cpp:1:24: fatal error: SegDispaly.h: No such file or directory
 #include "SegDispaly.h"
                        ^
compilation terminated.

I have the library located in my sketch folder under the name "SegDisplay":
/home/me/sketchbook/libraries/
└── SegDisplay
    ├── examples
    ├── keywords.txt
    ├── README.md
    ├── SegDisplay.cpp
    └── SegDisplay.h

and here's the code:
SegDisplay.h:
#ifndef _SEVEN_SEG_H_
#define _SEVEN_SEG_H_

#include <math.h>

#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class SegDisplay
{
public:
    SegDisplay (int clockPin, int latchPin, int dataPin, int digitPins[4]);
    void display (double value);

private:
    const int digitPins[4];
    const int clockPin;
    const int latchPin;
    const int dataPin;
    const byte digit[10] = //seven segment digits in bits
    {
        B00111111, //0
        B00000110, //1
        B01011011, //2
        B01001111, //3
        B01100110, //4
        B01101101, //5
        B01111101, //6
        B00000111, //7
        B01111111, //8
        B01101111  //9
    };
    int digitBuffer[4];

    void setRegisterData (byte data);
    void clearRegister();
    void clearDisplay();
    void updateDisplay();
};

#endif

SegDisplay.cpp:
#include "SegDispaly.h"

SegDisplay::SegDisplay (int a, int b, int c, int d[4]):
    clockPin (a), latchPin (b), dataPin (c), digitPins (d), digitBuffer ({0})
{
    for (int i = 0; i < 4; i++)
    {
        pinMode (digitPins[i], OUTPUT);
        digitalWrite (digitPins[i], HIGH);
    }
    pinMode (latchPin, OUTPUT);
    pinMode (clockPin, OUTPUT);
    pinMode (dataPin, OUTPUT);
}

void SegDispaly::setRegisterData (byte data)
{
    digitalWrite (latchPin, LOW);
    shiftOut (dataPin, clockPin, MSBFIRST, data);
    digitalWrite (latchPin, HIGH);
}

void SegDispaly::clearRegister()
{
    setRegisterData (B00000000);
}

void SegDispaly::clearDisplay()
{
    // deactivate transistors
    for (int n = 0; n < 4; n++) digitalWrite (digitPins[n], HIGH);
}

//writes the temperature on display
void SegDispaly::updateDisplay()
{
    byte outByte;
    // dispaly digits
    for (int i = 0; i < 4; i++)
    {
        clearDisplay();
        clearRegister();

        // enable nth cell cathode (transistor)
        digitalWrite (digitPins[i], LOW);

        // output nth digit on display
        if (i == 1)
        {
            //print the decimal point on the 2nd digit
            outByte = digit[digitBuffer[i]] | B10000000;
        }
        else outByte = digit[digitBuffer[i]];
        setRegisterData (outByte);

        //delayMicroseconds (500);
        delay (5);

        //Serial.print (outByte, BIN);
        //if (i == 3)
        //{
        //  Serial.println (".");
        //}
        //else Serial.print (", ");
    }
}

void SegDispaly::display (double value)
{
    int n = int (value * 100);
    digitBuffer[0] = n / 1000;
    digitBuffer[1] = (n % 1000) / 100;
    digitBuffer[2] = (n % 100) / 10;
    digitBuffer[3] = (n % 100) % 10;
    updateDisplay();
}

My target AVR is Arduino Uno R3, the code used to work fine in a sketch before I decided to create a library out of it. Any help would be greatly appreciated. thanks in advance.

You spelled the header filename wrong:
#include "SegDispaly.h"

should be:
#include "SegDisplay.h"

You have also made the same mistake in the class name multiple places in SegDisplay.cpp.

you know I checked the spelling of SegDisplay several times and couldn't spot it for some reason, I must be going blind. Thanks


text:
How do I use an image sensor with an arduino uno?
I have recently taken apart an old digital camera for its parts and I have found an image sensor inside it.
For those of you who don't know, an image sensor measures light; the shutter opens, light hits the sensor and the sensor converts this light into data to be stored as an image.
My question is how can I implement it into a project? What equipment do I need? It has a tape wire so I'm not really sure how I can use it. I have attached a photo of it also. Thanks!!

You need to find markings on it and figure out what the component actually is.  Then you can maybe find a datasheet for it that explains how it works and commmnicates.  Once you know that you can decide if that's something you can do with an Arduino.  Be prepared to learn that Arduino might not be big enough or fast enough to do anything with that particular sensor.

ARM based Arduinos probably are fast enough.

how can I implement it into a project?

Find its datasheet, understand how it works and code to it.
Just as what you would with any other devices. The challenge here is that you will be hard pressed to find any info about those kind of devices.


text:
Trying to flash ATTiny85 bootloader using FT232R in the Arduino IDE
I have a FT232R that I want to use to flash my ATTiny85 bootloader in the Arduino IDE, can someone help me out on this? I don't want to get a AVR programmer.

This is certainly possible but it's very inconvenient and not commonly done. It's much better to buy a cheap 6 pin USBasp clone off eBay or use another Arduino board as an "Arduino as ISP" programmer. It's possible because the FT232 has a bit bang mode but it's very slow. You can find instructions here: https://learn.adafruit.com/ftdi-friend/programming-the-arduino-bootloader, you just need to adapt the instructions to the ATtiny85 (SPI connections and board selection). I've never done this so I'm not going to write an answer but if you are successful please answer your own question.

It's also not very common to use a bootloader on the ATtiny85 due to the limited flash memory. Usually you will upload sketches to the ATtiny85 using an ISP programmer. For that usage the FT232 is even more inconvenient because it's so slow and you will typically upload more often than you would burn a bootloader.

A bootloader is a program that gets loaded into the bare microcontroller to handle a number of low level tasks. One of those tasks is the ability to load a program over UART (serial).
As such, the bootloader can be loaded into the microcontroller using a AVR programmer. Once this has occurred, you can then easily load in programs with the FT232R.
It is possible to use the bitbang mode on the FT232R to load the bootloader into an Arduino board, hence replacing the AVR programmer. So, it can work but it isn't easy.
As suggested by per1234, there is some instructions on how to do this to an Arduino Diecimila on the Adafruit website: Programming the Arduino Bootloader
In general the full page has a lot of useful information: Full page

Sorry for a late reply!, but can't you run the FT232R in bitbang mode?

@sa_leinad ... "I am sorry to say that what you are trying won't work." ... no, you can bitbang the FTDI and mimic an ISP programmer that way.

@yeti & Pepperrika, You are both correct. However this requires a certain level of expertise. Beginners especially won't be able to do this. However, if a beginner had a ISP then a beginner could easily program the bootloader into the ATTiny85 using the Arduino IDE.

So you agree that "... that ... won't work." is a false statement. And we all had missing expertise on nearly all topics somewhen in the past.
Well... wiring up a FTDI module probably is not more difficult than wiring up an ISP... and avrdude supports them, so it will not be rocket science.
I agree that having an ISP is the easiest way to go but @Pepperrika asked about it being doable with a FTDI and to this the answer only can be: YES!

@yeti, why don't you post your own answer if you have such a problem with mine. I've edited my answer - upvote it if you think it is now worthy.