text:
Time remaining with os_timer_t
The Ticker library for the ESP chips is quite useful, which wraps a os_timer_t object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha os_timer_t object?

The library just calls os_timer_setfn and os_timer_arm which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the Ticker class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing uint32_t remaining = timestamp_now() - timestamp_started.
A good function to hook would be the _attach_ms in Ticker.cpp. Add a uint32_t timestamp_started variable in the Timer.h header for the class. Then set timestamp_started = system_get_time() (from user_interface.h). Then write a function uint32_t remainingUs() { return system_get_time() - timestamp_started; }. Beware of integer overflows -- system_get_time returns passed microseconds since µC startup.

I was hoping there would be an os_timer call to see this, but this will work well enough.

The documentation (http://espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf, section 3.1) lists no such call for os_timer objects.


text:
Max current of Vin and 5V pin on Arduino Nano
What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

It's hard to say. The maximum the on-board regulator can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

The voltage of your supply
The ambient temperature around the board
The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.
Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).
However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).
The VIN current will be the same as the 5V pin current + the board current.

Oops. Silly me, should have read better.

@gerben It happens...

What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

it depends on the power dissipation limits (and to a less extent the current limit) on the regulator. the power dissipation is determined by the load your arduino and its loads draw, and the voltage dropout on the regulator.
the other part of the thermal limit is the thermal resistance of the package and ambient temperature.
Most of them use el cheapo 1117 regulators in sot223 that has a limit of 1amp + a thermal limit of 100c/w. so max power dissipation should be less than 1w. That means a practical limit of 0.5amp under the most aggressive conditions (2v dropout, or 7v input).
at 9v input, max of 0.25amp.
at 12v input, a max of 0.15amp.
...

source: Stack Exchange

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

sort: votes


text:
Port 0x6F problem
When I disassemble an Arduino IDE created pjoject I see in the created code ("disassembled code actually"), the it uses IN / OUT instruction on port 0X6F.
Like this (part of disassembled list):
00E3     4FFF                SBCI      R31,0XFF                 ; .O
00E4     91A5                LPM       R26,Z+                   ; ..
00E5     91B4                LPM       R27,Z                    ; ..
00E6     B79F                IN        R25,0X6F                 ; ..
00E7     94F8                CLI                                ; ..
00E8     1161                CPSE      R22,R1                   ; a.
00E9     C004                RJMP      L00EE                    ; ..

00EA     918C                LD        R24,X                    ; ..
00EB     9530                COM       R19                      ; 0.
00EC     2338                AND       R19,R24                  ; 8#
00ED     C002                RJMP      L00F0                    ; ..

00EE     91EC      L00EE:    LD        R30,X                    ; ..
00EF     2B3E                OR        R19,R30                  ; >+
00F0     933C      L00F0:    ST        X,R19                    ; <.
00F1     BF9F                OUT       0X6F,R25                 ; ..
00F2     9508      L00F2:    RET

Anyway the ATMEGA328 Datasheet says that port 0x6F is memorymapped and as such should be accessed through LDS/STS instructions.  This problem really confuses me.  Can anyone give me an explanation ??  Thanks !

What is the original C/C++ code?

avr-objdump disassembles those bytes to in r25, 0x3f and out 0x3f, r25, which is consistent with Mikael Patel's answer. It looks like your disassembler is broken.

The AVR operation code for the IN instruction is:
Loads data from the I/O Space (Ports, Timers, Configuration Registers, etc.) into register Rd in the Register File.

Operation:
(i) Rd ← I/O(A)
Syntax: Operands: Program Counter:
(i) IN Rd,A 0 ≤ d ≤ 31, 0 ≤ A ≤ 63, PC ← PC + 1
16-bit Opcode: 1011 0AAd dddd AAAA

The disassemble of the operation code B79F (hex) = 1011 0111 1001 1111 (bin) is IN R25,$3F which is actually SREG.
The block of code with the IN, CLI and OUT instruction is a critical section where the flags in SREG are saved, interrupts are turned off, and later the SREG is restored.
Cheers!

Thansk a lot . I'll check with the Disasm creator, tell him the problem and recompile when I get a new version.. Hope that solves the problem.   Anyway many, many thanks for the constructive answers.

HI: (time 22:23 European  time):   Called him, told him about the error. He examined. Corrected it. Returned a new version. I ran it. Disassembled the file (which give the above list), io-ports are now correct (all in range 0x00 - 0x6F) Thank for a valuable help.  KSH

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


text:
how to establish a connection between an arduino and a web server?
I want to establish a connection between my arduino mega ( which is connected to an ethernet shield so internet access is available) to a web server. Any idea how the code should be?
I searched for it but all I found was a local host connection establishment.
Thanks in advance.

None of the examples in the IDE help you?

That's the one thing i forgot to check. I'll get to it right now.

The answer of this was already existing in the arduino examples which I forgot to check at first. Thanks Majenko for making me notice.

@jsotola - actually this is an answer, as it resolves the question.  When a solution is posted as a comment, summarizing it in an answer is permitted; short of closing the question (as subsequently happened here) it's typically the only way the system can be convinced to consider the issue resolved and avoid having it bubble back up every few months to annoy everyone.

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


text:
if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet?
i have two arduino mega and they send data to each other by an I2C connection. But one of those arduinos is connected to an ethernet shield which allows it to send data to a web server. Being both connected does that mean that they both can send or access the web server. Sorry if any ambiguity was found but I didnt find a better way to ask this question.

I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.
However, you could write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.
However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.

Thank you my friend, this couldn't be answered better.

It can but only if the one with the shield allows it (it acts like a router).
The only way for the arduino without the shield can communicate with the internet if it can send a message to the one with the shield and it will forward that message and return the replies back.


text:
Read one(2) hex-adresses from a string
On a 2560 MEGA I use serial(0) and serial1.
Serial1 is connected to an AT-328P   (not an UNO but a single AT controller)
The 2560 use Interrupt (serialevent) and Serial1Event.
Serial(0) is connected to the PC(USB) and is used to get commands that are planned to control both microcontrollers. And RX1 /TX1 (Serial1Event) is connected to the AT-328P .
I plan to use single letter Commands (eg. 'A' , 'B' .... 'Z') followed by a
delimiter (space or comma) again followed by 1 to 4 hexadecimals arguments.
EG:  "A 00,FFFF,AA,00"  or  "B,00,FFFF,33,00"  or "C 00,FF,FFFF,11"  or
"D 01,0000,FFFF,01" or "E,00,0910,1"
Valid delimiters are space, comma and Carriage Return
First argument is the number of the controller (00 = 2560 / 01 = AT328P, second to 4'th is the actual command to the controller.
The problem is parsing the command line from the PC. The one I use is far to slow (I scan the inputBuffer char by char and take my desiscion from that) - much to slow.
Now I want to parse the inputBuffer BEFORE I check the command letter (saving time and get the param's before I go into the specific subroutine) but here I  am i trouble.  I dont' know how to convert the 4 (2) Ascii chars into a valid HEX (or INT) -value.
I have seen some code somewhere ( and naturally forgotten where) doing it, but the methods I have used till now is oldfashioned and (far) out of date, and I am not very good to C++ (but I wanna learn it), so  I will be ashamed showing it.
Can any one give me an idea how to proceed .
Thanks
Kris AKA Snestrup2016

You wrote “The [parser] I use is far to slow”. It's actually pretty hard to make a parser slower than the serial stream that feeds it.

@Edgar Bonet Sorry, what I mean, I use the Serial0event Interrupt and after receiving the CR I parsed the input line. I did that in a most unconvienient way as described in the question. So now I an searching for a new (smarter) way to do it.

DARN, I have just found out, that SERIAL_EVENT IS NOT the same as Interrupt , so I have to rewrite all my code.  (#¤&%¤%&¤%#¤)..  So I will redraw this question  (if possible) and come back later.   Anyway Thanks for any thoughs and help so far.

Yeah, I was about to tell you that. SerialXEvent is just a function that gets called between each iteration of loop(). If you want to make it properly interrupt driven you will have to scrap the HardwareSerial class crutch and write your own UART code.

One thing I added to the chipKIT version of the Arduino-esque API was to have Serial.attachInterrupt(...) so you can intercept the normal ISR for character reception. Maybe something Arduino should think about adding too...


text:
Post-split, where do I download the Arduino IDE?
I've been out of the loop with Arduino for several years.  I heard about the split (another link), but didn't really understand, nor keep up with it, nor the details of the fallout.
Today, I decided to jump back in and make something, and a DDG search led me to Arduino.cc to get the software.  But is that what I need?
How do I know if that's the right software IDE?  Is there another location?  Does it matter?  Does it depend on more variables?  Is this split akin to the OpenOffice and LibreOffice split, where one is more better (technical term!) supported than the other?
I'm working on an Arduino Uno I got from Microcenter.

The split is already over. They are working on merging everything that happened during the split, if they haven't already.
I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).

Both sites contain the same version of the IDE. .Org dropped their 1.7.x branch (actually 1.0.x renumbered) and both now have the 1.6.x branch version-bumped up to 1.8.x.
As Gerben noted, the split is over, The rift is healed!.


text:
Arduino HTTPClient passing string to variable
For some reason I can't seem to pass a simple string from one variable to another. Below is my code:
  HTTPClient http; // Declare an object of class HTTPClient
  http.begin(address); // Specify request destination
  int httpCode = http.GET(); // Send the request

  Serial.println("String: " + http.getString());

  String prp = http.getString();
  Serial.println("temp string: " + prp);

It prints out:

String: < ! DOCTYPE HTML>
  26
temp string:

Why doesnt my string get correctly passed on to my temporary string variable?
Tom

The getString() method calls writeToStream which is documented write all  message body / payload to Stream. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.

Is there a way I can adapt my code so that it will still work?

isn't it obvious? read into variable and then print the value of the variable. remove the redundant println

Isn't that what I do? The first println works fine, it's the second one that's the problem!

you throw away the String used in first println. but the response was only in that String. call to getString put the received bytes into that String.

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


text:
Connecting two sensors with bluetooth
I am new with Arduino. Im working in a school project, and I decided to create a glove with shock sensor for goalkeepers and need a ultrasonic sensor next to the ball, so i can know when the ball was kicked.
I need the data from both sensor.
Is this possible with only 1 arduino?, where the arduino is with the ultrasonic sensor and the shock sensor is connected with a bluetooth module to send it to the arduino.
Or, I have to use 2 arduinos?, one with with the glove and the other with the ultrasonic sensor and connect both with bluetooth?
If this is not the best way, can you help me with some ideas to do it? Thank you.

what are you trying to measure? .... how will the device be used?

This to be possible with only 1 Arduino depends in your sensor. It is most likely not possibpe without another microcontroller (not nesessarily an Arduino) because of the following reason.
Most bluetooth modules on the market (linke the HC-05 vor HC-06) are bluetooth serial modules, meaning that they build a serial connection over bluetooth and provide the corresponding two pins (RX and TX). Yet most sensors don't implement an UART interface (the Serial interface in Arduino), but only give an analog or digital output voltage. With much work you might be able to tweak the firmware of the bluetooth chip for reading and sending a digital value, but this would be more work, than the price of a second microcontroller would justify.
So I would try to add a small microcontroller (like an ATTiny85) to the sensors side. It can measure the sensors output voltage and then send it via Serial to the bluetooth module. You might also want to use another Arduino here, though this might be an overkill. Maybe a really small version.

After some thinking I had the idea, that it might be possible to send an analog voltage from the sensor through a audio bluetooth module without using another Arduino. Though I'm not sure if this really would work and which module you need for that.
All in all I still would go for the extra microcontroller and serial interface bluetooth, because it is much easier for a beginner.
EDIT:
Above I mentioned using Serial on an ATTiny85, which is not directly possible, since it does not have a full UART hardware (but only a USI). Though you can use the standard SoftwareSerial library on it. If the rest of your code isn't to big, it should still fit in the small memory of the Tiny.


text:
How can I initialize an array of objects in setup?
How can I declare an empty global array, to be initialized in setup?
What I would like to do is this:
#include <ResponsiveAnalogRead.h>

const size_t ANALOG_SIZE = 3;
const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

void setup() {
  for(size_t i=0; i<ANALOG_SIZE; i++){
    analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
  }
}

But the error I get is:
sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
 ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                              ^

Is it impossible to declare an empty array of a given size?

did you try the example sketch that came with the library?

@jsotola yes, that compiles just fine, but that uses only one ResponsiveAnalogRead object.
https://github.com/dxinteractive/ResponsiveAnalogRead also shows how to use multiple, but initializes them globally, not in setup, I want to loop over an array of pin-numbers to initialize multiple of them.

As Craig wrote, the declaration of an class typed array will call the default constructor of the class, which is the one without any arguments. The class, that you use, does not provide a default constructor, since it needs it's parameters. You cannot do it this way.
But you can use dynamic allocation. In global scope only declare an array of pointers to ResponsiveAnalogRead objects:
ResponsiveAnalogRead *analog_reads[ANALOG_SIZE];

This array only holds pointers, that can point to ResponsiveAnalogRead objects. The objects themselves are not created yet. In setup() you can then create the objects dynamically with the new statement:
analog_reads[0] = new ResonsiveAnalogRead( input_parameters);

(Of course you have to replace input_parameters with all parameters, that the constructor needs). To call a member of the object, you can dereference it like this:
analog_reads[0]->member_function();

If you don't know about pointers yet, you should google for a tutorial (there are plenty), so that you understand the principle behind them.
Important note: Dynamic allocations of memory geht written to the heap in RAM. Since the Arduino (especially the Atmega based ones) has only very limited RAM, dynamic allocations have to be handled with great care. You should not create and delete data often in your program, since this would make swiss cheese out of your heap. But allocating the memory only once in your program and never deleting it, will not be a problem, as long as you don't try to allocate too much memory.

Makes sense! I have some experience in C, so I do know pointers :) Thanks for elaborating.

Craig already explained the reason of the error is the lack of a default
constructor, and chrisl suggested a reasonable alternative. I would like
to suggest two other alternatives.
Static initialization
You state that you want to do the initialization in setup(), but you
don't explain why you want that. I will guess that what you really
want is to have all those objects in array. The library page provides
this example showing how to statically initialize multiple instances:
ResponsiveAnalogRead analogOne(A1, true);
ResponsiveAnalogRead analogTwo(A2, true);

The problem with this example is that you don't have an array, so you
cannot loop through the instances. This problem, however, can be easily
fixed:
const size_t ANALOG_SIZE = 3;
ResponsiveAnalogRead analog_reads[ANALOG_SIZE] = {
    ResponsiveAnalogRead(A0, true),
    ResponsiveAnalogRead(A1, true),
    ResponsiveAnalogRead(A2, true)
};

Note that you don't need the ANALOG_PINS array anymore. And you don't
need to pass 0.01 as the last argument to the constructor, as this is
the default value anyway. This would be my preferred solution: it is
simple enough and doesn't increase the number of lines of code.
Patching the library
If you really want to initialize the array in setup(), then you can
patch the file ResponsiveAnalogRead.h from the library:

Add default values to all the parameters of the constructor. For
example:

ResponsiveAnalogRead(int pin=0, bool sleepEnable=0, float snapMultiplier=0.01);

Add a method for setting the pin after initialization:

void setPin(int newPin) { pin = newPin; pinMode(pin, INPUT); }

The first change will enable you to compile your code as-is. The second
change will allow you to update the objects in setup() rather than
overwriting them (which I don't find very elegant):
for (size_t i = 0; i < ANALOG_SIZE; i++) {
    analog_reads[i].setPin(ANALOG_PINS[i]);
    analog_reads[i].enableSleep();
}

Note that using the default constructor now has the side effect of
setting pin 0 to input. This should not be a big deal, as the
constructor is called before setup(), and all the IO pins are inputs
at this point. If you want nevertheless to void that side effect, then
set the default pin to -1, and patch the constructor to only configure
the pin if it's not -1.
Patching the library creates a maintenance burden though: you will have
to reapply the patch each time the library is updated. This may not be
that bad if you know how to git rebase or git merge, but ideally you
would want to get a pull request accepted by the original maintainer.
Edit: Before patching the library, consider weighting in this
issue and using this fork.
Update: A pull request addressing this issue has been
accepted. As of version 1.2.0, the class has now a default “do nothing”
constructor.

Thanks for an even more elaborate answer!
By the way, the reason I want to initialize in setup() is because I want to multiplex these analog pins to 16 channels. I want each multiplexed channel to have its own ResponsiveAnalogRead object. That also means I do not want to get rid of the ANALOG_PINS  array, because I want to loop over that 16 times :) I considered patching the library after @Craig 's answer, but I have no C++ experience. Thanks for suggesting the issue and the fork, but I've gone with the solution offered by @chrisl already.

When you declare an array it will call the default constructor for the type. ResponsiveAnalogRead does not have a default constructor so it cannot initialize the entries in the array.


text:
Serial communication between GPS and Arduino Ethernet
I'm trying to read out GPS positions from a serial GPS module I have.
I'm using an Arduino Ethernet and a Haicom HI-204 III GPS (http://www.haicom.com.tw/driver/hi-204iii_usb.pdf).
If I connect the GPS directly to my computer (through a USB-serial converter) at 4800 baud, 8N1, I receive a nice stream of position and diagnostics messages:
$GPGGA,183652.000,5702.0870,N,00954.4732,E,1,06,2.0,20.5,M,42.5,M,,0000*62
$GPGSA,A,3,22,08,27,18,11,32,,,,,,,3.4,2.0,2.7*37
$GPRMC,183652.000,A,5702.0870,N,00954.4732,E,0.00,,310518,,,A*70
$GPGGA,183653.000,5702.0870,N,00954.4732,E,1,06,2.0,20.5,M,42.5,M,,0000*63
$GPGSA,A,3,22,08,27,18,11,32,,,,,,,3.4,2.0,2.7*37
$GPRMC,183653.000,A,5702.0870,N,00954.4732,E,0.00,,310518,,,A*71
$GPGGA,183654.000,5702.0870,N,00954.4732,E,1,06,2.0,20.5,M,42.5,M,,0000*64
$GPGSA,A,3,22,08,27,18,11,32,,,,,,,3.4,2.0,2.7*37
$GPGSV,3,1,12,08,67,204,28,18,59,267,23,10,47,067,26,11,46,279,32*72
$GPGSV,3,2,12,27,36,156,30,01,33,270,20,32,31,116,32,28,26,314,18*79
$GPGSV,3,3,12,22,21,217,33,14,15,140,24,20,09,055,,24,04,038,*7D
$GPRMC,183654.000,A,5702.0870,N,00954.4732,E,0.00,,310518,,,A*76
$GPGGA,183655.000,5702.0870,N,00954.4732,E,1,06,2.0,20.5,M,42.5,M,,0000*65
$GPGSA,A,3,22,08,27,18,11,32,,,,,,,3.4,2.0,2.7*37
$GPRMC,183655.000,A,5702.0870,N,00954.4732,E,0.00,,310518,,,A*77
$GPGGA,183656.000,5702.0870,N,00954.4732,E,1,06,2.0,20.5,M,42.5,M,,0000*66

Now I'm trying to read these messages from the Arduino. But when I connect the GPS to a SoftwareSerial port, I only get gibberish:

:⸮⸮J2⸮⸮>>⸮

(note that when I copy/paste the output to here, many of the charaters disappear, so they are probably completely invalid)
My code looks like this:
#include <SoftwareSerial.h>

#define rxPin 3
#define txPin 4

SoftwareSerial gpsSerial(rxPin, txPin); // RX, TX

void setup (){
  Serial.begin(4800);
  gpsSerial.begin(4800);
}

void loop (){
  while (gpsSerial.available()) {
    char c = gpsSerial.read();
    Serial.write(c);
  }
}

In think the output looks like wrong serial settings, but I have tested all speeds (and verified that 4800 baud works through the serial adapter), and as far as I can tell, SoftwareSerial is 8N1 by default.
What am I doing wrong?

What USB adaptor are you using?

The GPS unit you link to is a USB device, not a serial device. How can you be connecting that through a USB to serial converter?

Good question :-) The USB unit simply becomes USB because they have a serial to USB-converter on the cable between the GPS and the USB plug. So I cut the cable on the serial side of the converter and connected that to the Arduino.

So you don't actually have any information about the electrical signalling the unit uses? You need an oscilloscope to examine the signal - see if it's TTL or EIA-232 signalling.  If it's the latter you will need to feed it through a MAX232 first.

Further Googling leads me to the theory that I might need a RS232-to-TTL converter between the GPS and the Arduino. I'm not sure, though, as I supply the GPS with 5 V directly from the Arduino, so there should be no need for a step down from 12 V.

It's not just stepping down - it's inverting and removing the negative voltages.

Ah, you're too quick :-) No, I don't have any further information, and unfortunately also no scope available. So I guess I will test a MAX232 (somebody also suggests that here: http://forum.arduino.cc/index.php?topic=9798.0)

Awesome, thanks for that info. I'll try it and check back in when I get hold of the hardware. Thanks again!


text:
DMX on the Arduino without additional driver chip
I recently saw this video where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.
Based on my research DMX is RS-485 and for this there's a driver chip required.
So I have three questions about this:

Why do all sources I found say that there's a driver chip required when it seems to work without?
I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

The physical layer of a DMX interface is based on differential signaling over an RS485 link.  This is exactly what is said here on the DMX Arduino.cc page.
A differential signal (like RS485 or USB) can travel greater distances than signals which reference ground (like RS232, I2C or SPI).  This is because noise, which affect both sides of a differential signal, can be canceled out at the far end when one of the signals is inverted then added to the other by the differential receiver.
Connecting one side of a differential receiver to ground and driving the other side with logic level voltage is not recommended.  Even if it worked and did not cause harm to the transmitting processor nor the differential receiver the signal will likely be susceptible to undesirable noise.
RS485 is a ubiquitous standard and likely several easily sourced designs exist for the Arduino.

RS485 or RS422 and consequently DMX use differential drivers at 5 volts.  This means that both lines are 0 to 5V nominally, with a (usually, depending on the cable used) 120 ohm resistor as a terminator on both ends.  A 3.3V signal might work, but barely.
perhaps sending the signal on one line and just 0V on the other might work sort-of, but I've never tried or even heard of that.
My guess would be that in this case they are using a bit-banged serial port modified to also control the other pin, but inverted.  Perhaps something could be done with a standard serial port on one pin, setting up an interrupt on that pin changing level, and using the ISR to check the level on the 'serial pin and invert it and set the other pin.  I think that would probably incur too much of a delay between the two pins, but perhaps not.  Strictly speaking, the delay between the two pins changing if it was bit-banged is probably out of spec for RS422/485, but might work anyway unless the baud rate was higher.
If you are going to use DMX, spend the $0.30 and buy a driver chip or a bit more and get a DMX shield.  I've seen DMX get screwed up by a whole lot less than the differential line being a bit out of sync.


text:
Atmel studio 7 vs Arduino IDE for register level coding?
Which one is better to get started with register level embedded c coding?
Also which one is used professionally?

doesn't matter. 2) Arduino shouldn't be used professionally.

I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it very difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the avr-gcc tool chain and then simply use the text editor of your choice.
As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.

How do you set up a Make based setup directly on top of the avr-gcc tool chain. i don't know how to go about doing it. So, it would be great if you could give some insight on how to do it.

Here’s an avr template I created and a digital thermometer project I’ve been working on based on it.

Atmel Studio for professional. Arduino is for fun and is normally the first step into embedded c programming using the atmega328 (Arduino)


text:
Why is there no embedded c code in arduino libraries?
When I took a look at how the arduino libraries were coded I expected to see register names like I/O registers(PINx,DDRx,PORTx) and other such registers with values assigned to them but instead I saw normal C code with functions and a class.
Why isn't there any embedded C in the structure of the library? Am I misunderstanding something very basic? Please help me understand.

If you take a look at the Arduino core library (e.g., the AVR version of
wiring.c), you will see lots of low-level register access. That's
why the core code is specific to a processor architecture.
Other libraries are built on top of the core API in order to be
portable.

Then why do people even code using low-level registers when they can just use the core API?

@Roshan: 1. Performance: digitalWrite(), for example, is more than 100 times slower than direct port access. 2. Hardware features: the core only provides access to the most generic stuff, you can fully exploit the hardware capabilities only if you access the hardware directly.

Because the Arduino API abstracts those things.
If you put that kind of low-level code into a library the library becomes non-portable.  By sticking to the Arduino API (digitalWrite, pinMode, etc) the library can be used on all boards.


text:
How to connect Mg995 and arduino nano since nano can only output 40mA at max?
Datasheet for Mg995 shows:
Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?

The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.
So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.


text:
Arduino reading string sent from Rpi multiple times
1.Reading strings sent from Arduino on RPI
Below you can see that I am communicating between a rpi and arduino serially. I am sending "start", then move_played to the rpi. The readline() reads until a newline so, first start gets read then the move_played string(it's like read the move played only after encountering the string start)
Python code on RPI
s1 = serial.Serial('/dev/ttyACM1', 9600)
stockfish = Stockfish('/usr/games/stockfish')
while 1 :
    if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
           move_played = str(s1.readline(),'UTF-8').strip('\n\r')
           print(move_played)

Code on Arduino
void SendMove();
String movePlayed ="e2e4";
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  SendMove();
  exit(0);
}
void SendMove()
{
  Serial.println("start");
  Serial.println(movePlayed);
}

2.Reading strings send from RPI on Arduino
The  goal for the arduino is to read the bestMove string after it reads "Rstart". But when I run the code on the rpi(sending the strings). The lcd prints "Rstart" and not the bestMove string. So from what I can see is that once the "Rstart" string is sent , the first readString() in the if condition , reads " Rstart" and the the second readString() in the print statement reads "Rstart".
Why is the string"Rstart" stll in the serial Buffer even after being read once?
Python Code on RPI
bestMove = "b3c7"
s1 = serial.Serial('/dev/ttyACM1', 9600)
s1.write(bytes("Rstart","ascii"))
s1.write(bytes(bestMove,"ascii"))

Code on Arduino
#include "LiquidCrystal.h"
const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
  lcd.begin(16,2);
  Serial.begin(9600);
}
void loop()
{
  if (Serial.available()>0)
  {
    if(Serial.readString() == "Rstart")
    {
      lcd.setCursor(0,0);
      lcd.print(Serial.readString());
      delay(10000);
      exit(0);
    }
  }
}

it should not work at all. you send "Rstartb3c7" and readString should read it in one piece

so, how do I send it as 2 separate strings and read them separately,I've been trying but can't seem to find out.


text:
Necessary torque of motor to move a door.
I am building an automatic door opener and for its mechanism I need a motor with a high torque and low speed. My question here is how to measure the torque needed to move the door as I cannot really weigh the door and find its mass. Can anyone help me out?

Ask a moderator to change this to Electronics.stackexchange.

This is more of a question about applied physics, and not about electronics.

You need a "hanging scale" preferably "analog one".

Mount it to any place of the door and slowly pool at 90 degrees. Check what value does the scale show when doors start moving. Static friction is always higher than dynamic friction.
Torque = Radius * Force
Raduis is the distance between mounting place and door hinges.
Force is 9.81 times max value shown by the scale in kilograms.
Do this many times for many mounting points then take average.
Use safety margin of 50% (motor should have at least 150% of required torque)


text:
Powering a water pump with nodemcu
I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.

Is this the pump you are using? https://www.aliexpress.com/item/YIXINYOU-DC-12V-Diaphragm-Vacuum-Pump-Water-Pump-Oxygen-Pump-Air-Pump-DSL-2-12-020/32819735122.html

Your question does not seem to have anything to do with either Arduino Hardware or Arduino software, so it is unclear on what basis it would belong on this site.  Generally for a motor you want an NFET, not a bipolar transistor, and you must not route the power through the microcontroller board.

It is indeed the pump i am using.

Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good.  The pump should have a separate power supply, or at least be powered in parallel with the Arduino.  Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.

But as shown here: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
The Vin is connected to the USB port via a diode so the power does not go "through" the Arduino.

@zbut you just described the power for the pump doing through the MCU board and specifically its diode, which exactly what you were told was a bad idea.


text:
Detect if Serial1 and Serial2 are defined, at compile time
I have my library that uses Serial, Serial1 and Serial2 to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.
Problem is, Serial1 and Serial2 are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error
'Serial1' was not declared in this scope.
So I figure I need to adjust my code with preprocessor directive like #if defined, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

Not sure if the SDK has particular hardware defines setup for things like a serial port.  Most look at the SDK's processor defines and use conditional compilation directives such as "#ifdef ARDUINO_AVR_UNO".

Also, I'm looking at the ArduinoBoardManager at github source code and do not see where they define hardware like serial port on a per processor bases.  Maybe you could add that and re-use this code.  But I still think the easiest way about this is pick what serial port code you want to compile based on the processor type.  Look at the source code in this github project to see how they did this.

Why not make the constructor take an object reference of type Serial (or HardwareSerial or even Print)?

HardwareSerial.h in Arduino AVR boards core defines HAVE_HWSERIALX
example
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

Consider the approach used here in the ArduinoBoardManager project at github.  The file ArduinoBoardManager.h uses conditional compiling to determine the correct code to compile based on processor type.  A similar approach can be used to asses if certain hardware peripherals such as serial ports were available based on processor type.
#if defined(__AVR_ATmega328P__) // uno, fi
  // Code compatible with an Arduino Uno
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // Code compatible with an Arduino Mega
#endif

why do it, if HardwareSerial.h does it for you. and for example Uno Wifi has additional hw Serial1 (to connect onboard esp8266) even it is a 328p

Oh, I agree - I didn't know about the alternatives until posted here.  I just knew how the ArduinoBoardManager project was handling it.


text:
ESP32 WiFiClient request missing response
I am facing problem with ESP32. I use basic example for WiFiClient and making request to my server. The problem is that the response should be 15000 bytes long, but very often I got only 2750 or less.
char buffer[15000];
while (client.available()) {
  char c = client.read();
  buffer[i++] = c;
}
Serial.println(i);

You are assuming that all 15000 bytes are available all the time.
They won't be.
Instead of "while available read something" you need to "While not enough has been read, then if available read something".
When reading from (assuming) HTTP you first need to read and interpret the headers (the lines before a single blank line).  One of these will be the "Content-Length:" header, which will tell you exactly how many bytes are in the body of the response. Then you use that to read the right number of bytes from the body.
So the sequence is:

Read line by line for the headers interpreting the ones you need to, until:
You receive a single blank line
Read the data byte-wise until you have read the number of bytes indicated in the Content-Length header.

If you aren't reading from an HTTP server and you are certain that the data is exactly 15000 bytes in length then you need to skip to point 3 above. Never assume that all the data is there. If there is data then read it, and repeat until you have totalled 15000 bytes.

Thanks, the problem was probably caused by client.available(), while reading response, it found a gap when client has no data available and so ends the reading.
When I havent got enought data, I wait (with timeout) to get some data available.


text:
I2c device disappear from bus after writing
I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a TLV493D connected by I2C. I know from this thread that before using this device, I have to set the powermode :
Wire.beginTransmission(HallAddressWrite);       // Address the sensor
Wire.write(configReg);              // Address the Configuration register
Wire.write(powerMode);              // Set the Power Mode to Low
errorCode = Wire.endTransmission();             // Stop transmitting

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of default I2C scanner
if (error == 0)
{
  Serial.print("I2C device found at address 0x");
  if (address<16)
    Serial.print("0");
  Serial.print(address,HEX);
  Serial.println("  !");

  Serial.println("Beginning write test...");
  Wire.beginTransmission(address);
  // no register writing
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  Serial.println("SECOND Beginning write test...");

  Wire.beginTransmission(address);       // Address the sensor
  Wire.write(0x00);              // Address the Configuration register
  Wire.write(0x05);            // Set the Power Mode to Low
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  nDevices++;
}

which gives the output:
I2C device found at address 0x5E  !
Beginning write test...
Test ended with code : 0
SECOND Beginning write test...
Test ended with code : 0

And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).
More informations :

My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.
My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.
I also have a SRF02 on my I2c bus : it is working as expected.
I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.
I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.

Have you checked, that the supply voltage doesn't fall too low, when writing to the TLV via I2C? During reading the datasheet I thought, this maybe would show the seen behavior by resetting it everytime, you write to it.

Hi chrisl, thank you for replying. That actually was a good point, but unfortunately, supply voltage stay constant at 3.3V.

To sum up this problem :
TLV493D configuration work by writing two bytes with I2C. You must begin by writing 0x00, which will be ignored since the first register is reserved. Then, you write a second byte that will actually do the configuration (second register).
The three smalest bits enable or disable INT, FAST and LOW mode.
I still don't understand why I am not able to enable INT mode on my Atmega32u4 while it doesn't seem to be a problem on Uno or Mega (on LOW mode). Anyway, two configurations work for me :
0x07 --> INT, FAST and LOW are all enabled
0x01 --> only LOW is enabled
I don't think it's a issue to disable INT. If I understood correctly, it will make the device send an interrupt pulse to request microcontroller reading. If you manage readings by yourself, I don't think you need INT to be enabled.
Many thanks to CodeGorilla for his support.
UPDATE:
I managed to get an Arduino Leonardo. Indeed, all my obsevations on my Atmega32u4 based card are still corrects (writing 0x05 second register make the device disappear from bus, but not with 0x01 or 0x07). But again, it works normally on Uno or Mega... Really odd ! If anyone has an explanation to offer, it would be greatly appreciated.

By default the FAST register is set to 0 at power up.
When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.
Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".
Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.
Also - Do you have pull-up resistors on the I2C bus?  You might encounter problems without them.  They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.

Thanks for your answer. I am not quite sure I understand though. At which point of my code am I setting LOW to 0 ?
I do have a pull-up resistors on my I2C bus.
And finally, what I really don't understand is why I have to do all that, knowing that my code is working just fine on Uno and Mega ? I mean, what is the Atmega32u4 difference ?

@erenaud , that is the wrong kind of question. You should do everything right, and then solve any remaining problems. Is your atmega32u4 running at 3.3V? Then you don't need a level shifter. Use pullup resistors. Follow the datasheet.

@Jot As I said, I am using pullup resistors.

Sorry I missed the fact that it was "working" on a Uno and Mega.  When using it with a Uno/Mega do you use a 5V or 3.3V I2C bus?  According to the code you have included above and the datasheet you link to you are writing to Write Register 0 with the value 5.  Register 0 is reserved and must not be written to or have I misread the data sheet?

@CodeGorilla I am using 3.3V bus. Indeed, I thought I was writing to register 0 with value 5, but I got mislead by the comment on the code snippet I found on the arduino forum's thread I linked. Actually, I am doing exaclty as the example in page 13 of the user manual. The first writing (0x00) is for the first reserved register. Then, I write (0x05)) to the second register, which set FAST to 0, INT to 1 and LOW to 1.

@CodeGorilla I noticed something interesting: when writing 0x07 to the second register (so FAST, INT and LOW are all set to 1), I don't loose my communication with the device. But of course, my readings are totally wrong since the code I currently used  doesn't support FAST mode.

@erenaud - Could it be that enabling INT ("not recommended for I2C") and disabling Fast are causing the problem, have you tried a value of 0x01? for the second reg?

@CodeGorilla Indeed, it is working as well and I think you are absolutely right, INT shoudln't be put enabled. Thank you for your help !


text:
ESP8266 communication issue
I have an issue communicating with ESP8266 via Arduino Uno's serial ports.
I can connect to it using
python -m serial.tools.miniterm /dev/ttyUSB0 115200
command but when trying to send an AT command, it looks like this:
�tC�

ERROR
�v[�
ERROR
at

OK

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only 115200 works.
I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.
My schematic looks like this:

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.

Where are the voltage dividers from Arduino TX to ESP RX to shift from 5V to 3.3V? Are you sure the module is not on its default 9600 baud? Why is the ESP's EN not pulled up? Does adding a big capacitor between 3.3V and GND help?

Regarding voltage dividers: I was unaware it was needed. I've been more or less following this instruction: http://www.instructables.com/id/Arduino-motion-detector-PIR-that-writes-to-SQL-via/
Regarding the 9600 baud: Pretty sure - when I try to connect at 9600 it's all gibberish.
ESP EN: Will look into it
Capacitor: Will look into it

Appendix: With EN (Enable) I meant CH_PD (chip powerdown) -- but you already had it conencted to 3V3, so that's ok. Most probably it's because of the voltage shifting or the power supply is too bad.

3.3 V pin of Uno can't supply the necessary current for the esp8266.

115200 is the default baud rate of AT firmware

@Juraj I'll try to get some sort of external supply running tomorrow and report back

check the wires and connections. try connect the ground directly, not over breadboard

@MaximilianGerhardt It seems that the issue was with TX 5V voltage. I've bought some resistors, added a voltage divider and it works fine. Will answer my own question with updated schematic soon

The issue, as Maximilian Gergardt suggested in comments, was with Arduino's TX/RX sending 5V signal. Adding voltage dividers on RX line solved the issue. Refer to diagram below for details:


text:
Unable to send SMS from interrupt routine
I am trying to develop a burglar alert system. I am using PIR sensor, Arduino Mega and SIM800L. I have connected PIR sensor to interrupt pin. Whenever motion is dected, a function corresponding to the interrupt will be called. In that function I am sending a SMS to notify with an alert message. If motion is detected 2 times, I will call the emergency contact number.
This is the code I have written.
#include <SoftwareSerial.h>
#define PIR1 2
#define SIREN 13
#define statusLED 12

SoftwareSerial SMS(11, 10);// rx(11-arduino) connect to tx(gsm module)
                         // tx(10-arduino) connect to rx(gsm module)

String CONTACT1 = "xxxxxxxxxx";  //mobile number

boolean status;
byte motionCtr = 0;
unsigned long latestMovementTime = 0;

void setup() {
  pinMode(PIR1,INPUT);
  pinMode(SIREN,OUTPUT);
  pinMode(statusLED,OUTPUT);

  Serial.begin(9600);
  SMS.begin(9600);
  SMS.println("AT+CNMI=2,2,0,0,0");

  delay(5000);
  activateSystem(0);
}

void loop() {
  unsigned long currentTime = millis();
  //If motion is not dected for 5 minutes, turn off the siren.
  if(currentTime - latestMovementTime > 300000 && motionCtr>=1){
    stopSiren(0);
  }
  delay(500);
}

void activateSystem(byte manual){
  delay(60000); //warm up time for PIR sensor
  attachInterrupt(0,motionDetected,RISING);

  status = true;
  digitalWrite(statusLED,HIGH);

  if(manual){
    Serial.println("System ACTIVATED by SMS.");
    notifyBySMS("System ACTIVATED SMS.");
  }else{
    Serial.println("System ACTIVATED.");
    notifyBySMS("System ACTIVATED.");
  }
}

void deactivateSystem(byte manual){
  detachInterrupt(0);

  status = false;
  digitalWrite(statusLED,LOW);

  if(manual){
    Serial.println("System DEACTIVATED by SMS.");
    notifyBySMS("System DEACTIVATED SMS.");
  }else{
    Serial.println("System DEACTIVATED.");
    notifyBySMS("System DEACTIVATED.");
  }
}

void motionDetected(){
  startSiren("Motion at bedroom door.");
}

void startSiren(String msg){
  //Record the time of latest motion dected.
  latestMovementTime = millis();

  motionCtr++;
  Serial.print("Ctr="+motionCtr);
  Serial.println(msg);
  notifyBySMS(msg);

  //Start the siren only if motion is detected 2 times
  if(motionCtr==2){
    digitalWrite(SIREN,HIGH);
    Serial.println("Siren STARTED.");
    notifyBySMS("Siren STARTED.");
    call(CONTACT1);
//    call(CONTACT2);
//    call(CONTACT3);
  }
}

void stopSiren(byte manual){
  motionCtr = 0;
  Serial.println("Ctr="+motionCtr);
  digitalWrite(SIREN,LOW);
  if(manual){
    Serial.println("Siren STOPPED manually.");
    notifyBySMS("Siren STOPPED manually.");
  }else{
    Serial.println("Siren STOPPED");
    notifyBySMS("Siren STOPPED.");
  }
}

void sendSMS(String mobileNumber, String msg){
  Serial.println("Sending SMS to "+mobileNumber);
  //AT command for text mode of gsm module
  SMS.println("AT+CMGF=1");
  delay(100);
  SMS.println("AT+CMGS=\""+mobileNumber+"\"\r");
  delay(100);
  // the text you want to send
  SMS.println(msg);
  delay(100);
  // ASCII code of CTRL+Z
  SMS.println((char)26);
  delay(5000);
  Serial.println("SMS sent to "+mobileNumber);
}

void call(String mobileNumber){
  Serial.println("Calling..."+mobileNumber);
  SMS.println("AT+CMGF=0"); //AT command for PDU mode of gsm module
  SMS.println("ATD"+mobileNumber+";");
  delay(45000);
  SMS.println("ATH");
}

void notifyBySMS(String msg){
  sendSMS(CONTACT1,msg);
  delay(1000);
//  sendSMS(CONTACT2,msg);
//  delay(1000);
//  sendSMS(CONTACT3,msg);
//  delay(1000);
}

I am receiving the SMS from setup(). But I am not receiving the SMS that I have sent from interrupt routine. Also I am receiving the call only sometime, it is random. I guess this is because I am using delay() in interrupt routine.
How can I implement such logic without delay().

Never use Serial in an interrupt!

Serial and delay() both require interrupts in order to work right, but within an ISR, interrupts are already disabled.

Have the interrupt set a flag (boolean variable). Then in the loop, check that flag, do your actions and reset the flag. Using delay, serial, and softwareserial inside the ISR is not adviced.

As mentioned in the comments Serial won't work in an ISR. Generally, you should do as little as possible in an ISR. Often an ISR will just set a flag to be handled in loop()
You will then need to refactor loop() to handle the flag set in the ISR. A common method is to use a finite state machine.

don't forget to declare the flag volatile!


text:
Output voltage of PIR sensor

Case 1
I am measuring output voltage of PIR sensor, I am getting 3.3v
Case 2
I have connected a resistor and a led to output of PIR sensor. Now when I measure voltage at the output pin of the sensor, I am getting 2.04v only.
In case 2 as the output voltage is dropped, it is not able to trigger a high state to arduino pin.
Where am I going wrong? What shall I change?

I believe you have to remember that the LED itself has a voltage drop of about 1.7V, so 3.3 - 1.7 = @1.6V.  Plus the voltage drop over your resistor depending upon the size it is.  So that voltage drop should be expected.

The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.
Either increase the resistor value, and accept that the led is less bright.
Or use a transistor to drive the led.
Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR


text:
Is there any problem in running Arduino logic to 12V LEDs?
I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
12V voltage-out (from converter 2) to LED strip voltage-in.
12V ground (from converter 2) to Arduino ground and LED strip ground.
Arduino data pin to LED strip data pin.

WS2811 are (usually) 5V LEDs. What LED strip exactly is it you intend to use?

@Majenko Hmm strange! It's these: https://www.electrokit.com/en/product/rgb-led-slinga-20x-o30mm-2/

Ah right, not quite what I was expecting. Those are separate LED and driver chip arrangements, not the combined driver chip + LED SMD type you normally see. No problem.

The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

Provide +12V and GND to the chain of LEDs from a 12V power supply
Connect the data line to an Arduino
Connect the GND connection to the Arduino as well.

Nothing more is needed.

Great! Thank you! As a beginner I was a bit worried about damaging the Arduino.

@Anna It's a common worry. As long as the 12V doesn't get connected to the Arduino it's fine.


text:
How can I make a power button for my project powered by a USB powerbank?
I've solved the battery power supply issue for my Arduino project by simply connecting a USB powerbank. However, I just realised that I can't come up with a good way to add an on/off button! There doesn't seem to be a way to turn the Arduino off using software. My second solution would be to cut up the USB cable (or an extension chord) and solder a switch onto the 5V wire.
Is there a more convenient solution that I'm missing?

You could put the microcontroller into sleep-mode. Then use a button (connected to one of the interrupt pins) to wake it up.
But depending on what Arduino board you are using, and what other sensors etc you've connected to the board, this might not save that much current. For example on the UNO board the usb-to-serial converter is always on, so while your MCU is sleeping and trying to save power, the usb-to-serial continues to draw current.
But adding a switch to a usb-cable would be a lot simpler.
PS doesn't the powerbank have an on-off switch?


text:
Pull more than 250 mA from powerbank-powered Teensy 3.6
I'm using a powerbank speced 5V at 2.4A to power my Teensy 3.6 via the USB port. However, Teensy recommends to not pull more than 250 mA from its 3.3V pin.
Is there any way I can pull more current, at either 3.3V or 5V, without splicing the USB cable? I will use it to control WS2812(b?) LEDs.

you can use the Teensy to control the LEDs ... but you cannot use the Teensy to power the LEDs

That makes sense, thank you @jsotola. Do you have any suggestion on how to power the LEDs from the powerbank that I'm powering the Teensy with?

The Teensy 3.6 breaks out the USB input power on the VUSB pin (labeled on on the back).
This is the raw 5V in from the USB connector before it feeds the 3.3V voltage regulator.
See the schematics at the bottom of this page

Thank you, I'll look into that pin!


text:
MPU-9250 IMU on SPI, external sensor or magnetometer using I2C master
I'm trying (for sport...) to use an MPU-9250 in SPI mode as it should be faster, and wasn't able to talk to the embedded magnetometer in my code.
I've gone through the documentation (RM-MPU-9250A-00 v1.4) which is a bit spartan on that subject but gives the rough idea, it should work by enabling the built-in I2C master feature and using "proxy" I2C registers; I've tried to "do as it says" to communicate with the magnetometer; I'm querying the magnetometer identification register, and I only see 0x00 in there.
I searched in nature, and couldn't find an example of F/LOSS software using an external sensor plugged on the MPU.
Perhaps I've done something wrong but I can't see it, so here's a bottle in the ocean :)

Why would you need to enable I2C master if you want to use SPI?  That just seems wrong, like the author of the doc was having a bad day.  Can you search around and see if there is any other evidence that this is the right thing to do,

The IMU chip can act as an I2C master to talk to downstream I2C devices...

It turns out that my mistake was in the SPI communication code, but nevertheless here is some info because it's not very obvious.
I went over the top and:

Review the electrical interface to see whether by any chance, my chip was badly hooked-up. Everything was fine.
Enabled register read-back and saw that... owww, it was bad.
Reviewing PS-MPU-9250A-01 § 7.5 SPI Interface I saw that I had made a stupid copy&paste error in my code... when copying my read code over to the write I forgot to adjust the MSB of the first spi byte.

Then:

I2C_MST_P_NSR=1 seems important or we get zeros
basic config in there, currently using the I2C proxy to read the magnetometer, and I don't like having a sleep to wait for I2C transfers to happen or not, but this is a WIP and the code won't go anywhere.

accept your onwn answer


text:
A minor confusion in digitalWrite command
Will the Arduino IDE interpret digitalWrite(13,x), where x>0, as digitalWrite(13,HIGH)?
And will it interpret digitalWrite(13,x), where x<=0, as digitalWrite(13,LOW)?

0 is low, everything else is HIGH

but some joker could make an arduino core where LOW is defined as 2. the AVR code for digitalWrite and digitalRead would work. it doesn't assume that LOW is 0. so your code shouldn't do that either. (but in my sketches I often assume that LOW is 0).

the esp8266 core digitalRead and digitalWrite functions ignore LOW and HIGH  and use if (val) and return the state of the register bit

Every other value than 0 or LOW will result in setting the pin to HIGH. In the following I explain why:
The function digitalWrite() can be seen in the file hardware/arduino/avr/cores/arduino/wiring_digital.c. The important lines here are:
if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

As you can see, it checks, if the given value (from the parameter) is equal to LOW and if so will set the corresponding pin to 0. In every other case it will set the pin to 1. The definition of LOW can be found in arduino/hardware/arduino/avr/cores/arduino/Arduino.h:
#define HIGH 0x1
#define LOW  0x0

So the code checks, if the value is equal to 0 and sets the pin also to 0. Every other value will result in a 1 (meaning HIGH). Also have a look at the definition of digitalWrite():
void digitalWrite(uint8_t pin, uint8_t val)

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.

Just nitpicking: Also False and anything other, which evaluates as 0, works here :) (And it is common to use boolean variables/expression as the val)


text:
How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor?
Im using the SparkFun MAG3110 3D sensor:
https://www.sparkfun.com/products/12670
My application is essentially to make a contactless "magnetic joystick" using a local magnet for accurate and constant 3D position sensing in x, y, x planes of a local magnet, exactly like in this video (skip to 1:06):
https://www.youtube.com/watch?v=CO6y6bjFfmY
The magnet I'm using is constant, so i'm trying to figure out a way to remove the earths magnetic field noise around the sensor so it cannot interfere with the sensors readings as if the earths magnetic field was virtually not present.
I've already written code that takes about 50 samples in each plane (x,y,z) and takes the average of each of the planes and outputs those readings minus the average offset values (Ex: Serial.print(x-xavg), Serial.print(y-yavg), Serial.print(z-zavg)). I did this to basically "zero out" the earths magnetic field, like zeroing a weight scale.
That wasn't really effective and results were not anywhere near constant after introducing and removing the local magnet, over and over again.
I've considered:

a low pass filter
sensor fusion using my gyroscope/accelerometer module
(I know that sensor fusion is usually used to calibrate the Magnometer to be a more accurate compass, but is there anyway to use this technique to  eliminate the earths magnetic field?)
using data from http://www.magnetic-declination.com/ to tie into my calculations to offset the readings
Using an electromagnet module to output the earths magnetic field inverted continuously in an attempt to cancel out the earths magnetic field
trying to find a whole new sensor completely that does not have a low enough sensitivity to even detect earths magnetic field

So my questions are:

Is there any way to do this?
Are any of my considerations practical or possible?
Are there even any 3d magnetic sensors on the market that do NOT pick up the earths magnetic field? - I've contacted SparkFun, Arrow, ST, and other companies about this exact question and never really get a sure answer on this question specifically?
if not, how was this man in the video able to reduce noise around his sensor? - He shows visually that his sensor is starting to filter out noise, saying that he's using an "adaptive averages" algorithm and links to some code, but I was unable to see/find that and don't understand how he is doing that?

One option is a magnetic gradiometer.  This consists of two magnetometers, which are placed at different distances from the local magnet (one close, one far).  You subtract the readings to eliminate dependence on the earth's magnetic field, on the (fairly good) assumption that the earth's field does not change over the distance between the sensors.

Earth magnetic field is pretty constant. In your measurements it will show up as an offset that you could subtract, but of course it will change if the sensor rotates.
Whatever measurement noise you see certainly doesnt' come from Earth. Either your setup is close to a local source of magnetic radiation (inductors, wires with high alternating current), or your sensor picks up noise from its power supply. Put your sensor away from high currents, power it with batteries and see how much noise you'll get in that case.

This can also be used for calculations if you wanted to be precise as much as possible. Magnetic Field Calculator

If you're already subtracting the mean of several samples of the ambient field, what's left should be noise, and much lower than your signal (the field due to your handheld magnet).
If you're trying to get a level of precision at the same order of magnitude as the noise, you'll need a larger 'N' (sample size), perhaps of both the ambient and of the desired signal, or apply even more stringent statistical techniques.
But I doubt that's what the experimenter in the video was doing. It's more likely he was close enough the sensor and with a strong enough magnet, that the noise was insignificant by comparison. He was using a rare-earth magnet - are you? Those typically have a stronger field that a more common ceramic or steel one. If not, you may need to use yours at a smaller distance from the sensor to get a similar signal to noise ratio.


text:
Using same pins number in different arduino?
I'm new beginner in programming arduino, and I want ask a question about arduino code, this is the problem " i used two arduino to build a robot, but i don't know how to set the code that for two arduino uno that pins in first arduino i used them all and now i wanna use the pins in second arduino, and how write code for the second arduino, which it is the same pin number i used  in first arduino, how to creat a code? thanks a lot guys for answer my question... (sorry for my bad english)...

Do both Arduinos run the same sketch, but with different pins? If the sketches are different there is no problem. If the sketches are the same, #define ARDUINONUMBER 1 and #if ARDUINONUMBER == 1, #else, and #endif can make the pin numbers change by changing just the #define statement. If that isn't the problem, please explain more.

I also do not fully understand the question.
If the 2 arduinos run independently, there should be no problem?
If you are saying you want 1 Arduino to be the MAIN ONE.. but you have run out of pins.. and want to add another Arduino (to have more I/O pins).. but have the MAIN ARDUINO still 'control' the second Arduino.. then you'd need to set up a way for the MAIN Arduino to communicate with the SECONDARY Arduino.
I suggest using Serial Comm (Software Serial) to do so.

this is simple problem, I have two arduinos, 1st arduino all pins is connected to their functions, now i have the second arduino, in 2nd arduino i wanna use the pins for other function, both arduinos is in same sketch, how to write the code for the both arduinos, how do i connect between them? (thanks for respons my question before, sir)

You want two Arduinos, running the same sketch, to use the same pins for different purposes? How will that work? Why do you want to do that? Is this an X-Y problem?

You could look at GPIO expanders like the MCP23017, cheaper and easier than a second Arduino.

The notion that “both Arduinos are in the same sketch” is slightly off.  Each of the Arduinos will contain a program; their programs might be identical if you do some fancy programming, but it is simpler to write one sketch per Arduino.
Thus, your first Arduino will run a sketch designed to control the devices it is connected to, and your second Arduino will run a sketch designed to control the devices that it's connected to.  Conceivably, you might have some devices that both Arduinos connect to.
Calling the two sketches S1 and S2, the device on pin number n as referred to in S1 will typically be a different device than the one on pin number n as referred to in S2.  Most but not all of the pin usage assignments for each pin number will be different in one sketch versus the other.
It's likely the two Arduinos will need to communicate with each other.  For a range of methods, see for example  How to have an Arduino communicate with 3 other Arduinos.  For additional detail see Arduino-to-Arduino serial communication and How to network many Arduinos with sensors using I2C.
If you decide to use I2C, then also see MasterWriter Tutorial and Wire Library webpages at arduino.cc.

To expand on my comment, if you begin your sketch with conditional definitions, you can compile it for different sets of pin assignments just by changing the #define ARDUINONUMBER xxx statement:
#define ARDUINONUMBER 1

#if ARDUINONUMBER == 1
#define FRONTMOTORPIN 7
#define REARMOTORPIN  8

#elif ARDUINONUMBER == 2
#define FRONTMOTORPIN 12
#define REARMOTORPIN  13

#else
#error Board number must be 1 or 2.
#endif

void setup(void)
{
   pinMode(FRONTMOTORPIN, OUTPUT);
   pinMode(REARMOTORPIN, OUTPUT);
   ; // etc
}

void loop(void)
{
   ;
}


text:
My Digispark board won't show up in Ports tab in Arduino IDE (OSX)
I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:
"Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.
Atmel 1624 tiny85

I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".
Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.
See:
http://digistump.com/wiki/digispark/tutorials/connecting
You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.


text:
How to set counter for two ultrasonic sensors?
This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

Are you asking how to measure the elapsed time between two events?

Yes. Elasped time between the condition when both the echo pins are high.

Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.
This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.
#define echo1 3 // Set your echo pins here
#define echo2 4

unsigned long startTime = 0;
unsigned long endTime = 0;

void setup() {
}

void loop() {
    // You can do stuff here

    // If the first sensor goes off
    if (digitalRead(echo1) && (0==startTime))
    {
        // Remember the time this happened
        startTime = millis();
    }
    // If the second sensor goes off
    if (digitalRead(echo2) && (0==endTime))
    {
        // Remember the time this happened
        endTime = millis();
    }

    // If we have both start and end times
    if (0 != startTime && 0 != endTime)
    {
        unsigned long duration = endTime - startTime;
        // Do what you want with "duration"
    }

}

It seems to work. But here the problem is the range of ultrasonic sensor. The sensor can detect the object even up to 300-400 cm so here the sensor cannot work in narrow road as it will detect the objects across the road too and the echo pin will never be at LOW state,if I am not wrong.

Well, that's a different question.  Please post one question at a time.  It would be worth reading how to ask a good question and then posting a new question.  Please consider accepting the answer if it answers the question you asked.

I tried coding according to your given code but the above problem arose so I thought commenting here,if you might have any answer for that.


text:
Every loop other case
I need to achieve that in every loop my Arduino do other thing. Say in first loop do one thing, in second do second thing and in third loop do third thing. And again. And while doing one thing, other things are dead.
Not sure what approach to use.
This is just my 50 cents:
for(int x=0; x<2; x++)
  {
  switch (x) {
    case 0:
      //do something
      break;
    case 1:
      //do something
      break;
    case 2:
      //do something
      break;
  }
  delay(1);
}

I tried this from above but it stuck at case 0
Any point or link to explanation would be nice.

how do you know, "it is stuck in case 0"?

It don't do case 1. And it should.

The question was how you know that.  This question will probably not be answerable until you post actual code which causes the problem.

In your code the for loop is wrong: if you want to reach case 2, you need x <= 2; or x < 3 in the for. Then this code should in general work. You can also make a global variabe for the "step" you're currently in only write the switch part in the loop followed by step++;

Either the case 0 code is stuck in a loop or it exits abnormally.

The code i provide is just a guess. The main question is how to set that in each loop my Arduino do different thing.

Sorry, but it's not clear from either your words or your "guess" code what exactly you are trying to do.  The principle problem is the word "loop" - a loop is either infinite or has some terminating condition(s).  You mention doing a series of things, so you'll need to be specific about until what condition you want to do each before moving on.  And then be specific if the overall sequence should repeat.  Also, the need to let the Arduino-language loop() run repeatedly vs. only once per complete sequence is governed by things like intervening event methods it is unclear if you will use.

Your implementation is in principle correct. However, tradionally, you don't incrementally loop over all states from 0 to end using a for loop. The implementation is more flexible if it allows the state to go to any other state if it needs to. This would be a normal finite state machine (FSM).
#include <Arduino.h>
/* How many states are possible? */
#define MAX_STATES 2
/* global state variable */
int currentState = 0;

/* prototypes */
void Action1();
void Action2();

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

void AdvanceStateByOne() {
    currentState = (currentState + 1) % MAX_STATES;
}

void loop() {
    //Execute the action dictated by the current state
    switch(currentState) {
        case 0:
            Action1();
            break;
        case 1:
            Action2();
            break;
        default: //Catch for un-implemented states
            break;
    }
    //Go to next state, incrementally.
    //This could also be modified in one of the functions above
    //Loop back to zero state after MAX_STATES using modulo operator
    AdvanceStateByOne();

    //for testing, introduce some delay
    delay(1000);
}

void Action1() {
    Serial.println("Action 1");
}

void Action2() {
    Serial.println("Action 2");
}

This prints out "Action 1" and "Action 2" in a loop forever.
Now you could take this further and instead of using pure numbers for your states, you can use an enum representation of those to make the code clearer:
enum state_t {
    STATE_DO_ACTION_1 = 0,
    STATE_DO_ACTION_2,
    STATES_END
} ;

And then act on those accordingly. You can also use the C++ feature of a enum class to give you a nice notation like State::SomeState1.

for(int x=0; x<2; x++)
  {
  switch (x) {
    case 0:
      //do something
      break;
    case 1:
      //do something
      break;
    case 2:
      //do something
      break;
  }
  delay(1);
}

You will never do case 2, that's for sure, as you are incrementing to less than 2.


text:
Steppers only vibrate, not rotate with I2C
The goal of my project is to be able to control two steppers with 4 buttons. Steppers are connected to Adafruit Motor shield(the older one) which is stacked on Arduino UNO, buttons are connected to Arduino NANO. I'm using I2C between the two Arduinos. However, if I push a button, the steppers won't rotate, only vibrate, but if I'm using only Arduino UNO with the motor shield stacked on it, button connected directly to the motor shield, it's working well.
Arduino UNO is Master Reader, while NANO is Slave Writer. There is a fritzing image of the circuit.
I don't know where's the problem, if it's in the circuit, if it's because of my battery(i bought it like 10 minutes ago) or the code. Any help is apreciated.
Master code:
#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 2);
AF_Stepper motor2(48, 1);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave code:
#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 8;
const int button4 = 7;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}

int are 2 bytes, but Wire.write() transmits only a byte at a time.

have you ran any test code on the Arduino Uno to make sure that the motors are connected correctly?

@jsotola yes, they work if I don't use I2C.

Don't you know the solution for that? @jose can u c

In both master and slave, you have x and y declared in the broadest scope possible. Different devices, shouldn't matter. But x and y usual mean coordinates, which is not what you are trying to say - properly named variables help with understanding and maintenance.
I think your biggest issue, and one that confuses your attempts to debug, is the underlying logic.

You have 4 independent buttons, but prioritise one button over the
other. What happens if both buttons are pressed together?
You have 2 independent motors but prioritise one after the other.
Your slave uses repeating code.
You use your slave as both a writer and  decider. In this case, your
writer is making the decisions over which motor to move and which
direction.
Your master only makes one move at a time - but you have two motors and 4 buttons, so you should be able to move both motors in one loop.
Your handler expects the number of bytes to be read but you don't use that to control your reading.
Your consecutive reading does not differentiate on where the data comes from. x could be filled with any of the button presses, and so could y.
If the event handler is doing the work, why have a blocking delay in the code?

Effectively, you are taking a random read and expecting the device to do something deterministic. Hence your jittering.
To help you debug your device, you can first clean up your code.

reconfigure your slave to send a single response each loop. You only need 4 bits, where each bit represents whether buttons 1-4 are pressed. Only 1 variable to be written.
Use your master to decipher the input. This is where you can put the safety in (e.g. if both 1&2 are pressed/HIGH then ignore). This also reduces the possibility that your code is sending a forward then backwards signal.
Use your master to determine how many bytes have to be read and use this properly.

You will find your code cleaner, easier to read and easier to debug. Perhaps you will also see a way to directly slave the NANO to the UNO without i2C in the middle, simplifying your set up even more.
EDIT (additional information):

You can use the built in functions (see Arduino function reference under "Bits and Bytes") such as BitWrite/BitSet/BitClear and BitRead to set/clear the relevant bits on the variable you create (e.g. Byte ButtonStates). Note the use of Byte instead of Int
You can then use the slave to write the information and the master to read the information (Wire.write and Wire.read), you then know that each byte is complete and reflects what you intend.

Wow, you're pretty skilled in this area. This is a pretty great advice, however the problem is that I can't do the steps you mentioned alone.
How is "reconfigure your slave to send a single response each loop. You only need 4 bits, where each bit represents whether buttons 1-4 are pressed. Only 1 variable to be written." possible? I'll try my best and thanks for the answer! @AJD

@RóbertPollák: answer updated to help you a little bit more.


text:
Servo motor with 9V battery
I'm using servo motor in my Arduino based project, I've tried to provide servo with external power supply, So I've used 9v battery with IC7805 to step down to 5v,  but the motor is not working, so what should I do? FYI: I used the same battery with IC7805 to power IR proximity sensor which works fine.

A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.
Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.
Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.
A 7805 has a high dropout voltage and is out of place in a battery powered system.

What do you use instead of 7805 when power is needed ? Do you have a link ?


text:
Motor shields in arduino
what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?

Servos require power and PWM. Servo shields come in two main forms:

Simple distribution
Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.
The second kind, more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.
Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.

The dumb ones are basically distributors of power for the servo motors.
There are more clever boards that offer the control of multiple servos (usually 10+) by communicating with the Arduino via some higher-than-PWM-level control (Like I2C) thus taking less pins from the Arduino than a dumb servo shield.
Both kinds usually require a power supply to power the servos.
G.

He said "servo motor shield", not a DC motor driving shield. Very different thing.

do you mean that using motor shields provides external power to servo?

@Majenko How does my answer suggest I am talking about a DC motor shield? Would you please elaborate?

"So, you need something that takes the signal from these pins and translate them into high current controls." - that is what a DC motor shield does. It's not what a servo motor shield does. You have perfectly described a H-bridge shield.

@Dharanendiran Almost. A motor shield provides power to the servo/stepper motor but that power has to tome from somewhere, so to make a motor shield work you'll need a power supply to power the shield itself and you may need another power supply to power your Arduino.

@Majenko It is what ALL motor shields do, that's why you need them: to be able to handle high currents. (higher than what the Arduino pins can handle) What you hook up to the other end of the shield is not specified in that sentence, it can be a stepper motor or a servo motor or a DC motor.

@KillerRabbitofCaerbannog Do you actually know how a servo motor works, and what signals it requires?

Yes I do, and let me Google it: http://www.jameco.com/jameco/workshop/howitworks/how-servo-motors-work.html
Sorry, sent it a bit early, I'll elaborate

Ok, so if you know how a servo motor works - tell me: what signal(s) would you possibly want to amplify using a H-bridge?

I see why you think I was talking about DC motors. Most servos contain their electronics, so you only need high current DC supply for them and a signal with PWM. A servo shield gives it power and takes the incoming signal and sends it to the motor. (or even buffers it but that's another topic) I made a mistake with the amplifying thing as I did not state explicitly that you only amplify (or more like translate) signals with stepper motors.

You need a motor shield for stepper or DC motors. Not for servo motors. You can directly drive as many servo motors direct from an Arduino as there are PWM pins (and more if you implement software PWM). There is no need for any amplification or buffering unless you are using long runs of cable and need the extra current to get the signal there cleanly. Your answer doesn't mention a single thing that is relevant to servo motors, and the OP didn't ask about DC or stepper motors.

@Majenko You can directly CONTROL as many servo motors direct from an Arduino as there are PWM pins. You still need some kind of power distribution to the servos, and that's what a "servo motor shield" does. Also, as you said, you don't need a motor shield for servo motors. Then the author was maybe talking about "servo motor control". Or he/she did talk about "motor shield". I elaborated the latter extending it to stepper motors. I am sorry if my answer was ambiguous and hope that the author wanted to know about steppers too.

That is what one kind of servo motor shield does. Those are cheap and rare (and often just a part of another bigger shield). The most common kind of servo motor shield also contain a PWM chip (like I linked to in my answer) for generating more PWM signals than the Arduino can create. THAT is what a servo motor shield is for. The power distribution is just a bonus. It's just as easy to use wires to distribute the power.

You should remove all references to H-bridges, amplifying of signals, DC motor / stepper motor driving, etc from your answer as they are nothing to do with the question and are just plain misleading.

@Majenko "and often just a part of another bigger shield" And that's why I wandered into stepper territory. Most motor shields provide stepper, DC and servo control which makes it appropriate to talk about all of these motors hence the "amplifying" stuff in my answer. My error was not stating that, I'll correct my answer later today.

SOME DC motor shields also provide handy servo pins since you often want to use servos and DC motors together (drive & steering). However, a servo motor shield (which is what the OP asked about) NEVER has DC motor driving capability.

I understand how you find my answer misleading and I'll rewrite it to make sure it is not anymore.


text:
Weird probled with TFT LCD screen and DHT22 sensor
I'm doing a research project that uses three sensors (DHT22, HTU21D and TMP102) and two screens (a normal 16x2 LCD, and a TFT).
I connected all the sensors and the LCD in my Arduino Uno and everything works fine. However, when I connect the TFT, the TFT simply freezes and does nothing. I ran the example Arduino sketches for TFT and it works fine. I also did a bit of debugging and found that if I don't invoke the DHT22 sensor reading functions (i.e., dht.readTemperature()), the TFT screen works fine.
I also triple-checked the wiring and it doesn't seems that something is wrong.
Any ideas why this behaviour occurs? Thanks.

sounds like you need to configure the DHT to use a different GPIO

Similar problem have someone else here too: http://arduino.stackexchange.com/questions/34987/ultrasonic-sensors-with-12v-motors-will-not-work-adruino - there was some shared pins, so each device worked separately, but not both togeher. Changing the pins (GPIO) solved that.

Thank you, both. The problem was shared pins between the components. Now, I must figure out how to extend the outputs pins on Arduino!

To get more pins on an Arduino, look at the MCP23008 port expander.


text:
Small Arduino with Bluetooth HID interface
I am trying to create a bluetooth gamepad for my phone.
I saw this:
https://www.amazon.com/DFRobot-Beetle-BLE-Arduino-Bluetooth/dp/B014KQHEH6/ref=cm_cr_arp_d_product_top?ie=UTF8
It says its bluetooth HID, but there are some conflicting comments saying it is serial over bluetooth. Is there something similar in a small form factor with an hid bluetooth module that I can use?

schematic ... https://github.com/Arduinolibrary/DFRobot_Bluno_Bettle/blob/master/DFR0339-Bluno%20beetle%20V1.0.pdf?raw=true .......... uses the cc2540 .... http://www.ti.com/product/cc2540   .... that might tell you what it actually is

Based on the fact that the controller you mentioned has a TI CC2540 Bluetooth processor, I have found a few webpages with information about HID capabilities in the CC2540. Based this the CC2540 should support HID.
Some example code.
Question on the TI forums, with a link to example code.


text:
How long does it take for a servo to change rotation?
I have an Arduino Uno and a Micro Servo 9g A0090 servo.
Given that Servo.read() simply returns the last value written to the servo I guess there is no way to query a servo's actual position.
If I can't query the servo, how do I know that the servo rotated to the position of my last write() call?
Rotating from 0 to 180 will take longer than rotating from 0 to 10. How do people normally handle this scenario? Perhaps I just time how long it takes to go from 0 to 180 and then always call delay() afterward to give the servo time to complete its rotation?

Normal servos don't provide any feedback. Their speed depends on the servo's specs and the load.
You could measure the time it takes to rotate a certain angle and use that to calculate the time, then add some safety margin. But if the load isn't constant, the times will be off.
You could change the position slowly, but that still doesn't guarantee that the servo will do what you told it to.
If you want to know servos's position, you need a servo that outputs it. There are servos that expose the signal from their internal potentiometer.

Adafruit sells them and has a useful guide about them.
You can also modify a normal servo yourself, by attaching a feedback wire to the potentiometer's wiper pin.

I can imagine several ways how to do it:

You can wait some specific time. How long it takes to rotate from 0 to 180. But it'll wait for much longer for small angles than it's necessary.
Better aproach would be to compute delay based on angle (maybe even on servo power supply voltage)
Another way would be measuring servo's power supply current.
You can use some rotary encoder. But some extra gears might be needed to be able to detect position fine enough.
You can "hack" into the servo's electronic and get the position - it's usually voltage divider (potentiometer). But it might introduce some extra interferences and servo might be fuzzy or unstable...

For 9g servo .10 sec for 60 degree rotation.
For mg995 .18 to .19 sec for 60 degree rotation.
For servo 3003 0.19 to 0.20 or 60 degree rotation.
You can check specification for other servos. I gave for common servos above.
Hope this help.


text:
State change in Arduino Using Adafruit display
if(menustate == 1310){menustate ++;Serial.println("Execution:");Serial.println(menustate);}
             if(menustate == 1311){menustate ++;if (hr==0) menustate ++;else{aCount++;gpArray[aCount]=hr;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1312){menustate ++;if (minu==0) menustate ++;else{aCount++;gpArray[aCount]=minu;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1313){menustate ++;if (seco==0) menustate ++;else{aCount++;gpArray[aCount]=seco;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1314){menustate ++;if (dates==0) menustate ++;else{aCount++;gpArray[aCount]=dates;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1315){menustate ++;if (months==0) menustate ++;else{aCount++;gpArray[aCount]=years;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1316){menustate ++;if (years==0) menustate ++;else{aCount++;gpArray[aCount]=years;}}
             if(menustate == 1320){menustate ++;}

I am trying to get different time inputs from users by using the menustate value , but here in this code the menustate starts from 1311 and without pressing anything the state goes directly to 1320 .and i cant get to the inbetween states

You should use a switch statement ... than after the switch statement you get the in between states:
// conditional loop
{

    // prepare for switch (if something is needed)

    switch (menustate)
    {
        case 1310:
            menustate ++;
            Serial.println("Execution:");Serial.println(menustate);
            break;
        case 1311:
            menustate ++;
            if (hr==0)
                 menustate ++;
            else
            {
                aCount++;
                gpArray[aCount]=hr;
            }
            Serial.println("Execution GP:");Serial.println(menustate);
        break;

        case 1312:
            // ...

        default:
            // You can do here things with all other values
    }

    // Here you have the in between states available
}

You should put this switch statement in some conditional loop (like until an end state is reached.

authors: Артем Вефелев