text:
Arduino Pro Mini doesn't automatically reset
I have an issue with my Arduino pro mini.
Yesterday, I uploaded a sketch a few times on the pro mini, with an FTDI adapter, and everything worked fine. Today I'm trying to re-upload a sketch, but now, for some obscure reasons, my Arduino pro mini doesn't want to reset itself. I need to manually reset it. Since it is embedded in s case, I can't do that if I want to upload a sketch.
EDIT: I managed to make some tests, and it would seem that the DTR pin on the mini doesn't work anymore. When I short the DTR PIN to GND, the mini doesn't reset itself. I believe that could be a reason. But why? And how? It was working a day ago.
I soldered the FTDI like that, and it didn't work several times.
(At the moment I left it unsoldered because I don't want to solder it yet):

Can anyone complete my intuition?
Thanks in advance.

Did you solder it? Or did you use a "female" connector soldered? Please [edit] your question and add this information, optimally with an actual picture of your assembly.

I edited the question, the connection is soldered, but it doesn't work

You have nothing else connected to the board besides the FTDI adapter? You have selected the "Arduino Pro or Pro Mini" from the standard AVR based Arduino support and not something else (e.g. minicore)?

No, I have only my FTDI, and I selected "Arduino Pro or Pro Mini" from the standard AVR based Arduino.

"When I short the DTR PIN to GND, the mini doesn't reset itself" if you are doing that with the FTDI adapter still soldered you are either trying doing what the FTDI adapter is already doing (which is of no use) or you are trying to short out DTR by connecting it to ground while FTDI is trying to drive it high (not really a good idea either).

Well it is of use, to determine if the FTDI or the mini is the problem. I'm not sure if the FTDI isn't sending the signlal, or if the signal isn't reaching the internal Atmega328. And what do you mean by "connecting it to ground while FTDI is trying to drive it high". To reset the arduino, the DTR pin must go low (to GND) ? Or did I badly understood this thread ? : Mini reset issue

I'm not sure how to go about this without it turning into a lengthy discussion. At any given moment FTDI chip is internally connecting DTR to either 5V (in your case) or GND. What happens if you jumper DTR to the same thing the FTDI chip is connecting it to? Nothing. It was already connected.  What happens if you connect it to the opposite thing? A large amount of current flows as you attempt to connect 5V and GND to each other through the FTDI's DTR pin. If you did this previously it's not unlikely that this is why your auto-reset no longer works. It is not diagnostically useful.

Well the FTDI chip is supposed to be connected to the DTR pin, but I need to make sure it still does (it's a cheap FTDI board btw). If that's wrong do you have any idea of how I could diagnose my board ? Or even solve the problem maybe ? And no I tried to GND it that after the auto reset wasn't working anymore, it's not the problem

Let us continue this discussion in chat.

Given your last message in the chat it sounds like this will not be clarified and resolved. If that's the case you should probably delete the question so it is not floating around in the system forever like that.

Is this is an actual photo of your FTDI and mini? I can't tell whether the FTDI pins are soldered to the mini. If not, I would guess that the problem is an unreliable electrical connection at one of the pins, and look there for the problem.
If it helps, this is what I use for my embedded devices. The FTDI is in the USB-A connector. The embedded end is just a female connector that pushes onto the 6 pins on the board. This cable supplies +5v; there are also ones that supply 3.3v.

Thanks for your answer, the connection is soldered.

In that case, I'd check the resistance of the solder joints including trying to wiggle them; then trying to narrow it down by swapping FTDI boards if you have another; and likewise, swapping the mini board.

Thanks for your answer, the connection is soldered. I don't think it's a connection problem, I verified the soldered connection, tried to bend them, there's nothing to do.
Thanks for you picture, it seems I have the same connections. Really don't know where to look ...

The reset pulse issued by the USB-Serial adapter via the DTR line may be of low amplitude (3.3V). This is occasionally too low for the Pro Mini reset function.  Sometimes, it helps to solder a 47k resistor across the reset button contacts, lowering the initial DC level of the reset input. This applies to 5V/16MHz and 3.3V/8MHz versions of the Pro Mini.


text:
How to know positive and negative in breadboard
I have this breadboard, and there is no indication on it about what is positive/negative on it.

In comparison, this other breadboard (pic from the internet) DOES have indications:

Can anyone give me a hint ?

Hint: there is no negative or positive.

@gre_gor like this https://www.pjrc.com/store/breadboard.jpg I want to wire two pins to ground on breadboard

@Williams You could do that as usually as you would with a printed or marked board.

It doesn't matter. You could label them yourself with a red and blue permanent marker.

Also from my experience, your breadboard has side rails wider apart than the other breadboard and a power supply intended for a breadboard won't fit.

Here;s the rub:  Don't forget what you have chosen.  Wiring power backwards is hard on some components.  I make a point of always using the same color of wires for power to everything, and as long as the same colors are on the same rails I don't need to look at breadboard markings.  Have fun!

btw, I have used those power supplies for breadboards.  Be wary.  Their QC is not good.  I don't use them any more.

You decide which rails are positive and which are negative when you connect them to the + an - from your power supply or battery.
A breadboard isn't polarised per se. It's just a bunch of cross-connections inside a perforated plastic case. No active or passive components inside.
Some manufacturers may choose to paint indications regarding where to connect the positive and negative rails, but those are just a guideline. Ultimately it's your choice, you're free to connect + and - wherever you want in the breadboard rails.

so If I wire GND of battery to first row, do I need to plug other wires which need to be GND besides to that wire in a same row ?

Yes indeed. Moreover, if you find it convenient to use a row in the opposite side of the breadboard as GND too, just connect it via wire to the first GND row and boom, you've got another GND row. As simple and easy as that.

As gre_gor said. A simple breadboard contains of rows and columns of connections but sometimes for convenience manufacturer marks or prints Positive and Negative symbol along the row as they are usually used to power a circuit

Connections in the two strips along the edge running top to bottom in your image are connected (in the way you have the image placed) top to bottom.  So, all pins are connected to each other in each of those rows.  Within the inner secions, the connections are (in your image) across from one side to the other.
You decide how you want the power supply cable to be connected to your breadboard,  just becasue there's no indicators means that they simply haven't drawn any coloured lines on the breadboard.  You can draw red and black lines on however you wish.

source: Stack Exchange

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

authors: Алик Третьяков

sort: votes


text:
If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)
I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

it's not a 5v pin, it's simply just to the V+ of the usb. if you send 6v  over the usb, the pin will also have 6v.

I guess what I need to ask is what is the Forward Voltage of the Arduino without any extra pins connected to any other components?

parallel loads all get the same voltage. using a ballpark of 40ma for the uno's consumption, @5v that's 125 ohms. if you want other loads to share in series with the uno, then calc the "forward" as a voltage divider with rLoad, 5v and 125Ω as inputs

Forgive my noobiness, but is it possible to drive a 12v linear actuator AND the arduino using the same power supply?

Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is where do those 5V come from. Basically, from 2 possible sources:

USB. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.
Barrel connector (wall adapter). It accepts 7-12V and brings it down to 5V using a linear regulator whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, preference is given to the wall adapter. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.
This is done not only for convenience purposes (so you have more current available), but also for protection. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.
I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.

You might be mixing up voltage and ampereage. The Arduino takes in from 5volts up to 12, and uses a regulator to bring higher voltages down to 5V. Milliamps (mA) is the measure of what is drawn per circuit part. The Arduino itself only draws around 25 of these, which if running off of USB, leaves around 475mA that other things can draw.

@enric blanco made a good description. I just point out the strange difference between USB (5V) and barrel connector (7-12V).
The barrel connector has to accept different power supplies (with different voltages), moreover they may need voltage regulation; thus arduino needs a "regulator" after the barrel connector. There are different composants that can do it. This simple one will provoke a minimal loss of voltage. That is why you have to input more than 5V.
There are other components (buck/boost) that could accept input voltage from 3V to 12V and always provide 5V as output, but they are more expensive (5$).

On a basic level, the 5v of the USB port is regulated by the power supply of the external device, be it a computer USB port or a USB type charging module. When you are using the power jack on the Arduino, you can provide a range of voltage, from 7v (recommended minimum) to as much as 20v. This input power passes through a voltage regulator to provide the regulated 5v necessary to operate the Arduino.
Voltage is not "used up" by the Arduino, but you may have little reserve power for additional devices which are tied into the 5v bus.
Consider that voltage can be viewed in a manner similar to water pressure, while current can be compared to the volume of water flowing. If you have a 1000 mA power supply and the Arduino uses 500 mA, you have still available 500mA at 5v for other uses.
You can experience voltage drop in a circuit, depending on the way components are connected. That's more advanced than necessary for this discussion.
This is a very basic overview and details will vary from one model Arduino to another.
Also note that one should not apply 5v to other pins marked 5v as it bypasses the regulator and can damage the board or other devices attached.

You can supply five 5V directly to the 5V pin, which is effectively what the USB interface does. The quoted 7 to 12V is only if you are using the power jack. That converts it down to 5V which is what the processor needs.

No, you don't have to input more than 5V at the raw pin while exactly 5V is output at the VCC pin (at least with the Pro Mini).
How this is done I have no idea.

authors: Дмитрий Зюнин

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

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


text:
Ultrasonic sensors with 12v motors will not work! (ADRUINO)
ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!
The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.
this is the shield I am using: https://www.pololu.com/product/2507
if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...
the code.
#include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;

#define trigPin 7
#define echoPin 8

void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

//This is the sensor testing if somthing is in range!
if (distance < 4){
        Serial.println("in range");
        md.setM1Speed(100);
        md.setM2Speed(-100);
}
else {
        Serial.println("not in range");
        md.setM1Speed(-100);
        md.setM2Speed(100);
}

if (distance >= 200){
        Serial.println("!");
}
else {
        Serial.print(distance);
        Serial.println(" cm");
}
    Serial.println(distance);
    delay(500);
}

Why are you delaying the loop 500 ms at the end of each iteration?

TLDR: change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

You are using pins 7 and 8 for ultrasound.
At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5
You will see, that the shield is using pin 7 as M2INA and pin 8 as M2PINB
So each loop you push M2INA (trigPin) LOW, then HIGH then LOW, then wait until the sensor write HIGH to M2INB (echoPin) just to immediately send PWM pulses to both trigPin (M2INA) and echoPin (M2INB) via commands
    md.setM1Speed(100);
    md.setM2Speed(-100);

No way it can work as you expect.
You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare
#define trigPin 3
#define echoPin 5

and connect your ultrasound sensor there acordingly.
(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").
Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.

it works now! thank you very much! this is my first time using this website and it has saved my life :) thank you!!!!!!
I tried 3 and 5 and it didn't work... I tried 1 and 0 and it worked great! your smart XD thanks.

Nice, that it works now :) Can you mark it as answer?

I think I did it. I clicked the checkmark and the up arrow button.

Maybe it took some time to propagate thru th whole system :)


text:
Run 5V/2.3W water pump on Arduino Pro Mini 5V
I want to build up my automatic water pump with an arduino pro mini 5v and a 5v usb water pump (2.3 W). As I understand, I cannot power the pump directly through the vcc pins of the board, right?
Would it be possible to place a female USB Port in my system to power the board and the pump through a relay on the board? What would be an appropriate circuit diagram?

if the micro has a VIN pin, you can simply connect that to the pump, and switch the ground "on/off" using an n-chan mosfet like the IRLZ44N: gate to GPIO, drain to pump, source to GND. FETs switch faster and with less power than a relay, so you can even use PWM to slow down the pump!

As I understand, I cannot power the pump directly through the vcc pins
  of the board, right?

This is from the Arduino Pro Mini schematic:

Note that the maximum current output is 150 mA. On the other hand, your pump needs 2.3 W / 5 V = 460 mA > 150 mA. So your understanding is right: you can't power the pump directly through the Vcc pins of the board.

Would it be possible to place a female USB Port in my system to power
  the board and the pump through a relais on the board? What would be a
  appropriate circuit diagram.

There are lots of extremely cheap, commercially available, opto-isolated 5V relays modules in aliexpress and the like.
I'd recommend one like this because it allows you to have separate supplies for the relay coil and for the input diode in the opto. That will help you to avoid problems related to having "different" 5V levels due to dropout in the Pro Mini regulator.
Module picture:

Module schematic:

Module connectivity:

VCC --> VCC from the Pro Mini.
JD-VCC --> V+ from the power supply (same as RAW input to the Pro Mini).
COMMON --> V+ from the power supply.
NO (normally open) --> connect it to the 5V rail of the USB pump.
NC (normally closed) --> leave it unconnected.
Be sure to connect all grounds together.
I'd also recommend adding an additional decoupling capacitor close to the RAW pin of the Pro Mini, to protect the regulator from voltage spikes caused by switching-off inductive loads like the relay coil and the pump motor.

NOTE: take into account that the relay module can draw up to an additional 80-100 mA of current. Take that into account in your power/current budget.

Hi Florian you can take power from USB fro both Arduino and the water pump.This is the schematic you have asked for your project. An arduino Pin can give maximum 20mA current that's why we need a limit resister to limit the current below 20mA and also this current should be such a way that it can drive the switching transistor. So the challenging thing is choosing the correct resister
I have taken the value 1K
So the current at Arduino Digital pin is Current I = 5V/1k = 5mA which is below of 20mA and sufficient to drive the Transistor. you can use BC548 transistor also.

simulate this circuit – Schematic created using CircuitLab


text:
Arduino secure two way communication over radio
I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).
I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:
https://forum.arduino.cc/index.php?topic=314845.0
The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key->encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.
For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.
Any other ideas for secure communication?

Since you have two-way communication you can be far more cunning that just including a timestamp.  You can use real authentication.
The idea here is the "sender" first sends a request to the "receiver" saying "Let me in".
The "receiver" then sends back a message saying "Ok, here's your session key".
The "sender" then encrypts the connection credentials using that session key in some way (or encrypts it in some way including that key with the credentials) - ideally with a trapdoor hash algorithm, and sends it to the "receiver".
The "receiver" then does the same operation with the data it expects the "sender" should send, and compares it with what it received.
If they match, then the "receiver" can allow communication from that "client". The "receiver" would then send a new session key to the "sender" which would then be used to encrypt all communication thereafter. That key must be different to the first, and would need to use symmetric encryption.
This all means that:

The authentication key changes every time - there is no chance of "replaying" it
The communication key changes with each session, so again there is no chance of replaying messages at a later data, since the key will be wrong.

Yes, there are a lot of overheads with this method, but it's secure.
The authentication methodology is basically the Challenge Handshake Authentication Protocol (server sends challenge, client responds with credentials along with challenge, trapdoor encrypted, server compares with its own encryption and allows or denies).  The rest is basic encryption of your choosing using the unique key the remote end of the connection provides.

You may want to take a look at my RC4-with-diffusion algorithm RC4D which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.

RC4 should no longer be used for cryptographic applications; it's outmoded.

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


text:
Ping a sensor for error checking
Is it possible to ping a sensor, like DHT22 or 18B20, to check for connection. I want to do an error check in void setup() and make sure all sensors are connected properly.

There is no simple "yes" or "no" answer to this.
You need to check the datasheets and libraries for your chosen devices and see what is available.  Many libraries will have begin() function, which may, or may not, return whether the device is working.
Many may just lock up waiting for communication, and there's not a lot you can do with that short of reprogramming the library to work differently.
Some (especially analog sensors) will return values from their reading functions that are far outside a tolerable range that you could assume indicated a malfunction.
For I2C based sensors you could use a variant of the I2CScanner sketch to look at what addresses are in use before attempting to use the sensors themselves.
Other protocols may have a similar system you can use to examine what is on the bus.

There isn't one answer for all sensors. Some may implement a self-check; if not, an operator could provide a specific environment at startup, which setup() would test for. Otherwise, about all you can do is a sanity-check on the output.
DS18b20 - the Dallas/Maxim one-wire digital thermometer, for example, has a specific value immediately after reset; you could check for that before commanding a measurement. Or simply take a sample and make sure it "makes sense". The specific tests available depend on what a given sensor implements.


text:
Choosing a proper power source for for basic RC car with 4 motors
Help me to choose a power source for the below project:

4x DC Motors (3V~6V DC each with ~170mA),
1x Micro Servo Motor (4.8V~6V),
1x Ultrasonic sensor
1x Bluetooth sensor

It is basically an RC car. The project runs on Arduino UNO and it uses Motor Shield (1.2) to power up those five motors. The motor shield does support external power supply. Shall I go for that, or Arduino can power up the entire system altogether?

First thing I can say, Arduino Uno with external power has a 1A current limit.
Besides this, you'd better give some links to the shields and sensors you use then everybody can see the specifications of the devices before answering your question.

2S LiPo with 5V UBEC is what you want.  Hit your favourite RC model seller for those.  I use HobbyKing (as the links show).
The capacity choice of the LiPo depends on

How much power your motors etc need, and
How long you want it to run for

You could also go for 3S or 4S to get more power if your chosen UBEC supports the voltage.

Thanks for the comment with links. I am from India and the shipping time to India is horrible from that website. I checked with the local dealer and other websites and it seems there is no luck. Can you suggest a solution with 18650 batteries? like 2x18650 batteries for motor sheild and two for Arduino.? possible?

Many [fake] Arduino UNO boards on the market have an AMS1117 regulator for external power supply from 7.5v to 12v. note that it's a linear regulator and it "wastes" the excess power as heat and compared to the very demanding components you have (about 1 amps) it's obviously not an option. so no. you can't use "External" supply of Arduino to power them all.
it's best to use separate supplies for each board. or you may Use a 5V Battery Kit and connect it to 5V pin on either shields.

I believe that the "external power supply" on the motor shield refers to the fact that it can be powered off of an external supply rather than using the regulators on the Arduino board.

@sa_leinad of course it is. many motor applications use a lot of current (and higher voltage) which is far above the capabilities of Arduino's regulator or power tracks. they "must" be powered from an external supply of their own because of interference or heat. but in this case , it should be ok for 5V power rail(bypassed regulator) of Arduino.

Perhaps rephrase the line: "so no. you can't use "External" supply of Arduino to power them all."

@sa_leinad I assumed the "External supply of Arduino", is an external adapter or battery which goes through regulator of the Arduino UNO board. if the 5V input is considered external, then yes I should rephrase it


text:
Print Byte Array in Serial monitor screen of Arduino IDE
I need to print mentioned below byte array on the serial monitor screen of Arduino IDE
char b[]= {'0x7E', '0x00', '0x1C','0x90', '0x00', '0x13', '0XA2', '0x00', '0x41', '0x58', '0x1C', '0xCB', '0xFF', '0xFE', '0xC1', '0x7C', '0x00','0x0F', '0x00', '0x01', '0x00', '0x00', '0x37', '0x46', '0x46', '0x46', '0x00', '0x00', '0x00', '0xE7' };
void setup() {
Serial.begin(9600);
}

void loop() {
Serial.println(b[]);
delay(500);
}

But whenever I am trying a print, the error problem was there which was not resolved which is
C:\Users\Misha\Desktop\test\Test_2\Test_2.ino: In function 'void loop()':

Test_2:8:18: error: expected primary-expression before ']' token

 Serial.println(b[]);

                  ^

exit status 1
expected primary-expression before ']' token

Any suggestions on this will be great help.

what is b[]? array variable is simply b.

Hey, Thanks for the suggestion whenever I have used Serial.println(b) also but its printing only the LSB value, I am not able to print the MSB values.

of course. you can't print an array with print and invalid syntax will not help with it

What MSB values are you on about? You just have a list of 8 bit values. There is nothing "MSB" or "LSB" about them. I think you need to go back and rethink what it is you are doing and asking and get the two to match up.

You can’t print an array in that way.
If you want to print an array of hexadecimal value (with two digits), you have to use sprintf function and change declaration of b array.
uint8_t b[]= {0x7E, 0x00, 0x1C, 0x90, 0x00, 0x13, 0XA2, 0x00,
              0x41, 0x58, 0x1C, 0xCB, 0xFF, 0xFE, 0xC1, 0x7C,
              0x00, 0x0F, 0x00, 0x01, 0x00, 0x00, 0x37, 0x46,
              0x46, 0x46, 0x00, 0x00, 0x00, 0xE7};
int i;

void printHex(uint8_t num) {
  char hexCar[2];

  sprintf(hexCar, "%02X", num);
  Serial.print(hexCar);
}

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

void loop() {
  for(i=0; i<sizeof(b); i++){
    printHex(b[i]);
 }

 Serial.println();
 delay(500);
}

The output produced is:

7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
  7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
  7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7

Similar in this case It only displays the LSB values but no MSB values were displayed in serial monitor screen

What do you want to print? ASCII character or the hex value? In serial monitor Do you want this: 7E 00 ... ?

@varuljain I updated the answer.

Btw the buffer is too small to contain two characters and '\0' character.

I am anxious to understand HOW to use the Serial Monitor

I am anxious to understand HOW to use the Serial Monitor input line to write/change the elements of the array (instead of declaring the array as is done in [1 Answer ] above. marty Jan 8 2020


text:
I2C on ATtiny85 and Si4703 radio
I've got an Si4703 breakout from Sparkfun, which communicates via I2C. I have gotten it to work very easily using a regular 3.3V Arduino Pro Mini, but am now trying to move everything over to an ATtiny85. It seems this should be possible, but my I2C knowledge is basically zero.
SETUP
I have everything laid out on a breadboard:

ATtiny chip with 3.3V power and ground from a good power supply
Si4307 on the breadboard too
SDIO on digital pin #0 (pin 5 on the chip) with a 4.7K pull-up running to 3.3V and out to the breakout
SDLK on digital pin #2 (pin 7 on the chip), same as SDIO
A reset pin for the breakout, running from digital pin #1

I've verified this with the Pro Mini and it works great, so I'm doubtful the problem is here.
SOFTWARE
My ATtiny is set up using the TinyWireM library for I2C, and using a customized version of the Sparkfun Si4703 library. <-- if I had to guess, this is where the problem probably is... I think
My modded library files are here (too long to paste in the forum):
https://gist.github.com/jeffThompson/5e48c8915148e6e0bac7d85c9a3da948
https://gist.github.com/jeffThompson/10934cf8f07b3000e7e61601266b2b2c
And my Arduino code:

#include <TinyWireM.h>
#include <Si4703_ATtiny.h>

int SDA =   0;       // I2C data pin on ATtiny85
int SCK =   2;       // I2C clock pin on ATtiny85
int reset = 1;       // can probably be any digital pin

Si4703_ATtiny radio(reset, SDA, SCK);

void setup() {
  TinyWireM.begin();    // need this?
  radio.powerOn();
  radio.setChannel(937);
}

void loop() {
  radio.setVolume(15);
  delay(1000);
  radio.setVolume(0);
  delay(1000);
}

TESTING
I've tested both the Pro Mini and ATtiny85 version using my scope, but I'm pretty new to that tool, especially for I2C. I see similar clock and data patterns from both versions, and can see that there is readable I2C data from the ATtiny on my scope (it is finding readable hex data and sees it is ACK-ed, at least some of the time). I have programmed ATtiny chips through the Arduino IDE before, so I'm pretty familiar with that process, and double-checked things are outputting using an LED.
TLDR
I'm not anywhere near an I2C expert, and have never built an Arduino library, so I'm guessing I need some help with my modded library (unless I'm missed something else obvious).

Why all this trouble ? The ATtiny85 is not officially supported by Arduino and a ATmega328p in a small package is also very small.

You haven't explained your problem!

@Jot – the ATtiny85 is still cheaper, and doesn't require an external crystal.

@Gerben – the problem is it doesn't work! Since the ATtiny85 doesn't have serial, I can't easily see what the problem is. Was hoping someone with more knowledge could help find where the issue might be (the modded library code, etc).

Try adding an led for debugging.

@Gerben – I did (it's in the post, but there's a lot of info). I put one on the SDIO and SCLK lines, just to see if stuff is coming out. I can see I2C-looking data on my scope too, so I think the problem is code, not circuit.

The Si4703 has an approach that I'm not used to. It reads for example 32 bytes, and waits for ever after the requestFrom. You can remove that wait loop, it has no use. It uses millis in the wrong way. I think that the TinyWireM can do only 16 and not 32 bytes with requestFrom. Could you try other Si4703 code that is more "normal" ?

Thanks @Jot – it's basically the library from Sparkfun, replacing references to the Wire library. But if the TinyWireM library can't do 32 bytes, then I'm probably out of luck, right? (I don't know enough about I2C or the Si4703 chip to write any interface code myself, I'm afraid.)


text:
Why does this Arduino Pro Mini use a capacitor on the DTR reset line?
I'm kind of curious as to why there is a 0.1uF capacitor on this Arduino Pro Mini (https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf). It seems like it would work just fine without it.

"This question does not show any research effort..." ie, you really should do a web search before posting a question here, as if you had you would already know the answer.

One aspect of it wouldn't work fine without it. Do a little digging in the Arduino documentation, and you'll find out what.

The capacitor provides one of the most basic functionalities of the Arduino. If you don't know what that is, then google it.

Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.
This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.
The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.
So it will convert a LOW transition to a LOW pulse.

It is not the USB serial chip, it is the operating system serial driver's most common default mode settings.  And regardless of that, the Arduino programming process typically toggles it explicitly.


text:
Bug read an image from SD card and draw it on TFT
I have developed a code to read an image stored on my SD Card and display it on a TFT. I can read the image from the SD Card successfully but I cannot draw it on the TFT. I dunno where is the bug.
Could you please guys help me figure it out?
Board: Arduino DUE

#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>

#include "ascii_data.h"

#define SERIAL_PORT     9600

#define PIN_SCE         10
#define PIN_RESET       6
#define PIN_DC          5
// #define PIN_SDIN
// #define PIN_SCLK
#define PIN_LED         2

#define LCD_COMMAND     LOW
#define LCD_DATA        HIGH
#define CHAR_WIDTH      6
#define CHAR_HEIGHT     8
#define LCD_WIDTH       84
#define LCD_HEIGHT      48
#define CHARS_PER_ROW   (LCD_WIDTH / CHAR_WIDTH)
#define CHARS_PER_COL   (LCD_HEIGHT / CHAR_HEIGHT)

#define PIN_SCSD        4

void draw();
void reset();
void cls();
void lcdMode(int mode);
void lcdInitialize();
void printString(int y, const char *value);
void printString(int x, int y, const char *value);
int printChar(int x, int y, char value);
void setPixel(int x, int y, int value);
void lcdWrite(int value);

byte data[84][6] = {0};

String input = "";
bool complete = false;

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

void setup()
{
  // Enable I/O stream
  Serial.begin(SERIAL_PORT);
  Serial.println("Serial Init..");

  // pin modes
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_SCSD, OUTPUT);

  // SD stuff
  SD.begin(PIN_SCSD);

  // display stuff
  reset();

  SPI.begin(PIN_SCE);
  SPI.setClockDivider(PIN_SCE, SPI_CLOCK_DIV16);

  lcdInitialize();

  input.reserve(200);

  printChar(0, 0, 'a');
}

void loop()
{
  while (Serial.available() > 0) {
    char ch = (char)Serial.read();
    //Serial.print(ch);
    if (isprint(ch) && ch != '\n') {
      input += ch;
      //Serial.println(input);
    }
    else {
      complete = true;
    }
  }

  if (complete) {
    Serial.print("Command: ");
    Serial.println(input);

    //Serial.println(input.startsWith("exists(") && input.endsWith(")"));

    if (input.startsWith("exists(") && input.endsWith(")")) {
      String file = input.substring(7, input.length() - 1);

      Serial.print("File: ");
      Serial.println(file);

      File f = SD.open(file);
      if (f) {
        Serial.println("File does exists");
        f.close();
      } else {
        Serial.println("File does not exist");
      }

    } else if (input.startsWith("print(") && input.endsWith(".img)")) {
      String file = input.substring(6, input.length() - 1);
      File f = SD.open(file);
      if (f) {
        cls();

        Serial.print("Printing image: ");
        // Dimensionen auslesen
        int width = 0;
        int height = 0;

        char ch = '\0';
        String dim = "";

        while (f.available()) {
          ch = (char)f.read();

          if (ch != ',' && ch != '\n')
            dim += ch;
          else {
            if (width == 0) {
              width = dim.toInt();
              dim = "";
            } else if (height == 0) {
              height = dim.toInt();
            }

            if (ch == '\n') {
              break;
            }
          }
        }

        Serial.print("Dimensions of image: ");
        Serial.print(width);
        Serial.print(" x ");
        Serial.println(height);

        for (int i = 0; i < height; ++i) {
          for (int x = 0; x < width; ++x){
            char ch = '\0';
            while (ch != '\n') {
              ch = f.read();
              if (ch == ','){
                continue;
              }else (ch == '0' || ch == '1') {
                int pix = ch - '0';
                setPixel(x, i, pix);
              }
            }
          }
        }
      }

    } else if (input.startsWith("print(") && input.endsWith(")")) {
      String file = input.substring(6, input.length() - 1);
      File f = SD.open(file);
      if (f) {
        cls();

        int x = 0;
        int y = 0;
        Serial.print("Printing: ");
        while (f.available()) {
          char ch = (char)f.read();
          Serial.print(ch);
          if (-1 == printChar(x, y, ch));

          draw();

          x = (x + 6) % 84;
          if (x == 0) {
            y = (y + 8) % 48;
          }
        }
        Serial.println();

      } else {
        Serial.println("Error: File does not exist");
      }

    } else {
      Serial.println("Unknown command");
    }

    complete = false;
    input = "";
  }

  draw();

  delay(10);

}

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

void draw()
{
  lcdMode(LCD_DATA);

  for (int b = 0; b < 6; ++b) {
    for (int x = 0; x < 84; ++x) {
      lcdWrite(data[x][b]);
    }
  }
}

void reset()
{
  digitalWrite(PIN_RESET, LOW);
  delay(500);
  digitalWrite(PIN_RESET, HIGH);
}

void cls()
{
  for (int x = 0; x < LCD_WIDTH; ++x) {
    for (int y = 0; y < LCD_HEIGHT; ++y) {
      setPixel(x, y, 0);
    }
  }
}

void lcdMode(int mode)
{
  digitalWrite(PIN_DC, mode);
}

void lcdInitialize()
{
  lcdMode(LCD_COMMAND);

  // FUNCTION SET (extended instruction set)
  lcdWrite(0x21);

  // SET BIAS
  lcdWrite(0x14);

  // SET TEMP COEFFICIENT
  lcdWrite(0x04);

  // SET CONTRAST
  lcdWrite(0xBF);

  // FUNCTION SET (normal instruction set)
  lcdWrite(0x20);

  // SET DISPLAY MODE (normal)
  lcdWrite(0x0C);

  // reset display
  lcdWrite(0x40);
  lcdWrite(0x80);
}

void printString(int y, const char *value)
{
  printString((84 - strlen(value) * 6) / 2, y, value);
}

void printString(int x, int y, const char *value)
{
  do
  {
    printChar(x, y, *value);
    x += 6;
  } while (*++value != '\0');
}

int printChar(int x, int y, char value)
{
  lcdMode(LCD_DATA);

  if (value < ' ') {
    return -1;
  }

  for (int dx = 0; dx < 6; ++dx) {
    for (int dy = 0; dy < 8; ++dy) {
      setPixel(x + dx, y + dy, !!(font[value - ' '][dx] & (1 << dy)));
    }
  }

  return 0;
}

void setPixel(int x, int y, int value)
{
  if (x >= 0 && x < 84 && y >= 0 && y < 48) {
    if (value) {
      data[x][y / 8] |= (1 << (y % 8));
    } else {
      data[x][y / 8] &= ~(1 << (y % 8));
    }
  }
}

void lcdWrite(int value)
{
  digitalWrite(PIN_SCE, LOW);
  SPI.transfer(PIN_SCE, value, SPI_CONTINUE);
  digitalWrite(PIN_SCE, HIGH);
}

There seems to be a slightly vital part of your program missing - the part that actually writes the data[] array out to the screen...

@Majenko It seems to be in draw().

Ah so it does, didn't see that.

@Nsmit What do you see in the serial monitor? Did your code get so far as printing the dimensions correctly? Have you tried printing the contents of data to see if the image was written to it correctly? Have you successfully drawn or printed anything to the screen?


text:
Multiple dht11 on an wemos d1 r1
I am trying to connect three separate DHT11 to my Wemos d1 r1.
I have each sensor hooked to a power pin which turns on and off, the sensor pin and a common ground.
Here is my code:

#include <DHTesp.h>
#include <ESP8266WiFi.h>

String apiKey = "xxxxxxxxxxxxxx";
const char* ssid = "xxxxxxxxxxx";
const char* password = "xxxxxxxxxxxx";
const char* server = "api.thingspeak.com";

DHTesp dht;
DHTesp dht2;
DHTesp dht3;
WiFiClient client;

void setup() {

  pinMode(D6,OUTPUT);
  pinMode(D8,OUTPUT);
  pinMode(D1,OUTPUT);

    Serial.begin(115200);
    dht.setup(D5, DHTesp::DHT11);
    dht2.setup(D7, DHTesp::DHT11);
    dht3.setup(D2, DHTesp::DHT11);
    WiFi.begin(ssid, password);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
digitalWrite(D6,HIGH);

}

void loop() {
 digitalWrite(D6,HIGH);
  delay(8000);

    float t = dht.getTemperature();
    float f = (t*1.8) + 32;

    if (isnan(t))
  {
    Serial.println("Failed to read from DHT2 sensor!");
    return;
  }
    Serial.print(", \"maintemp\": ");
    Serial.print(f);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D8,HIGH);
delay(8000);

    float t2 = dht2.getTemperature();
    float f2 = (t2*1.8) + 32;

    if (isnan(t2))
  {
    Serial.println("Failed to read from DHT3 sensor!");
    return;
  }
    Serial.print(", \"lowtemp\": ");
    Serial.print(f2);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D1,HIGH);
delay(8000);

    float t3 = dht3.getTemperature();
    float f3 = (t3*1.8) + 32;

    if (isnan(t3))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
    Serial.print(", \"uptemp\": ");
    Serial.print(f3);
    Serial.print("}\n");

    digitalWrite(D1,LOW);

    delay(2000);

    if (client.connect(server, 80)) {
    String postStr = apiKey;
    postStr += "&field3=";
    postStr += String(f);
    postStr += "&field4=";
    postStr += String(f2);
    postStr += "&field5=";
    postStr += String(f3);
    postStr += "\r\n\r\n\r\n\r\n";

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n\n\n");
    client.print(postStr);

    Serial.print("Temperature: ");
    Serial.print(f);

    Serial.println("Sending data to Thingspeak");
  }
  client.stop();

  Serial.println("Waiting 20 secs");
  // thingspeak needs at least a 15 sec delay between updates
  // 20 seconds to be safe

  delay(53700);
}

As you can see I assign a separate DHT to each sensor pin and turn on and off the power pins to each sensor.  They all have a common ground.
When I run the code the first sensor reads the temperature but the second one says "Failed to read from DHT3 sensor!".
It is not the sensor because if I swap the first and second sensor the first one always read and the second fails.  If I eliminate the second sensor the third one fails.  I have tried to power all of the sensor pins in SetUP but still the first one is the only one to work.  Is there some kind of trick I have to use here.
I am using DHTESP.h since the regular DHT.h didn't work with the Wemos Pro Mini.
Has anyone had any experience with this to give me some guidance.
Thanks

Can you add a print of getStatusString in your error? For instance if (isnan(t))   {     Serial.print("Failed to read from DHT2 sensor: status ");     Serial.println(dht2.getStatusString());     return;   }. Do this for all three sensors, then post the output; it will tell you at least what is the error it detects (timeout? checksum? ...)

Can you draw a schematic diagram? What's the total measured pullup from the data line to the +5V line?

You probably have to create an set up a new DHT object each time you turn the power on. My guess is that the sensor needs to be initialized by the Arduino before it is ready to take readings, and when you turn the power off and back on it loses its configuration.


text:
I2C OLED conflicts with Interrupt
I'm using Nmradcc.h in combination with a OLED I2C.
The nrmadcc.h is using a interrupt 0 on Pin 2, the OLED uses A4 and A5.
After initialisation of the OLED and the Function
The problem is, I can use the Funktion with the Interrupt or the OLED, Not together.
But i want to. Can I stop the interrupt function with nointerrupt and than I2C and otherwise, or is there a better war?
Thanks Bert

#include <SPI.h>                  ////
#include <Wire.h>                 ////
#include <Adafruit_GFX.h>         ////
#include <Adafruit_SSD1306.h>     ////
#include <DCC_Decoder.h>
#define kDCC_INTERRUPT 0

Adafruit_SSD1306 display(128, 64, &Wire, -1);   ////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fill in the number of accessories / functions you want to control
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const byte maxaccessories=1;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

typedef struct {
  int               address;          // Address to respond to
  byte              mode;             // 0=continuous, 1=oneshot, 2=flasher
  byte              output;           // State of accessory: 1=on, 0=off (for internal use only)
  int               outputPin;        // Arduino output pin
  byte              highlow;          // State of outputpin: 1=HIGH, 0=LOW
  boolean           finished;         // Memory location that says the oneshot is finished
  int               durationonMilli;  // oneshot or flasher on time in ms
  int               durationoffMilli; // oneshot or flasher off time in ms
  boolean           isAnalog;         // false=digital, true=analog, sends analogValue to out pin.
  byte              analogValue;      // pulse with modulation (pwm) value that is written to pin. Range: 0 - 255
                                        // goto http://arduino.cc/en/Reference/AnalogWrite to see which pins support analog pwm output
  unsigned long     onMilli;          // for internal use
  unsigned long     offMilli;         // for internal use
}
DCCAccessoryAddress;
DCCAccessoryAddress accessory[maxaccessories];

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fill in the attributes for every accessory / function
// COPY - PASTE as many times as you have functions. The amount must be same as in line 17 above!
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ConfigureDecoderFunctions() // The amount of accessories must be same as in line 26 above!
{
  accessory[0].address = 1;    // DCC address
  accessory[0].mode = 0;       // Continuous. HIGH until DCC switches the address off again.
  accessory[0].outputPin = 13; // Arduino pin where function is connected to.
  accessory[0].output = 0;     // Initial state (0 or 1) of output after startup.

  for(int i=0; i<maxaccessories; i++)
  {
    if (accessory[i].outputPin)
    {
      pinMode( accessory[i].outputPin, OUTPUT );
      // Set initial state (only for mode 0, continuous)
      if (!accessory[i].mode && accessory[i].output) digitalWrite(accessory[i].outputPin, HIGH);
      else digitalWrite (accessory[i].outputPin, LOW);
      }
    }
  }  // END ConfigureDecoderFunctions

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // DCC accessory packet handler
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  void BasicAccDecoderPacket_Handler(int address, boolean activate, byte data)
  {
    // Convert NMRA packet address format to human address
    address -= 1;
    address *= 4;
    address += 1;
    address += (data & 0x06) >> 1;

    boolean enable = (data & 0x01) ? 1 : 0;

    for (int i=0; i<maxaccessories; i++)
    {
      if (address == accessory[i].address)
      {
        if (enable) accessory[i].output = 1;
        else accessory[i].output = 0;
      }
    }
  } //END BasicAccDecoderPacket_Handler

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup (run once)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  DCC.SetBasicAccessoryDecoderPacketHandler(BasicAccDecoderPacket_Handler, true);
  ConfigureDecoderFunctions();
  DCC.SetupDecoder( 0x00, 0x00, kDCC_INTERRUPT );
  pinMode(2,INPUT_PULLUP); //Interrupt 0 with internal pull up resistor (can get rid of external 10k)
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW); //switch off Arduino led at startup
  for (int n=0; n<maxaccessories; n++) accessory[n].output = 0; //all servo's to min angle and functions to 0

  display.display();
  display.clearDisplay();

} // END setup

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Main loop (run continuous)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
  static int addr = 0;

  DCC.loop(); // Loop DCC library

  if( ++addr >= maxaccessories ) addr = 0; // Next address to test

  if (accessory[addr].output == 1)
  {
    if (accessory[addr].mode == 0) accessory[addr].highlow=1; // continuous

    if (accessory[addr].mode == 1) // oneshot
    {
      if (!accessory[addr].highlow && !accessory[addr].finished)
      {
        accessory[addr].highlow = 1;
        accessory[addr].offMilli = millis() + accessory[addr].durationonMilli;
      }
      if (accessory[addr].highlow && millis() > accessory[addr].offMilli)
      {
        accessory[addr].highlow = 0;
        accessory[addr].finished = true;
      }
    }

    if (accessory[addr].mode == 2) // flasher
    {
      if (!accessory[addr].highlow && millis() > accessory[addr].onMilli)
      {
        accessory[addr].highlow = 1;
        accessory[addr].offMilli = millis() + accessory[addr].durationonMilli;
      }
      if (accessory[addr].highlow && millis() > accessory[addr].offMilli)
      {
        accessory[addr].highlow=0;
        accessory[addr].onMilli = millis() + accessory[addr].durationoffMilli;
      }
    }

      display.setCursor(90, 50);  ////
      display.setTextSize(2);     ////
      display.print(F("ON")) ;    ////

  }
  else // accessory[addr].output == 0
  {
    accessory[addr].highlow=0;
    if (accessory[addr].mode == 1) accessory[addr].finished = false;

      display.setCursor(90, 50);  ////
      display.setTextSize(2);     ////
      display.print(F("OFF")) ;    ////

  }

  if (accessory[addr].highlow)
    {
      if (accessory[addr].isAnalog) analogWrite (accessory[addr].outputPin, accessory[addr].analogValue);
        else digitalWrite (accessory[addr].outputPin, HIGH);
    }
  else
    {
      if (accessory[addr].isAnalog) analogWrite (accessory[addr].outputPin, 0);
        else digitalWrite( accessory[addr].outputPin, LOW);
  }
  display.display();
} //END loop

In this sample is the I2C OLED not working.
When I change the spot of
Adafruit_SSD1306 display(128, 64, &Wire, -1);

and
DCC.SetupDecoder( 0x00, 0x00, kDCC_INTERRUPT );

The DCC interrupt is not working, the OLED does work.

Please edit the question if you have more information or updates.

I2C requires precise timing to work. If interrupts fire while the Arduino is trying to read or write to the I2C bus, it will fail. I suspect you'll have to disable interrupts each time you read/write to the I2C bus and then re-enable them when you are done.

Thanks,
so everywere were display is called i need to use nointerrupts()?


text:
I2C potentiometer mess
I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!
I found a code for controlling an I2C pot in one of the arduino examples which is something like this:
#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte val = 0;

void loop() {
  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
  // device address is specified in datasheet
  Wire.write(byte(0x00));            // sends instruction byte
  Wire.write(val);             // sends potentiometer value byte
  Wire.endTransmission();     // stop transmitting

  val++;        // increment value
  if (val == 64) { // if reached 64th position (max)
    val = 0;    // start over from lowest value
  }
  delay(500);
}

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!
void setPot0(int n){
  if (n>256) n=256;
  if (n<0) n=0;
  Wire.beginTransmission(address);
  if (n<256){
    Wire.write(0x00);
    Wire.write(n);
  } else{
    Wire.write(0x01);
    Wire.write(0);
  }
  Wire.endTransmission();
}

and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that?
I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

what is your actual question? ....  the only question in your post is asking something about complaining

my question is how on earth should I send the I2C commands to use the pot. as I mentioned the code I wrote works but matches non of the I2C address and data patterns that they mentioned in their data sheet. I'm not sure what the control bytes should be and what's a general call vs a normal call? they just say general calls can change multiple pots (if present)?

general call and normal call are actually part of the I2C specification, it has to do with addressing single or multiple I2C devices

Does chapter 4 of the datasheet not give you all the information you need? Including the details of the THREE registers (yes, only THREE) for controlling the device?

I still can't find this pattern in any of the pages on datasheet -- Not even in Chapter 4, table 4-1 where it lists the registers? Register 0 is pot 0, and register 1 is pot 1. Clearly stated.

The registers are listed in table 4-1. Clearly enough.
The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.
Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.
So to write a pot 0 value of 0x23 you would write:
0x00 0x23

To write a pot 1 value of 0x65 you would write:
0x10 0x65

To write a pot 1 value of 0x13D you would write:
0x11 0x3D

You can make a simpler function to wrap it for you:
void writePot(uint8_t address, uint8_t pot, uint16_t val) {
    Wire.beginTransmission(address);
    Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
    Wire.write(val & 0xFF);
    Wire.endTransmission();
}


text:
Changing ESP-12E NodeMCU to ESP-01S - how to trigger sketch?
I had my sketch up and running with a NodeMCU and a Leonardo Pro Micro and decided I wanted to minimize the footprint of the project and use the smaller ESP-01S board instead.
The ESP-01S is programmed to send a push notification to Pushover and my old code works - the only problem is that I don't know how to trigger it from the Pro Micro.
With the NodeMCU I just setup it up to listen on Pin 2 and I triggered a high/low from my Pro Micro and it sent the push notification - at the moment as soon as I power the ESP-01S up it just sends the push notification over and over and doesn't see the connection from the Pro Micro to stop it doing this.
Here is my current code on the ESP-01S

#include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "Redacted";
const char* password = "Redacted";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "Redacted";
char userkey [] = "Redacted";
int length;
WiFiClient client;
void setup() {
  pinMode(0, OUTPUT);
  digitalWrite(0, LOW);
  pinMode(2, INPUT);
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
if(digitalRead(5) == 1) pushover("Deployment Completed");
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

and my Leonardo Pro Micro code is as follows
#include <HID-Project.h>
#include <HID-Settings.h>
int buttonPin;
int buttonPin2;
char chr;   // for incoming serial data, type char is signed 8-bit, -128 to 127, ASCII is char codes. Save 1 byte over type int.

void setup() {
  pinMode(5, OUTPUT);
  pinMode(7, OUTPUT);
  BootKeyboard.begin();
  Keyboard.begin();
  Mouse.begin();
  Serial.begin(115200);
  buttonPin = 4; //White Button
  buttonPin2 = 6; //Black Button
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  delay(5000);
  digitalWrite(5, HIGH);
  delay(100);   //short wait time
  digitalWrite(5, LOW);
  }

Obviously I want the digital pin 5 of the Pro Micro to trigger the ESP-01 to send a push notification when it's trigger.
Just for the record I'm using a 3.3v Pro Micro btw so there's no issue with the voltage here, before I was using a Logic Converter with a 5v board.
I have the ESP-O1S setup with the 3V3 and EN are connected to the 3v VCC on the Pro Micro, the GND to GND and I tried IO0 and IO2 to Digital Pin 5 on the Pro Micro.
Could someone point me in the right direction?

why do you read pin 5 in esp8266?

Use io 0 as the esp-01S pin wired to Micro, but change the logic for pull-up, because esp-01S has a pull-up resistor on io 0 of the esp8266. Use LOW to trigger the action and HIGH as normal state.
On Arduino Micro side set the output pin HIGH before you set it as OUTPUT. This will avoid the LOW state. While the Micro pin is in INPUT state after power-up, the pull-up resistor on esp-01S will pull io 0 HIGH.

Gotcha, so do I need to change any of this code on the ESP-01S?
void setup() {
pinMode(0, OUTPUT);
digitalWrite(0, LOW);
pinMode(2, INPUT);
Serial.begin(9600);
delay(10);

in esp8266 pinMode(0, INPUT); and if (digitalRead(0) == LOW) pushover("Deployment Completed");

Got it, cracked it, thanks Jaraj!

Just to double check, the correct way on the Leonardo to change the logic is to just set the pin write as HIGH in setup right? There's no way to flip it when you set it out as a Output (that I can see)

yes set it HIGH before setting it as output, to avoid the LOW state which would trigger the action


text:
Memory size issue with the struct
I am working on a project where I have to build an IR program that works with all of the AVR/Arduino boards to control the IR devices such as TV, DVD, etc. I am building a struct that can carry the Pronto code information and this is what I have so far:
struct Pronto {
    char* code;
public:
    Pronto(){}
    Pronto(char* code) {
        bool isValid = validateProntoCode(code);
        if(isValid)
            this->code = code;
    }
    Pronto toPronto(char* code) {
        Pronto cde(code);
        return cde;
    }
    void setPronto(char* code){
        bool isValid = validateProntoCode(code);
        if(isValid)
            this->code = code;
    }
    char* toString(){
        return code;
    }
    private:
    bool validateProntoCode(char* code) {
        if(!isInHex(code[strlen(code)-1]))
            return false;
        for (int i = 0; i < strlen(code); i++) {
            if (!isInHex(code[i]) && !(i % 5 == 4 ))
                return false;
            if (i % 5 == 4 && code[i] != ' ')
                return false;
            if (i % 5 == 0 && (!isInHex(code[i]) || !isInHex(code[i] + 1) || !isInHex(code[i] + 2) || !isInHex(code[i + 3])))
                return false;
        }
        return true;
    }
    bool isInHex(char c) {
        char list[22] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f'};
        for (int i = 0; i < 22; i++) {
            if (c == list[i])
                return true;
        }
        return false;
    }
};

This struct code
I can set the Pronto code, validate it, and get the string value from it.
Now, whenever I declare the struct inside the Arduino IDE:
pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");

I get this following message:

Sketch uses 4082 bytes (12%) of program storage space. Maximum is 32256 bytes.
Global variables use 2137 bytes (104%) of dynamic memory, leaving -89 bytes for local variables. Maximum is 2048 bytes.
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.

Pictures:
https://prnt.sc/ohu4d9
https://prnt.sc/ohu4io
https://prnt.sc/ohu4m8
https://prnt.sc/ohu4pr
https://prnt.sc/ohu4tn
Basically, I just showed all my work on code I did. I commented out any global vars, nothing changed. BUT, when I comment "pronto.setPronto("0000 0000");", I get free space.

So, how can I modify this struct in-order for it not to take allot of space?

The char* code right? That's the problem. Now can you help me modify code or at least tell me how I can resolve this.

The struct itself does not use a lot of space, I see mainly the code itself with has 40 bytes. The message says, that your global variables take up 104% of the memory. There is the problem, but you didn't show us your global variables. Maybe you can reduce the number of global variables, when they don't really have to be declared the whole program runtime.

I did. When I comment out "pronto.setPronto("0000 0000");", I get allot more free space. But all the #define, #include and other global vars I commented out, nothing changed. I am going to add the url with pics on the post just to show you.

Ehm, how long is the proto code there? It is definitely way longer than the one in your question

It shouldnt matter, the Pronto code can be as long as it can be. You know what it is right? All I did was to store the Pronto code string to char* variable. I couldn't use string nor its library since the header won't let me. I ended up using char*.

You store the code in a global variable, so yes, it does matter, how big it is. You only have 2KB

In your screen shots you are using string literals that are waaaay longer than in your sample code. I suspect using PROGMEM could be a way to work around. But why bothering with constant strings and verify and convert them at run time and not store them as raw data instead? (Also the outcome of the verification for a constant string literal will be always the same. So consider removing verification of your production code.)
uint16_t myParsedProntoCode[] = {
    0x0000, 0x006D, 0x0000, 0x00BF, 0x009F, 0x0031, 0x0030, 0x0010, 0x0010, 0x0031
};

This is much more space efficient as storing a nibble (4 bits) requires only 4 bits instead of 8 bits. So just half the space, not even taking the pointless whitespaces into account.

Thank you so much, now it is saving up more space.

Based on your question I prepared a fresh sketch (single file) to test the issue.
The code:
struct Pronto {
    char* code;
  public:
    Pronto() {}
    Pronto(char* code) {
      bool isValid = validateProntoCode(code);
      if (isValid)
        this->code = code;
    }
    Pronto toPronto(char* code) {
      Pronto cde(code);
      return cde;
    }
    void setPronto(char* code) {
      bool isValid = validateProntoCode(code);
      if (isValid)
        this->code = code;
    }
    char* toString() {
      return code;
    }
  private:
    bool validateProntoCode(char* code) {
      if (!isInHex(code[strlen(code) - 1]))
        return false;
      for (int i = 0; i < strlen(code); i++) {
        if (!isInHex(code[i]) && !(i % 5 == 4 ))
          return false;
        if (i % 5 == 4 && code[i] != ' ')
          return false;
        if (i % 5 == 0 && (!isInHex(code[i]) || !isInHex(code[i] + 1) || !isInHex(code[i] + 2) || !isInHex(code[i + 3])))
          return false;
      }
      return true;
    }
    bool isInHex(char c) {
      char list[22] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'};
      for (int i = 0; i < 22; i++) {
        if (c == list[i])
          return true;
      }
      return false;
    }
};

Pronto pronto;

void setup() {
  pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");
}

void loop() {}

The verification procedure for ATmega328P returns:
D:\Extra\Arduino\BatteryRestorer\BatteryRestorer.ino: In function 'void setup()':

D:\Extra\Arduino\BatteryRestorer\BatteryRestorer.ino:50:71: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");

                                                                       ^
Sketch uses 844 bytes (2%) of program storage space. Maximum is 30720 bytes.
Global variables use 83 bytes (4%) of dynamic memory, leaving 1965 bytes for local variables. Maximum is 2048 bytes.

Can you check if this one file sketch is still experiencing the issue? Maybe you installed and linked a library that allocates a lot of global variables.


text:
How To Activate H-Bridge?
My understanding of the H-bridge is, that activating in1 or in2 will direct the 12V current to the motor, so it either spins right/left. Not that in1 or in2 is the actual current passing through to the 12V motor.
These are the schematics.
I am trying to activate the H-bridge and the 12V motor by powering In1 with digital 2 from my Arduino.
The power outlet is an universal adapter connected to my wall outlet, which then goes to a breadboard power supply.
I don't have a functioning multimeter, so I cannot measure the exact current going through, but I do know, that if I place in1 in the power outlet's Vout the 12V motor spins.
Other than that, I do not have much information, and I would like to ask you guys for help as to why, the 12V motor doesn't spin when I power in1?

You don't have a ground connection between the Arduino and the H-bridge?

@Majenko This is about the dumbest mistake I have made in a long time. Thank you, it needed a common ground.

It's not a dumb mistake. It's a common mistake. So common I wrote an entire blog article all about it. https://majenko.co.uk/blog/importance-sharing-grounds

George, you should post a self-answer with the solution and then accept it so the question is marked as answered. (Or @Majenko should post an answer, since they're the one who identified the solution.)

@DuncanC Will do, I can accept it in 2 days.

There was no common GND between the H-Bridge and the Arduino.
The question has been solved.


text:
Multiple push buttons
I am behind a problem of controling multiple leds with multiple push buttons. Lets say that I have 5 push buttons and 3 leds. Led1 turns on if at least 1 out of the 5 push buttons is pressed. Led2 turns on if at lest 3 push buttons are pressed and Led3 turns on if at least 4 push buttons are pressed.
How can this be solved ? With if else ?arrays?
here is my code that i have
 const int led1 = 2;
 const int led2 = 3;
 const int led3 = 4;
 const int bp1 = 9;
 const int bp2 = 8;
 const int bp3 = 7;
 const int bp4 = 6;
 const int bp5 = 5;
 int state;

void setup()
 {
 Serial.begin(9600);
 pinMode(led1, OUTPUT);
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(bp1, INPUT);
 pinMode(bp2, INPUT);
 pinMode(bp3, INPUT);
 pinMode(bp4, INPUT);
 pinMode(bp5, INPUT);
}

void loop()
{
 state = digitalRead(bp1);
 state = digitalRead(bp2);
 state = digitalRead(bp3);
 state = digitalRead(bp4);
 state = digitalRead(bp5);
if (state = HIGH)
{ digitalWrite(led1, HIGH); }

if (state = 3 )
{ digitalWrite(led2, HIGH);
if (state >= 4);
{ digitalWrite(led3, HIGH); }
}
else { digitalWrite(led1, LOW); }
}

Please format your text so it can be readen

i did it but i don't know exactly how to edit it very nicely

When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k.  Or highlight the code and click the {} icon in the toolbar at the top of the editing box.  To highlight text click-drag across it or use the arrow keys while holding the shift key.

To get the functionality you want the code should be:
void loop()
{
 state = 0;
 if (digitalRead(bp1) == HIGH)
   state = state + 1;
 if (digitalRead(bp2) == HIGH)
   state = state + 1;
 if (digitalRead(bp3) == HIGH)
   state = state + 1;
 if (digitalRead(bp4) == HIGH)
   state = state + 1;
 if (digitalRead(bp5) == HIGH)
   state = state + 1;

 if (state >= 1)
   digitalWrite(led1, HIGH);
 else
   digitalWrite(led1, LOW);

 if (state >= 3 )
   digitalWrite(led2, HIGH);
 else
   digitalWrite(led2, LOW);

 if (state >= 4) // you had a ; here.
   digitalWrite(led3, HIGH);
 else
   digitalWrite(led3, LOW);
}

There are more shorthand ways to write this e.g.if (digitalRead(bp4) == HIGH) state = state + 1; could be replaced with digitalRead(bp4)?state++; but until you are familiar with programming it's often best to use the longer but clearer way of writing things.
If all you are doing is lighting LEDs then de-bouncing the buttons isn't necessary, any LED flicker caused by the contacts bouncing won't be visible to your eye.
If however at a later date you want to trigger other logic in your program to run once per button press then you will need to worry about that. All buttons and switches bounce a little when you close them, without something in the electronics or software to cope with that a single button press can look like a dozen very quick presses to your software.

Your code won't work as is. Each time you assign a value to state you're overwriting it in the next line. You could, for example have multiple int state variables such as state1 for the first line in the loop then state2 in the second etc. Then you need to compare values (don't use = on its own in a compare as it will assign the value being tested - use == instead). This way you gather all the button states first.
Or you could test the state of a button and if pressed add 1 to state:
if (digitalRead(bp1)) {
    state++};

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.
However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.
R3.

I solved my problem by myself with if..else structures. I am happy that I got this working and I learned something new. Thank you all for help and inputs.
int led1 = 2;
int led2 = 3;
int led3 = 4;
int bp1 = 9;
int bp2 = 8;
int bp3 = 7;
int bp4 = 6;
int bp5 = 5;

void setup()
 {
 Serial.begin(9600);
 pinMode(led1, OUTPUT);
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(bp1, INPUT);
 pinMode(bp2, INPUT);
 pinMode(bp3, INPUT);
 pinMode(bp4, INPUT);
 pinMode(bp5, INPUT);

}

void loop()

{

if (digitalRead(bp1)== HIGH or digitalRead(bp2)== HIGH or digitalRead(bp3)== HIGH or digitalRead(bp4)== HIGH or digitalRead(bp5)== HIGH )
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);
 }
else
{
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);

 }

if (digitalRead(bp1)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH)
    {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led3, HIGH);
    }
else
  {
   digitalWrite(led1, HIGH);
   digitalWrite(led2, HIGH);
   digitalWrite(led3, HIGH);
   }

if (digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH)
   {digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, LOW);
}

else
 {  digitalWrite(led1, HIGH);
   digitalWrite(led2, HIGH);
   digitalWrite(led3, HIGH);
   }

}

Your solution works, that's nice. But it's far from efficient. You check the state of the button for ridiculous amount in each loop. You may want to consider another algorithm, as seen on another answer here. And since the problem is solved, don't forget to accept an answer :)

I would do this:
 state = (state & ~STATE_MASK1) | ((digitalRead(bp1)==HIGH)?STATE_MASK1:0); //assuming buttons are active high
...

if (state & STATE_MASK1)
{ digitalWrite(led1, HIGH); }

it holds up to 8 button states for a uint8_t type.
edit: here is a quick implementation.
//state = 0;                                            //reset the state

//read the buttons - all active high
state = (digitalRead(bp1)==HIGH)?STATE_BP1:0;
state|= (digitalRead(bp2)==HIGH)?STATE_BP2:0;
state|= (digitalRead(bp3)==HIGH)?STATE_BP3:0;
state|= (digitalRead(bp4)==HIGH)?STATE_BP4:0;
state|= (digitalRead(bp5)==HIGH)?STATE_BP5:0;

//process the buttons
digitalWrite(led1, (state & STATE_BP1)?HIGH:LOW);   //active high - led1 is high if bp1 is high
digitalWrite(led2, (state & (STATE_BP2 | STATE_BP4))?LOW:HIGH); //active low - led2 mimics bp2|bp4 => led2 high if both bp2+bp4 are low
digitalWrite(led3, ((state & STATE_BP3) && (~state & STATE_BP5))?HIGH:LOW); //active high -> led3 is high if bp3 is high and bp5 low

the code controls 3 leds:

led1: it mimics bp1;
led2: it goes high if both bp2/bp4 are high;
led3: it goes high if bp3 is high and bp5 is low.

I picked the output logic for no particular reason.
here is the output:

you can check the waveform against the logic, :)
again, this is just one particular implementation and you can write your own code / logic to produce your desired outcome. the principle is the same.

Thank you all very much for your time and help, much appreciated ! Now I am going to read and to study everything.

I read everything, tested both codes and still not working :(

My programming level unfortunately is not yet so good to fully understand above written: (


text:
USB DEVICES WITH THE 32U4?
I have an Arduino Pro micro and I need to know if it is possible to use an USB device like a camera or things like that Since the processor is a 32U4. the USB Shield is for the Arduino Uno and I don't want to buy more stuff.

no; you can't get a "driver" for a normal USB camera for the MCU. you would need something closer to a Pi...

Some important facts:

The 32U4 cannot act as a USB master, only a USB device (it doesn't have a USB OTG interface).
The USB shield is an SPI based device. It can communicate with any host MCU that can use SPI, as long as you can wire it in properly.
The Arduino doesn't have the processing power or memory to deal with the sheer onslaught of data a USB camera sends.

So yes, you could use the USB shield with a 32U4 based board if you can work out the right wiring. However you will not be able to use things like cameras with it since you lack the processing power to do it.
For camera work you need something more like a Raspberry Pi.

or a serial/ftp camera...


text:
Typedef Function Pointer Invoking Issue
I'm having an issue trying to use a normal non-member function of my main sketch file as a callback.  I can't get the function pointer to invoke from a function other than it was saved.  More info below;
MotorEncoder.h
typedef void (*cb)(int16_t,int16_t);
class MotorEncoder
  ...
  private:
    cb _motor_callback;

Program.ino
cb encoder_cb = NULL;
...
encoder_cb = function_that_accepts_2_int16
DC_Encoder_1.move(motor_pos, speed, motor_id, encoder_cb);

EDIT: I want to edit the description as to not confuse anyone.  The code with the callbacks above is all correct.  The issue was I was working with open-source software and another developer was setting the selected serial-port connection back to the bluetooth channel in-correctly.  The callback was executed, I was connected to the ATMega2560 via serial connection to a raspberry pi and was looking for the callback to show there, not monitoring bluetooth so I didn't see any data come across.  Document your code.

You need to post code, not describe it. Please read How do I ask a good question?. Please post a Minimal, Complete, and Verifiable example.

I can't get the function pointer to invoke from a function other than it was saved. - I don't understand that sentence.

I'll mock up a simple example when I have time later tonight / this week.  But just to try and explain when I say that I mean I can use the function pointer inside of the "move" function and see it being called in my Program.ino file.  I recieve the function pointer and can immediately use it to call back into Program.ino
Program.ino calls this call later inside of it's loop function, say to function: "Function1".  "Function1" checks some variable and if true then attempts the callback but I don't see any code execute back in my Program.ino file.

This answer contains a few debugging guidelines, as I don't know what the problem is and don't see how one could tell without a good deal more of information.
I suggest creating a Minimal, Complete, and Verifiable example (MCaVe) of your code, not just snippets, so that other people can compile and run the code, thus being able to observe what happens in more detail and perhaps with added debugging output.
I'm presuming your callback is triggered as a consequence of an interrupt occurring.  I suggest you write the MCaVe to depend on a pin-change interrupt, rather than a motor-controller interrupt, to allow testing on a system consisting of no more than an Arduino with a button, a serial interface, and perhaps a few LED indicators.  Pressing the button would change pin voltage and cause an interrupt; your ISR would turn on an LED to signal it handled the interrupt, then trigger the callback.  The callback routine would turn on another LED as its signal.  The main loop would read the pin register bits for the two LEDs, record and report the times they came on, and turn them off after a second or two.  If you get a simple setup like this to work, the technique probably would carry over to your motor-controller case; or if not, probably being a smaller program and setup should be easier to debug and figure out why not.

I'll give that a go, and post a simple example back here if I'm not successful.   I am using an interrupt but it simply sets a volatile variable.  The motor class is then called from the Program.ino loop function, checks the variables and should perform the callback if needed.
I was trying to fix a larger firmware system for a group of people.  I'll mock something up more simple first and see if the problem exists,

@BruceBannor, ok; and I'd recommend posting the simple example, successful or not, as it will allow others to look for problems or improvements. +1

I finally had some time today to look at everything again, and I wanted to provide anyone who stumbles on this an update.  I'm going to mark this as the accepted answer.  Quick context; I'm working on an open-source firmware for the MakeBlock MegaPi, fixing a bunch of the calls and api's that I found broken for others in the community.
Through some debugging and using the serial monitor I found where they were always setting the serial-port back to the bluetooth connection.  I'll edit my answer as I'll run out of characters here.  The advice here is great for any general issue though.