text:
ISR vs state change detection on button
Hi I was wondering if a digitalRead state change detection could be saved in a variable like counter++, just like you can do with an interrupt function.
arent these two operations almost the same?
like have an external circuit with a  reed closed by a magnet, to take the place of a momentary push button,

The 2 techniques described in the question are commonly referred to as "polling" and "interrupt".  Either will work.  Polling is suggested for beginner programmers and when time is not important. Such as scanning an array of human controlled buttons. Whereas interrupts are usually reserved for when time is of the essence.  Such as synchronizing a camera's release switch with a strobe flash.
Also, consider polling as a simple to understand, easy to test sequence of events that will always happen in the expected order.  While interrupts can happen at any time and all interruptible code has to be written to tolerate being interrupted.
Often, debouncing is the more difficult problem when combining mechanical switches and microprocessors.  A good fundamental exercise is to write your own debounce program.  However, an Arduino debounce library is already available.

The fundamental difference between polling (digitalRead()) and interrupts is that of time. Yes, I know we discussed time and interrupts at length in another of your questions, but I'm not talking about recording time here.
With an interrupt you know (pretty much) when an input changed. With polling you can only know that it changed sometime in the past.  An interrupt occurs at the moment an input changes state (what that change is depends on the type of interrupt). That makes it possible for your program to remember that time (by querying millis() for example).
With digitalRead() the only way you can know if an input has changed state is if you manually remember what the old state was and compare it, so all you can know is that it's changed since last time you examined the input, and if those times are far apart all you can say is "sometime in the past X milliseconds it changed state".
If your input changes faster than that polling time you won't know about it. For instance, if you end up polling every 10 milliseconds, and you have a pulse on your input pin that lasts 4 milliseconds (that's an eternity in microcontroller time) but occurs part way between two polls (say from 3ms to 7ms) you'll never see it.
To put it more formally, to detect a signal of frequency f Hz you have to sample the input at minimum 2f Hz (or a period of 1/(2f) seconds. This is known as the Nyquist-Shannon theorem and applies equally to both digital and analog sampling (digital sampling is merely 1-bit analog sampling).
With interrupts, since you're not sampling based on periodic checks, but instead using a hardware trigger to detect an edge (rising, falling, or changing), and assuming you have interrupts enabled at the time an edge arrives on the pin (some code disables interrupts, and interrupts can't trigger while another interrupt routine is running), you instantly know about it regardless of whatever else you are doing.
Interrupts are said to be asynchronous, whilst polling is known as synchronous.
Which method you should choose depends on many factors: the speed of your signals (pulses from sensors, buttons pressed by humans, etc), what else your program is doing, how critical it is that you detect an input state change, etc.  For slow signals, like a button, polling is perfectly fine. For high speed signals, like a hall-effect sensor or a reed switch triggered by a bicycle wheel mounted magnet, interrupts are more suitable.
For some signals (especially things like revolution counters, frequency counters, etc) where you have a large number of brief pulses coming in over a period of time where all you want to do is count them, there are even better options than interrupts.
The internal timer peripherals of the chip can run in a number of modes that are designed just for this scenario.  You can run a timer with the clock source as an IO pin. That means that on each incoming pulse to that IO pin the timer counts up by one. That happens completely independently of your program. You just read the current count from the timer and reset it to 0 to start counting again at a period to suit you.
Another mode is Input Compare mode.  This combines normal interrupts with a timer. The timer runs in the background at a pre-defined rate, and as soon as a specific input changes state (each timer has specific inputs for this) the timer is frozen an interrupt is triggered.  This gives highly accurate time measurement of incoming signals since it's not subject to the time taken to service the interrupt. The timer is frozen immediately and you can query that time when the system is able to service the interrupt.
There is no native support in Arduino for either of those timer modes, though, so you would have to either find an advanced library that configures the timers in that way for you, or read and understand the datasheet and manually configure the timers in the right way.

so, for example, a state change, like a button toggle, is this an example of polling of the digital pin that is being read by digitalRead()? like, if a momentary button is pushed, its useless for a toggle, but if you scan the pin for a change, a HIGH or LOW, and save that change, then toggle off that change, (latch) is this is an example of polling?

Polling is merely the act of using digitalRead.

cool, so the MCU is polling when digitalRead is used, when there is a change, save the change, and thats the state change correct?

Polling means "tell me the state of the port right now". What you do with that information is up to you. By comparing two polled states you can find a change in state.

so whats the difference between a state change and state detection change? How does the MCU tell the difference?

"By comparing two polled states you can find a change in state" so digitalRead polls, then a change occurs, we can save with a variable, then compare with "if"?

I have no idea what a "state detection change" is.

state change detect means like a button press or release. its in the arduino sketch libary examples

A state change detection is what your sketch does with the information returned by successive polls.

static bool lastState = HIGH; bool state = digitalRead(3); if (state != lastState) { lastState = state; if (state == HIGH) { buttonReleased(); } else { buttonPressed(); }}

ive seen it coded allot simplier than that dude, but thats what Im studying

That's pretty much the simplest, however that detects both state changes (HIGH->LOW and LOW->HIGH). If it's only one you need then you don't need the ELSE.

yeah your right, sorry, thats pretty much the same code, just they had it different

a state change, then a state detection change

I still don't know what you mean by a "state detection change". That makes no sense at all. A change in the detection of a state...? How does that work? There's only state changes, and the detection of those changes of state.

The state changes are what you are looking for, and the "detection" is the method of finding them.

state change means a latch, not a momentary push, but the edge detection is the next change to look for, maybe used wrong word

A state change is a change in state. There are only two states that you can get from a digital pin - LOW and HIGH. Detecting those state changes doesn't give you a "latch", it only tells you when (and in what direction) the state changes.  What you do with that information (use it to toggle another "latch" variable, add one to a counter, whatever) is entirely up to you. All that side of things is encapsulated in the "buttonPressed()" and "buttonReleased()" functions in my example just now. Those functions do "whatever you want to do when a button is pressed".

like you want to toggle a button for 2 functions. just a button push does nothing but a glitch, so you got to have states. but you want to do the state change on a button push or release so use edge state detect

why are you using this function buttonReleased()? seems all you have to do is use if digitalRead(pinA) != state{ state = digitalRead(pinA); if (digitalRead(pinA)== HIGH ) { toggle another variable}

That function is a "placeholder". It means "I don't know what you want to do here, so I'll put something in to show where your code would go, and name it appropriately". It is not a function that exists. It is for you to replace with your own code to be run when the state changes in the appropriate way.

That code you replace it with could be "rev++" for example.

my logic is its like a ladder or steps, one condition depends on the previous one, and build from that, like the MCU is polling the pin, if there is a change, save it and build off of that. is that correct?

like if a newb like me is trying to advance from the LED on/off to a button toggle, we got to understand the logic first. and when I mean toggle I mean the LED stays on with one button push.

The LED toggle code is separate from the pin state change detection code. The LED toggle code is triggered by the pin state change detection code, though. "IF the pin has changed state AND that change is LOW->HIGH THEN toggle the LED"

instead of AND just use another nested "if"?

Yes, it has the same effect, with the added benefit of having a simpler "else" if you need it, and splitting out the state saving from the specific HIGH->LOW case.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
NodeMCU not responding AT after blink app
I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.
I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

the Blink program replaced the AT program

@Juraj How can I put it back?

download the AT firmware binary from Espressif site. On Windows you can use Espressif Flash Download Tool to flash it. On Linux use esptool.py. https://www.espressif.com/en/support/download/at?keys=&field_type_tid%5B%5D=14

Done, thanks! Can you add this as an answer, people who has the same problem may see it easier :)

If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from Espressif download page and flash it with the Espressif Flash Download Tool (Windows) or with esptool.py.

source: Stack Exchange

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

sort: votes


text:
"char inChar = (char)Serial.read();" why is the "char" in brackets? and what is it called
I am sure this is a very simple answer, but I don't know to look it up on google
In the example "SerialEvent" in the arduino IDE (v1.8.7), there is the following function
    void serialEvent() {
        while (Serial.available()) {
           // get the new byte:
           char inChar = (char)Serial.read();
           // add it to the inputString:
           inputString += inChar;
           // if the incoming character is a newline, set a flag so the main loop can
           // do something about it:
           if (inChar == '\n') {
               stringComplete = true;
           }
        }
     }

On the third line "char inChar = (char)Serial.read();" the (char) is given in brackets before the serial read.
Why is this? and more specifically how is called ?

This is actually more a C/C++ language question. The hint is "Please check the return value type for Serial.read()".

So it basically forces the value returned from serial.read() to be a char? Do you know how this is named, so I can look up the documentation?

In C, why are there parentheses around (int) in this example?, Type in parentheses in C variable definition

What topics can I ask about here? On topic: Specific questions about Arduino boards, code…  https://arduino.stackexchange.com/help/on-topic. Is this question not a specific question about Arduino code? Voting to not close.

@will.mendil This is called "Explicit type conversion" or "Casting". https://en.cppreference.com/w/cpp/language/explicit_cast. In some cases it ends up as some extra code but in other cases it is just a hint to the compiler and no extra code is generated.

@will.mendil Why is the explicit cast necessary above? What would happen if the statement was int inChar = Serial.read();? What would the statement inputString += inChar; mean if changing char inChar to int inChar.

It is called type casting and will convert one type to another. The return type of Serial.read() is int, because it will return -1, when you try to read without any bytes being available. The casting with (char) will drop the high byte of the (2-byte long) integer, leaving only the lower byte. This byte will contain the actual read data, in which you are interested here.
Casting is a complex thing, because there can be different ways to convert different types (for example maintaining the bit-content vs. maintaining the decimal value). The casting, that you are seeing here, should only be done, if you really know, what you are doing. The bits will not be changed to maintain the correct value, but the bit-content will be preserved, unless the new type is smaller than the former. In this case the rest is lost. Also, if you try to cast a float value to an int value with this, you will get a totally different decimal value out of it, because the numbers are encoded in the bits in a totally different way. Here it is known to be OK, especially, if you are checking for available bytes before reading with Serial.available(), because the library puts the ASCII data in the lower byte.
For further explanations you should consult C/C++ guides.

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


text:
Infinite Loop on Pin Input (Teensy 3.1)?
I have an infinite loop issue that keeps persisting in this code on my Teensy 3.1. This program is intended to take an input on Pin 0 and press the Enter key on the computer it is hooked into.
It is connected to a wire with no current but once a switch is flipped it should send a 5v Digital Signal blip to the Teensy and trigger it to run. It does function but it keeps getting caught in an infinite loop for some reason. Any help would be greatly appreciated!
// Global Variable
int signal_receiving_pin = 0;

void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT);
}

void loop()
{
// If statement to check whether an input has been received
if (digitalRead(signal_receiving_pin) == HIGH)
{
  // If the signal has been detected..
  Serial.println("The signal has been received \n");
  Serial.println("Now sending the ENTER signal \n");

  // .. The ENTER key is sent to the computer
  //Keyboard.press(KEY_ENTER);
  //Keyboard.release(KEY_ENTER);

  // Waiting 1 minute before allowing more input
  //delay(60000); // Pause
}
else
{
  // If the signal is not detected..
  // it will let you know it isn't there
  Serial.println("Input not detected \n");
}
}

Do you have a pulldown resistor?

Try using the internal Pullup/Pulldown resistor to control the input when the pin is not connected to anything.  If you do not have a pullup/pulldown, then the input capacitance on the input pin circuitry can sample and hold the 5V unreliably.
...
void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT_PULLDOWN);
}
...

You may want to uncomment the delay() or add some state logic trigger only one activation per each cycle of signal_receiving_pin

Just changing to INPUT_PULLDOWN solved my problem! Thank you good sir!

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


text:
Help with Serial.print()
How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?
Also, What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?
And please explain the difference with Serial.write()
Thanks!

is it your home work from school?

No how can that be a homework I was just just curious about serial communications. AND BTW I DONT DO homeworks

@Juraj i was reading this https://arduino.stackexchange.com/a/14405/41798 and was curious

you could look into the source code. class Print has all the print functions implemented using write function. HardwareSerial only implements write byte function, which adds a byte into TX buffer

Print is base class of the hierarchy Print <- Stream <- HardwareSerial

and in hierarchy Print <- Stream <- Client <- EthernetClient, the EthernetClient writes the byte into buffer for sending over network

if the TX buffer of Serial is full, the write function waits in a while loop until one byte can be added to buffer

Serial.print() feeds the data into the TX buffer one character at a time (through the Print class's inherited .write() function which HardwareSerial implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.
Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.
To put it in more detail:

When you call Serial.print() it's actually calling Print.print(), because Print is a parent class of the HardwareSerial class.
Print.print() repeatedly calls Print.write() for each character to print.
Print.write() is a pure virtual function (which means it's only got the definition in the Print class and child classes must implement it).
HardwareSerial.write() implements the Print.write() function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
Serial is an instance of the HardwareSerial class.

Serial.write() adds a byte to TX buffer

@Juraj Serial.print() is actually Print.print() which calls Print.write() which is a pure virtual function implemented by the HardwareSerial child class.

I didn't say something else


text:
variable doesnt have a type name
Why can't i assign the value to a variable  outside the function?
void setup(){}
int a;
a=12;   //  WHY IS THIS GIVING ME ERROR
void loop(){
}

Why the line a=12 gives me an error?
Thanks!

a=12;   //  WHY IS THIS GIVING ME ERROR

Because you can't do assignments like that outside of a function.
You can, though, create and assign the variable at the same time:
int a = 12;

That is a declaration of the variable, whereas
a = 12;

is a procedural statement. Procedural statements cannot be executed in the global scope. They can only be executed inside a function during the execution of the program (the global scope never gets executed).

But why cannt we do that ?

Because that is the syntax of C. "Ye canne change the laws of physics, cap'n"

Actually, the global scope is used for declaration and initialization. Execution is not needed. In C it is a rule that the first function that is executed is main. And the function main should call all other functions that will be called. Note that this function is 'hidden' (auto generated) by the toolchain. Other languages (like Python) can execute code within the global scope, but for C this has not been designed.

Is it just the syntax? or is there anything else behind that?

It's just the syntax. It's done that way so that the compiler can easily tell the difference between a piece of code that should be executed (a = 12) and a variable initialization (int a = 12). In the latter the "12" is stored elsewhere (in flash), and during the startup of your code that value (and other global variables) are copied into memory in the right places.


text:
Arduino Shield on Breadboard
I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.

no, but shields typically only use a portion of the pins, the rest are passed-through; this means a few dupont connectors can get a shield up and running; no need to connect "extra" pins" for the shield "top"

Chances are the offset headers won't allow the shield to directly plug into a breadboard.
As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

There was a Kickstarter project a few years ago to make just such an adapter. You might get in touch with the developer to find out whether he's made (or is planning) another run.

@Mazaryk is right.
Shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.


text:
Automatic subtle colour changing on ws2812b with arduino
I'm creating a wordclock and I'd like to change the ws2812b led strip color slowly, so that it fades from one colour to another. However, I'm new to arduino and I can't get it done and I also could not find anything on this anywhere (probably because of using the wrong keywords)
Currently I have a colour hardcoded like this:
void SwitchLED(int MyArray[], int n) {
     for (i = MyArray[0]; i < MyArray[0]+n; i++) {
          leds[i].setRGB((161,57,0);
     }
}

(The array in this code are the LEDs that will light up depending on the time I get from a ds3231).
So I would like a (random) starting colour to slowly change to another colour and so on. This in such a way that you will notice it only after a couple of minutes, so very slow and subtle.
I'm using the FastLED libary. I bit of help on this would be appreciated very much.

Something like leds[i].setHSV(millis()/1000, 255, 255);?

That's great, exactly what I needed. Thank you.

For the color, you can use the time (millis()) as a hue parameter.
void SwitchLED(int MyArray[], int n) {
    CRGB color = CHSV(millis()/1024, 255, 255);
    for (i = MyArray[0]; i < MyArray[0]+n; i++) {
        leds[i] = color;
    }
}

I used 1024 here to scale the time, so it takes 4 min 22 sec, to go through the hue cycle. And a power of two, should solve a visual glitch on millis() overflow.


text:
Run Code Based on Time From GSM Module (SIM900)
I am trying to check the time from the GSM module to let my code run or do nothing.
If I send the command, AT+CCLK? to the SIM900. This is the response:
AT+CCLK?

+CCLK: "17/02/14,16:58:25-20"

OK

How do I parse the time information from the SIM900 and setup a loop for my code to run if it is past 6pm but before 6am?
My code currently:
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7,8); //RX,TX

void setup() {
  PowerOn(); //power on GSM Module
  delay(10000); //delay 10 seconds
  SIM900.begin(19200); //software serial for GSM Shield
  delay(500);
}

void loop() {

// if time is past 6pm and before 6am send text message else do nothing

SendTextMessage();

}

///GetTime
void GetTime()
{
    SIM900.print("AT+CCLK?");
}

///SendTextMessage
void SendTextMessage()
{
    SIM900.print("AT+CMGF=1\r");//Because we want to send the SMS in text mode
    delay(100);
    SIM900.println("AT + CMGS = \"+12137777777\"");//send sms message, be careful need to add a country code before the cellphone number
    delay(100);
    SIM900.println("Motion Detected!");//the content of the message
    delay(100);
    SIM900.println((char)26);//the ASCII code of the ctrl+z is 26
    delay(100);
    SIM900.println();
}

///PowerOn
void PowerOn()
{
  ///software equivalent of pressing the GSM shield "power" button
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

I'm imagining SIM900 is a serial stream that supports input methods available() and read().  The hour portion of the response string is a two-digit integer delimited by a comma and a colon.  The following snippets of code assume you trigger a response and then start a listen() to connect to the software serial input.  Since listen() discards old data, presumably a message like +CCLK: "17/02/14,16:58:25-20" will be the next data to arrive.
This code converts any string of digits that it sees into a number.  Whenever it sees a non-digit character, it treats it as a delimiter.
When the previous and current delimiters are ',' and ':', it checks if the current number value is in the desired time range, and if so, it sets a flag, else clears a flag.
When the previous and current delimiters are '-' and '"', it assumes it is done with the parse.  Or one could, possibly, end the parse as soon as the hour field has been processed.
void loop() {
  // ...
  // somewhere within loop()
  byte num, dell;       // Currrent number and left delimiter
  byte timeFlag, readMore, foundTime;
  //...

  // Send string to elicit +CCLK and tell parser to handle response
  SIM900.listen();      // Discard old input
  SIM900.write("AT+CCLK?"); // Elicit new input
  readMore = true;
  timeFlag = foundTime = false;
  num = 0;
  dell = 0;
  // Read and parse +CCLK input; set or clear timeFlag
  while (readMore) {
    while (!SIM900.available()) {}; // Wait for a character
    char c = SIM900.read();
    if (c >= '0' && c <= '9') { // Is c a digit?
      num = 10*num + c-'0'; // Yes, add it to num
    } else {   // Not a digit, so check for Hour field or End of parse
      if (dell=='-' && c == '"') {
        readMore = false;
      } else
        if (dell==',' && c == ':') {
          timeFlag = (num < 6) || (num >= 18);
          foundTime = true;
        }
      dell = c;            // Record left delimiter of next number
      num = 0;             // Get ready to evaluate next number
    }
  }
  // If foundTime, then timeFlag is true for time in 6 PM to 6 AM, else false
  // ...
  // etc
}


text:
HC-05 Bluetooth Module Blinking Red Light-Arduino Uno
I have looked on google for an answer to my problems to no avail. The you tube video I am following is here: https://www.youtube.com/watch?v=f1v0IMegCvU
So basically on my android, I can't see the HC-05 device show up and the module itself is flashing red unlike the video's flashing blue light. I have connected the circuit exactly like he has in the video with the 2 10K resisters. I am using the same app. What is wrong? Here is my code as I copied from the video.
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.println("Connection Successful!");
}
void loop()
{
  if(Serial.available()>0){
    int data=Serial.read();
    switch(data){
      case 'a': LEDON();break;
      case 'b': LEDOFF();break;
      default : break;
    }
  }
  delay(50);
}
void LEDON(){
  Serial.println("Led On!");
  digitalWrite(13,HIGH);
}
void LEDOFF(){
  Serial.println("Led Off!");
  digitalWrite(13,LOW);
}

I also get the error avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 when connected through usb. I do not get any errors when just flashing the arduino without any wires connected to the arduino. I know that the port is correct. Any ideas would be helpful. Thanks.

You write “I do not get any errors when just flashing the arduino without any wires connected to the arduino”. Q1: By 'flashing' do you mean sending a sketch to the Arduino?  Q2: How does the sketch get to the Arduino if no wires are attached?    Q3: What else is connected to the Arduino when the USB doesn't sync?  Eg is the HC-05  connected?  Q4: Re  “I know that the port is correct”, what port do you mean?  Q5: In the IDE, what  board programmer or programming method do you have selected in the two cases? (Ie with or without USB connection)

Answers: Q1=No, I mean just not having anything connected to the arduino other than the usb cable and selecting upload. Q2 answered by Q1. Q3=ground, 5v, tx,rx and those goes to the circuit on the breadboard just like in the video. Q4=port 1 and is genuine arduino it says. Q5=Not for sure what you meant by this question. I am using C programming language, is that what you meant? Confused here.

Re Q1-2-3, looks like you mean uploading works ok when the only wire attached to Uno is the USB cable, but if app. circuit is attached it doesn't.  Re Q4, what text appears when you hover the mouse cursor over the Tools, Port line?  Re Q5, if you click Tools in the IDE, what shows up in "Programmer" field?

It is Com 1. Then in the programming field it says, "Atmel STK500 development board."

Can I just check you have the USB connected to the Arduino and the PC and you are using Serial to connect to the Bluetooth.  If so that won't work.  The code you have isn't reading from BT its reading the keyboard input of the PC.  You need 'SoftwareSerial' to create a second serial port on an Uno, or use a Mega, to connect to the blue tooth, then you can put the HC-05 into pairing mode and all that stuff.

Are you programming it from your phone, or from a PC.  (Either way the above comment still stands)

I am not trying to connect to another arduino, I am trying to connect to an android phone. When you say "SoftwareSerial" does that mean I need to change all my serials to this "softwareserial" in my coding? The video says nothing about it. I am programming from my PC and then uploading the code to the arduino.

There are several issues to consider:
• Program downloading
• HC-05 serial communication
• Bluetooth pairing
For the first issue:  The serial-over-USB connection between the development computer and the Uno ties up the Uno's hardware serial RX and TX pins.  There will be a conflict if the development computer transmits when the HC-05's TX is connected to the Uno's RX.  This can be resolved by disconnecting the HC-05 TX when downloading a program.
For the second issue:  The Uno schematic shows 1KΩ resistors between TX and RX on the ATmega328P and RX and TX on the USB chip (ie on an ATmega16U2, or a CH340, etc).  If the HC-05's TX drive is strong enough, it will overcome the drive from the USB chip and work ok.  Note, I would leave out the voltage divider (on the HC-05 RX line) that the video shows.
For the third issue:  The HC-05 in the video mentioned in the question has a blue LED that blinks steadily when the HC-05 isn't paired, and blinks at a long interval when it is paired.  Many HC-05's have red LEDs instead of blue; the LED color is not an issue.  Some HC-05's don't blink at all when paired; that's not an issue either.  What is an issue is that (according to description in question) your HC-05 keeps on blinking, so apparently isn't paired up.
Whether the HC-05 pairs with an Android app is more or less independent of whether you have the HC-05 connected to an Arduino; you should be able to pair your phone with the HC-05 when just Vcc and ground are connected to the HC-05.  If you are having trouble with pairing, try another app; try powering the HC-05 down and up; and try a different HC-05.  I mention trying another app because one serial-terminal app I installed on my Android phone needed the app or the HC-05 to be restarted to pair up after loss of pairing, and the serial-terminal app I replaced it with did not need those actions.  Note, pairing takes a few steps on my phone:  in Settings / Wireless, search for Bluetooth devices; select device; enter its passcode; run an app and tell the app which Bluetooth device to use.

I read through your answer and did what you asked me to or at least I think I did. So what I did is here:                                                                For the first issue I disconnected the HC-05 TX when downloading and it did it successfully unlike before. After downloading, I reconnected it since the arduino now has the code. Second issue: I left out the rx line resister and just put a wire in place of where the resistor was before for that line. Third issue: Noted. I tried different HC-05 and apps but after all these suggestions, it still has the same problem. More Ideas?

By "same problem", you mean blinking LED and not pairing?  That aspect doesn't depend on what the Arduino does -- it's up to the HC-05 and the phone.  Do you have another phone to try?  Did you enable BT discoverability of the phone?  [I don't remember at the moment the ins and outs of pairing, ie what matters and what doesn't; you may need to do some web searching on that topic, for your model of phone.]

I have the exact phone as in the video. I did research and nothing. And yes the same problem is blinking led and not pairing. I have BT enabled. I tried 2 different HC-05 with same results of blinking and not pairing. What is wrong? I did the same thing as in the video and it doesn't work? Just doesn't make any sense, it worked for him and I followed his exactly, so it should work.

Does your phone discover the HC-05 like video showed?  Did you send the 1234 or 0000 passcode?  Those are prerequisites for pairing.  Aside from that I don't have more ideas at the moment ... except I upvoted the question :)

The phone doesn't see the hc-05.

Try this code(it's simpler):
char data ;
void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}
void loop()
{
   if(Serial.available() > 0)
   {
      data = Serial.read();
      Serial.print("\n");
      if(data == '1')
      {
         digitalWrite(13, HIGH);
         Serial.print("on");
      }
      else if(data == '0')
      {
        digitalWrite(13, LOW);
        Serial.print("off");
      }
   }
}

Upload this to your Arduino. Open your phone, go to bluetooth settings and connect to HC05 with password 1234. Download an app from here: https://github.com/Mayoogh/Arduino-Bluetooth-Basic
Now your circuit should work.
Arduino to HC05 connections:
   5V -> 5V
   GND-> GND
   RX -> TX
   TX -> RX
LED connection: connect LED to pin 13 and the GND pin beside it(it's fine if you don't use resistor).


text:
Is it possible to use LCD (the 16 pins) without potentiometer?
look, I don't have any potentiometer lying around, and I don't have any variable resistor.
So is it possible to instead use a fixed resistor for the LCD display ?

Use regular resistors like Majenko said. But if you want to get extra fancy, you could use one of the PWM pins to set the contrast in software

Sure. You can use two resistors in series to be a "fixed value" potentiometer.
The "wiper" of the potentiometer is the junction between the two resistors.
I can't tell you what values to use, so you'll have to experiment. You want them to add up to somewhere in the tens of kilo-ohms though, ideally, though the value isn't that critical - it's the ratio between the two values that is of interest, and it's that which gives you your contrast setting.


text:
Arduino - Calculating the time for which a Pushbutton is pressed and held without being released
I'm working on a project that requires calculating the time for which a pushbutton is kept pressed without being released. Is there a code snippet that i can use for this particular need ?

Constrain your question.  Are you talking Minutes? Seconds?  Milliseconds?  If milliseconds, how do you plan on contending with switch bounce?

Milliseconds only. I haven't figured out the solution for the bounce problem yet.

Was not asking how you were going to solve it.  Wanted to know how you were going to interpret it. Guessing, I would say you want to start counting in millisecond increments on first contact.  Then I am going to assume you want to stop counting at last contact.  But the tricky bit: You will not know about last contact until after (depending on the quality of your switch) 10s of milliseconds goes by with out additional contacts.  So, what ever solution you choose, you will need to consider these issues and guess at the timing, try them then adjust them until you get the desired results.

Yeah that is exactly how I'am interpreting this question. Okay let me try and get back here. Thanks buddy.

There is a library called "Debounce", which you can find here: playground.arduino.cc. Based on that library, here is a simple sketch that displays the amount of time a button is pressed.
// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

void setup(){
  Serial.begin(9600);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}

The millis() overflow shouldn't be an issue, since the substraction endTime - startTime will also overflow, since elapsedTime is also an unsigned long.

Hi VE7JRO, I get this error, is there something wrong with importing the library ? :Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"
C:\Users\user\Desktop\buttonpresstrial3\buttonpresstrial3.ino:1:22: fatal error: debounce.h: No such file or directory
#include <debounce.h>
                  ^

compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Sorry @VishwaV, you can find it here: https://playground.arduino.cc/uploads/Code/Debounce.zip. I'll update my answer. I'm using version 1.0.6.2 of the IDE, and I'm guessing the newer versions use the updated Bounce2 libraries.

Hi @VE7JRO, Even after importing it to my libraries folder in arduino, I'm getting this error : D:\arduino-1.8.5\libraries\Debounce\Debounce.cpp:2:22: fatal error: WProgram.h: No such file or directory .  What should i do ?

On line 2 of Debounce.cpp, remove this: #include "WProgram.h" and replace it with this: #include "Arduino.h".

I replaced it with the help of notepad and the error still persists @VE7JRO

Try adding a couple of blank lines to the top of Debounce.cpp. The error was on line 22 (Debounce.cpp:2:22) the first time. Adding blank lines should change the line number of the error. We need to verify you are editing the right file.

Hi @VE7JRO i added a couple of blank lines to the top of debounce.cpp file and the error still stays on line 22. Am i editing the wrong file then ?

Yes, you are editing the wrong file.

Oops , okay wait this is what I did, I saw the Debounce.cpp file. Converted it into wordpad format and changed the line as you said. After doing this, i saved it back in the word format. Should i change it back to cpp format or anything like that ?

And the error has an additional line now :
Multiple libraries were found for "Debounce.h"
Used: C:\Users\user\Documents\Arduino\libraries\Debounce
Not used: D:\arduino-1.8.5\libraries\Debounce

It looks like the IDE can't decide whether to use the library on C drive or D drive. I would remove one of the duplicate libraries. File name should be: Debounce.cpp. I'm not familiar with wordpad. Do you have a simple text editor?

Hii @VE7JRO , you were right i removed one of those duplicate libraries and got it right. Your code is working absolutely fine now, Thanks.

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


text:
Fail to retrieve the value from gsm sim 900A by using AT Command to PHP script
I am currently trying to establish a connection between my gsm sim900A to one of my test server. The connection seems pretty good so far, though I'm a little bit confused why there are no values retrieved by my php file. Even so, the insert query works although it insert empty value into the database. So my question is how to retrieve it properly? I already change the method in php script to POST, both of it doesn't return any good signs.
Arduino Code:
void postData()
{
  sim900a.println("AT+HTTPINIT");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPPARA=\"URL\",\"test.my/demo/writedata.php\"");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPDATA=12,10000");
  delay(1000);
  printSerialData();

  sim900a.println("strBoton=999");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPACTION=1");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPREAD");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPTERM");
  delay(1000);
  printSerialData();
}

PHP Code:
<?php
$servername = "test.my";
$username = "****";
$password = "****";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$Boton = $_GET["strBoton"];

$sql = "INSERT INTO test VALUES ('$Boton')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Output:
AT+HTTPINIT
OK

AT+HTTPPARA="CID",1
OK

AT+HTTPPARA="URL","test.my/demo/writedata.php"
OK

AT+HTTPDATA=12,10000
DOWNLOAD
OK

AT+HTTPACTION=1
OK

AT+HTTPREAD
OK

AT+HTTPTERM
+CME ERROR: operation not allowed

AT+SAPBR=0,1
OK

I am not sure but, in this tutorial at page 8, it does almost the same code pattern like yours. You might want to check it. Sorry but I don't know PHP, I can't help you with it.
But I am confused with AT+HTTPACTION, since AT+HTTPACTION=0 is the read and AT+HTTPACTION=1 is the post. Check the tutorial and optimize your commands.
Also check this one. It writes WAIT=6 after AT+HTTPREAD before terminating it.

I will check the link you send. I will command on it if anything necessary. Thanks for the link by the way.

I'll change it to AT+HTTPACTION=0 and remove certain lines of codes and it works! Thank you sir. :)

Your welcome, always happy to help a fellow ;-)


text:
String array length in function
I know this question has been asked a thousand times, but I can't find a solution for my case.
I what to get the length of a string array in a given function. This is for an arduino board.
#define LEN(x) sizeof(x)/sizeof(x[0])
const char* mainMenu[] = {"FirstWord", "SecondWord", " "};

void myFunction(const char** m) {
  int a = LEN(m);

  /* Do something */
};

void setup(){
   myFunction(mainMenu);
};

The LEN(m) works fine in the setup() function. But in myFunction() it either gives me 1 (i guess the length of the pointer) or 9 (length of the 0th element of the array)

The problem is that LEN is evaluated locally for each usage replacing it with the content. In myFunction the parameter being passed to it is a pointer, not the array.
You need to evaluate the size once and once only in the context where the array hasn't collapsed into a pointer. That is usually done immediately where the array is defined:
const char* mainMenu[] = {"FirstWord", "SecondWord", " "};
#define MAINMENU_LEN (sizeof(mainMenu) / sizeof(mainMenu[0]))

Because mainMenu is a global it's always available, and when you require the length you get the length of the global array.
If you want to keep things local you will have to pass the number of elements in the array as a parameter to the function that uses that information.
myFunction(mainMenu, MAINMENU_LEN);

Another common alternative is to have some "end of array" marker and you loop through your array until you find that marker (that's how strings work - with \0 for the end of array marker):
const char* mainMenu[] = {"FirstWord", "SecondWord", " ", 0};

Then:
for (int i = 0; m[i] != 0; i++) {
    ...
}

hum, ok interesting. But how would I calculate the length of any given array passed to myFunction? In the example I only had mainMenu, but if I have multiple menus, I want to get its length programmitically

You can't. You have to calculate it somewhere where the array is still an array (the point where it's defined) and pass that value as a parameter.

really? so there is no function similar to go or python with len(x) or length(x) ?

No. There is no function like that. Simply because that is not how C works.

@will.mendil I have added some commonly used methods to my answer for you.

Just saw that, the for loop should work. I'm really used to python and fell in love with go a few months ao. But for what I'm doing, tinygo won't work since it's missing some functions. I'm struggling with C as the way it works it very different. Anyway, thanks for the help


text:
Arduino communication protocol with python - beyond pyserial and Arduino example
TL;DR does someone know of a advance and reliable/redudent USB protocol for communicating between a raspberry pi and Arduino due (native port)
I am trying to learn how to build a little robot which I hope could be autonomous at some point. In terms of hardware I am using an Arduino Due and a raspberry pi 3. The former is connected to DC motors, servos, ultrasonic sensors, light sensors, etc... The pi is responsible for running the picam and sending controlles from an Xbox controller to the Arduino as well as running a django web interface.
Long story short, I am trying to have python reliably communicating with the Arduino over serialusb (using the native port) but with no luck. The simple communication protocol shown in the Arduino example is too weak. I found a GitHub project named arduino-robust-serial https://github.com/araffin/arduino-robust-serial which worked at first but for reasons which are quite long to discuss here was not enough.
My question is as follows: does someone know of a reliable serial protocol around which could be used to have a raspberry pi communicating with an Arduino over usb?
I hope I'm not too vague. But looking online I'm struggling to find resources regarding Arduino which are not beginner blinking light examples.
Thx

What protocol in what "example"?

The one I was referring was the SerialEvent example in the arduino IDE

Ah that. That's really not a protocol example. Only an example of how you can do things with SerialEvent.  SerialEvent is silly, anyway. Forget it.

Good to know, so do you have a recommendation to how I could get the two to talk properly and fast, as the sensors need to transmit data to the pi in real time?

Depends very much what the data is and what quantity there is.

The pi transmits command to control the motors. Wanting to expand I the future python sends the motor's name and a value. The Arduino ois responsable from interpreting that. On the other hand the Arduino sends data from 8 ultrasonic sensors as fast as possible (ideally every 50ms) as well as a light sensor which measures the rotation of the wheels (basically within a few dozen milliseconds).  My question wasn't really a how to do it. But rather has someone proposed a serial protocol to do such thing. I would be surprised otherwise

There are many many protocols around. I myself have one called ICSC, though whether that is suitable for you or not I can't say. There's as many ways of transferring the data as there are cats that want skinning. You could probably get away with a simple ASCII protocol (M1:213\n for example).

Why is the simple protocol from the examples too weak? Are you loosing data with it? Or what is the problem there?

indeed, I am missing data packets (e.g. the motor keep spinning even though I've sent the stop command) probably because the buffer is more than often full. and since I'm streaming data from the arduino i get to some points where everything freezes. Needless to say, that I'm not using it well, hence why i'm looking for examples of protocols such as the ICSC mentioned here or the arduino-robust-serial to see how people did it. I'm basically not very good at implementing the example shown in the aruidon IDE and am looking for what people have done so far

If your Arduino code cannot process the information fast enough, you have a general problem. At one point or another you will loose information with every communication protocol, if you cannot process the information as fast, as they are arriving. The buffers will also fill up with other interfaces. Or are your messages simply too long (more than 6 byte)? Then raise the buffer size

*more than 64 bytes - in case of Serial. Not 6 bytes, sorry, typo

Maybe if I reformulate my question: what frameworks exist for robotics applications that consider the coupling of an arduino with a raspberry pi (I'am looking into ROS.org, though it's not ideal for raspberry pi) are there modern alternatives?

why would the arduino need to transmit the signal from the wheel rotation sensor? ... that part of the system should stay in the arduino ... the arduino and the wheels should be more like a Logo turtle ... the RPi issues a command to move ahead 10cm and the arduino does it ... or move ahead 10cm, but stop when bumped, and report actual distance of travel

Ok, after quite some time looking for something that would allow me to easily control an arduino with the raspberry pi, I found the FIRMATA protocol which allows one to communicate with the arduino through many languages. (a snippet from the github page for SEO purposes is shown at the end of this message).
From there I looked for through the python frameworks, and had a long chat with MrYsLab who helped me integrate the arduino Due to his pymata and pymataExpress frameworks. They work quite well and enable you to have a script that quickly and efficiently communicates with the arduino. I'm sure proper frameworks from ros.org or gobot are better. But pymata worked for me hence my answer to my own question.

processing

https://github.com/firmata/processing
http://funnel.cc

python

https://github.com/firmata/pyduino
https://github.com/lupeke/python-firmata
https://github.com/tino/pyFirmata
https://github.com/MrYsLab/PyMata
https://github.com/MrYsLab/pymata-aio

perl

https://github.com/ntruchsess/perl-firmata
https://github.com/rcaputo/rx-firmata

ruby

https://github.com/hardbap/firmata
https://github.com/PlasticLizard/rufinol
http://funnel.cc

clojure

https://github.com/nakkaya/clodiuno
https://github.com/peterschwarz/clj-firmata

javascript

https://github.com/jgautier/firmata
http://breakoutjs.com
https://github.com/rwldrn/johnny-five

java

https://github.com/4ntoine/Firmata
https://github.com/kurbatov/firmata4j
https://github.com/reapzor/FiloFirmata

.NET

https://github.com/SolidSoils/Arduino
http://www.imagitronics.org/projects/firmatanet/
https://github.com/wbadry/FirmataCSharpClientClass

Flash/AS3

http://funnel.cc
http://code.google.com/p/as3glue/

PHP

https://bitbucket.org/ThomasWeinert/carica-firmata
https://github.com/oasynnoum/phpmake_firmata

Haskell

http://hackage.haskell.org/package/hArduino

iOS

https://github.com/jacobrosenthal/iosfirmata

Dart

https://github.com/nfrancois/firmata

Max/MSP

http://www.maxuino.org/

Elixir

https://github.com/kfatehi/firmata

Modelica

https://www.wolfram.com/system-modeler/libraries/model-plug/

golang

https://github.com/kraman/go-firmata

Qt/QML

https://github.com/callaa/qfirmata

Android/Kotlin

https://github.com/xujiaao/android-firmata

Smalltalk

https://github.com/pharo-iot/Firmata


text:
Code for a rolling average
Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.
What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.
My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.
#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 tempSensor;

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

double array[30];
double rollingaverage=0;
int i=0, j=0;
double sum=0;
double newreading;
void setup() {

  Serial.begin(9600);
  lcd.begin(20,4);
  mlx.begin();
  Wire.begin();

}

void loop() {
  if(j=0){
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      sum += array[i];
      if(i>0){
          rollingaverage = sum/(i+1);
      }
      j=1;
  }
  else{
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      if(i < 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
          sum = sum + array[i] - array[i+1];
          rollingaverage = sum/30;
      }
      else{
          sum = sum + array[i] - array[0];
          rollingaverage = sum/30;
          i=0; //reset index to 0
      }
  }
  i++;

  lcd.clear();
  lcd.print("Belt: "); lcd.print(rollingaverage);
  lcd.setCursor(1,2);
  lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

delay(2000);
}

Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks

Example, if you have 25 valid values and 5 zero, you need a counter for "valid values" and change rollingaverage = sum/30; and replace 30 with the counter value.

if(j==0) instead of (j=0) would be nicer perhaps.

Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.
I have a library that does it all for you that would make things easier for you:

https://github.com/MajenkoLibraries/Average

One way is to initialize the whole buffer to the first value. Your average won't be "true" in some sense, until the whole buffer has been replaced with read data, but as long as that first value isn't too different from the true temperature, your average during that period will be more sensible. I.e., it won't have to  ramp up from zero.
Another way is to use an Exponential Average instead of the Rolling- or Boxcar-Average. The Exponential Average doesn't depend on storing old samples and can adjust well - i.e. within a few samples, depending on 'X' (see below) - to a sudden change (which temperatures don't normally do, anyway).
It calculates a new average by summing X percent of the current average + (100-X) percent of the next sample - you choose the value of 'X' that works best in your own application.  I have good results averaging temperatures, even from analog sensors, using X=75. For fixed-point numbers such as the 4 binary places returned by the Max DS18b20 sensors, would be
// (3 * avg + 1 * sample) / 4
avg = (((avg<<2) - avg + sample) + 2) >> 2;

For floating point numbers, it would just be:
avg = (3. * avg + sample)/4.;

Update:

Initialization is as much an issue with an exponential average as it
  is with a boxcar average.

Yes, it is. I initialize my exponential averagers with the first sample and usually get along pretty well. It might not work so well if the averager was too heavily damped.

... a boxcar of width 30 ...

An exponential average, by its nature, can give recent samples more weight than older ones so giving so little weight as you suggest to the next sample will make it quite heavy-handed! X=75% has worked quite well for me to reduce noise without heavy-handed damping. What works well for one system may not work for another, but by running a saved sample-set through a few trials on your desktop will quickly get you to a reasonable X.
We don't know how that width (30) was arrived at; perhaps it is necessary? But averaging, by its nature, being both low-pass (usually desired) and delaying (generally not desired), spreads sudden features like spikes while it limits their amplitude. I've sometimes use a spike suppressor ahead of a lighter averaging filter, where the alternative average-only would have required enough averaging to damp significant signal features too heavily.

Initialization is as much an issue with an exponential average as it is with a boxcar average. Specifically, a boxcar of width 30 has roughly the same “averaging strength” as an exponential average with X = 100×(1−1/30). And the latter will need more than 30 samples to completely settle.

The other answers address the problem with your code, however a better solution is to use a different algorithm.
I would use exponential smoothing (which is simpler to code, requires less data and produces a similar result). This is the technique I used to use when responsible for producing statistical performance reports. If readings are plotted this results in a smoother graph, which shows trends and discounts noise.
Briefly take the current sample, multiply by a discounting factor and add the a proportion of the current value.

s = x * α + (1-α) * s

To produce results from the start initialise the sample to the first reading then calculate.
See https://en.wikipedia.org/wiki/Exponential_smoothing
I would probably start with a smoothing factor of 0.3 - choose a smaller value to give more weight to past values.

You are essentially repeating JRobert's answer.


text:
Powering Arduino Uno, CAN Crocodile and NeoPixels from Car
I have purchased a cigarette adapter that gives me 2 USB ports, however this gives me 5v and up to 2.4A.
Thats ok for powering the Arduino Uno, I need 12/24v to power the CAN crocodile.
I also want to drive quite a lot of NeoPixels.
How can I do this?

Being specific in your question will help; what does "quite a lot" of NeoPixels mean, in quantified terms?

Sorry, 186 neopixels.

A reasonable estimate for current consumption of 5V NeoPixels is 60mA per pixel. For 186 pixels, that means about 11.16A at 5V; well over the 2.4A of the adapter being used for your other components.
There exist modules called "DC-to-DC Buck Converters", which can step down the 12-14V of your automobile to pretty much any voltage under the input voltage. To be safe, look for a buck converter of at least a 75W rating, and which meets your criteria for input and output range (minimum of 12V input, could be rated higher; output range inclusive of 5V.)
Be sure that the Ground connections for the NeoPixel power supply and the other supply are shared/connected, but don't share the +5V line between supplies.

Thank you, this is all a bit beyond my understanding...I'm a very good coder but electronics is something I play with...is there an off the shelf solution that I can purchase to provide me with connections suitable for the Arduino Uno with CANBus shield and the NeoPixels?

You can search the usual online vendors (amazon, ebay) for "Buck Converter" and make sure they can handle your input and output voltage needs, and at least 75W (your NeoPixels alone could draw up to 55W, and it's safe to have some buffer). Most of what you'll find are bare PC Boards with components mounted on them, but no case/enclosure. Your definition of off-the-shelf may be different.

How about this: https://www.amazon.co.uk/Droking-Converter-Step-down-Regulator-Voltmeter/dp/B07CV6QQ8Q/ref=sr_1_34_sspa?ie=UTF8&qid=1538492915&sr=8-34-spons&keywords=%22buck+converter%22&psc=1

That one is limited to 2A, so it won't work. In general, this community avoids direct product recommendations. On the link you gave, there are "also viewed" items that include higher-current buck converters.

I haven't worked out the current requirement, https://www.amazon.co.uk/dp/B01N9FB78X/ref=sspa_dk_detail_1?psc=1&pd_rd_i=B01N9FB78X&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_p=8e5be0e3-b258-4b06-8b6e-695b24f935a4&pf_rd_r=ZTFR1W9099TXMBWXGJ6S&pd_rd_wg=JYlov&pf_rd_s=desktop-dp-sims&pf_rd_t=40701&pd_rd_w=BVivb&pf_rd_i=desktop-dp-sims&pd_rd_r=467c2bda-c656-11e8-a52e-91026566f7d5

That next link is a "boost converter" which raises output voltage above the input voltage. Something along these lines https://www.ebay.com/itm/24V-12V-To-5V-20A-Buck-Converter-100W-High-Current-Voltage-DC-10-35V-Regulator/223167400971

And on Amazon, although it states the output voltage is 5V: https://www.amazon.co.uk/Converter-DROK-Current-Regulator-Regulated/dp/B00F0FYPPQ/ref=sr_1_1?ie=UTF8&qid=1538494335&sr=8-1&keywords=24V+12V+To+5V+20A+Buck+Converter%2C+100W+High+Current+Voltage+DC+10-35V+Regulator

I still need at least 12v for the CAN crocodile.

Is your car not a 12V system?

Yes, its an Audi A5, I'm looking for a solution that I can plug into the power outlet in the boot, which is a cigarette lighter style socket... I need 5v for the Arduino and CANBus shield, 12v for the CAN Crocodile and 5V for the neopixels but these can draw quite a bit of current, something that protects the car system from going pop.

You don’t need a converter for the 12 V.

What I need is a convenient interface to the various voltages.

12V from the car, 5V from the buck converter. What other voltages do you need?

Just looking for a suitable mechanical interface where I can attach all the wires...looking for something ready made I can just attach to.

I don't think you'll find something more ready-made than what has been shown so far...


text:
using pmrpcm library for sound output from Teensy3.2
I converted an MP3 sound effect (5 seconds long) to WAV to play it out of a Teensy3.2 with speaker connected to PWM output pin.  The TMRPCM library specifically talks about Arduino AVR boards, but doesn't mention Teensy.  On the PJRB (Teensy) website, the only info I can get is for their high quality audio shield with extensive programming.  I just want to play the simple WAV file from the SD card where it is located.  (I can display images on a GLCD from SD card, so not a problem).  The problem is when I compile my sketch I get many errors related ONLY to the the library.  If I don't include the TMRPCM library, there are no errors.  I DON'T NEED high quality sound!  Any ideas?  Another library perhaps, or tweaks to existing?  I can post the errors if necessary, they seem to be related to timers not being declared in the .h file.

Teensy 3.2 is not AVR Arduino. TMRPCM is only for AVR Arduino. Since the Teensy 3.2 has high quality sound why would someone port the low quality TMRPCM library to it? You could, but a simpler method is just to use a timer for sample rate and adjust PWM duty cycle per sample with a carrier frequency > 2x the maximum sample frequency.

Sometimes you don't need the expensive fountain pen...just a pencil.   The Teensy should do EVERYTHING and more than an AVR chip, in my opinion.  having said that, I'm using an el-cheapo ISD1820 sound module with small amplifier module and getting exactly the results I want.   I had been hoping to put a number of sound bytes on SD card, but this works and modules are so cheap I can use more than one.   Get 20 seconds of sound.

The Teensy can do everything the AVR Arduinos can, and more. It's just a SMOP. No one has needed it to do what you want, since it does better than what you want, so no one has bothered to program it yet.

I understand but I wanted to use TRMPCM to have a library of MP3/WAV SFX on an SD card.  Surely others would want such a thing, it would be great for games for example.  Another analogy: I wanted a small transistor radio, not a complete component stereo system.

So why use a Porsche to go shopping?


text:
Programing a Bare Pic32
I recently received two types of Pic32 microcontrollers from Microchip, specifically the PIC32MX270F256B and the PIC32MX230F256B. I would like to use an Arduino Uno to setup the bootloader and to do all the programming. I found a tool to upload to the board here, but as it is from a 2012 forum here, I cannot figure out what it is exactly used for. It seems to be able to upload hex files, but in which format and to what is unclear to me. I also found Arduino bootloaders for a similar group of microcontroller here, however I cannot tell exactly which version I need, if any, or how to upload it.
Any help on how to use these tools or others would be greatly appreciated as my only experience with Arduino before this is with a simple to program to Arduino Uno.

To all who have an better idea than I do as to how to tag this, feel free to suggest changes or just edit the post.

I am unaware of any Arduino-based tools for installing a bootloader on a PIC32. If you are going to work with PIC32 you really should invest in a proper programmer.
I often use (pretty much throw-away) Chinese clones of the PICkit2 programmer. You can find them on eBay nice and cheap.  Genuine Microchip programmers are pretty expensive, so these cheap clones are quite handy...
You will also want to install the chipKIT environment into the Arduino IDE.
When it comes to the bootloader there are no official boards that use those chips. So you will need to compile your own version, which is not trivial. You will need to install MPLAB-X and the XC32 compiler and create a new profile within the project with the right settings for your board.
And then of course you will have to craft a board configuration for your custom board.
All-in-all it's quite a complex task porting a new board / chip to the chipKIT environment, and you would probably be better off directly using MPLAB-X and programming directly in C (although it's harder to get started in that environment). The PIC32 chips are considerably more complicated to work with than little AVR chips.


text:
How to use? ATmega328P Development Board for Arduino UNO R3 Bootloader Project DIY

How to use? ATmega328P Development Board for Arduino UNO R3 Bootloader Project DIY.

The answer is: you don't use it. Buy a cheap arduino uno clone. This development board does not have a usb-serial chip, therefor it is not possible to upload a sketch to it without extra hardware. It was probably in the description where you bought it, that you need an extra usb-serial module. Instead of buying an extra usb-serial module, you may just as well buy a arduino uno clone.

Looks like about 1/5th of an Uno with a ZIF socket. The rest, other than the ZIF socket, is pretty pointless. The USB is for power only. To program it you need an external USB UART interface. It doesn't even have a USB-ASP built in like you'd expect from something that looks like that.  Pretty much a pointless heap of junk.

@Majenko, the 2x3 header is labeled ICSP, so it is a bootloader flasher

No, that is for plugging a programmer into. like the Uno's icsp header.

The purpose of this board is to flash (Arduino) bootloader to Atmega 328 chips. It has not a build in programmer, only a ICSP header to connect the programmer.
So wire it with a programmer and then chip in, ZIF close, burn bootloader, ZIF release, chip out, next chip in, ZIF close, ....
video

Actually you can program with this device. Treat it as a Genuino Uno and select AVRISPmkII programmer. Used mine several times.


text:
Call function and not came back
Im having a little problem with my code. here i called a function to make a test, if it passed it goes back and continue if it doesn't it goes to main loop.
void loop()
{

    if (call == 1)
    {
        funca();
    }
    print("waiting..");
}
 void funca()
    {
        gsmtest();
        print("calling..")
    }
 void gsmtest()
    {
        if (test==1)
             {
            print("test ok");
             }
        else
              {
                print("error");
                loop();
              }
    }

here is a simple example, if u press call, the code goes to funca which make a call to gsmtest. if test goes ok it print "calling.." if not it print "error" and goes back to loop. for some reasons here if test failed, it print error and than goes to loop after that it print "calling.." (continuing funca which i want to abort it if test goes wrong) .

You're overflowing your stack due to infinite recursion.
By explicitly calling loop() you are breaking the whole call stack system. You effectively have:
loop() ->
  funca() ->
    gsmtest() ->
      loop() ->
        funca() ->
          gsmtest() ->
            etc...

Instead of>
loop() ->
    funca() ->
        gsmtest()
    <-
<-

Instead of calling loop() you should use return; to "return" back to where the function was called from.
For example:
void loop() {
    if (call == 1) {
        funca();
    }
    print("waiting..");
}

void funca() {
    if (!gsmtest()) return;
    print("calling..")
}

bool gsmtest() {
    if (test == 1) {
        print("test ok");
    } else {
        print("error");
        return false;
    }
    return true;
}

but in that case if gsmtest is error it will continue to the next instruction (it will print "calling.." while it doesn't suppose to).

So you have it returning a value that says "this failed" then test for that in the calling function, then return from that too.

yes its my back up plan, but i'm looking for better way, without using variables.

You won't find a better way. This is how it is done. And you don't need variables.  Let me craft an example for you.


text:
Arduino for push notifications to phone
I'm interested in using an Arduino for a project for taking information and sending it through a phone application. I was wondering what the cheapest option there is for an arduino with internet capabilities. From what I see, a lot of articles list they use UNOs with shields for wifi/ethernet. After looking these up, I noticed that they can get a little pricey. Is there any alternative options I may be overlooking? Thanks.

You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.

Also, the ESP8266 itself can be coded with the Arduino IDE/environment, and could replace an existing arduino. In general the ESP8266's have more RAM and flash storage than the UNO.

Is it possible to use any GPIO on ESP8266? It would be nice to hook the sensor directly onto ESP8266. For example DHT22.

The ESP8266 has several GPIO pins. https://github.com/esp8266/Arduino/blob/master/doc/reference.md#digital-io
Note that they are 3.3V, not 5V like the UNO.

Well then you can't get any cheaper than ESP8266 if your requirements are limited to a few GPIOs. Thank you for pointing that out @josecanuc.


text:
Vin and Ground pins shorting only under specific conditions
So I have an Arduino Nano that I think might have gone bad. The Vin and ground pins are shorting (I'm checking continuity with a multimeter). But it only shorts when:

The Arduino has power
The red lead of the multimeter is on ground and the black is on Vin (not the other way around)

I've tried checking with the leads both ways (red to ground as well as red to vin) while both on and off, and with two different multimeters, one of which is brand new. Completely at a loss for words because this isn't really how physics is supposed to work (continuity shouldn't depend on lead orientation from the multimeter or whether the circuit is powered, right?). Any insight would be appreciated. Do I have a bad board?

Sounds normal to me. You shouldn't measure continuity when power is applied. As to point two. For the multimeter to measure resistance, it has to apply a small voltage. The Arduino however is using this voltage and tries to run on it. This in turn will drop the voltage making the multimeter confused. Measuring components that are in circuit can be hard or even impossible in certain situations.

if a circuit has DC continuity in one polarity and not the other, there is a diode across the circuit. you describe a "reverse input polarity protection" diode doing it's job.

But it only shorts when: The Arduino has power

You must not use a continuity checker or ohm meter on a powered circuit.
Not only will it not work, you risk damaging the meter.
It's also not necessarily safe to use such a meter on an unpowered active electronic circuit like an IC or eval board, as the meter must apply a small amount of power to the circuit to make a measurement - how much power varies between meters and settings, and how much a circuit can tolerate in an unintended way depends on things like polarity and the state of other parts of the circuit.  However, it is common practice to do so - especially for example when there's a fear that the device might already be damaged.

It is not clear from your question what you are measuring with the multimeter (volts, ohms, amps etc.) but if you are using the ohms scale when your Nano device is not connected to the power, your multimeter charging capacitors on the board and reversing the leads will then cause a discharge through the multimeter, maybe giving a reading which leads you to believe there is a short circuit.

I'm checking continuity (whether or not there is a closed circuit).

Also if you have this setup and set it to measure Amp, then it will effectively shortcut the leads with as small resistace as mutltimeter can.
Also check, if those connectors (usually crocodiles) cannot touch something they should not (each other mainly)


text:
Question about Variables
is there a way to use a previous assigned value to variable to adjust the step motor? what i mean is:
example:
Sensor reads 100 degrees so
Adjust the step motor to 100 degrees and hold, then after 10 min
the sensor reads 110 degrees so
Adjust the step motor (110 - 100) by extra 10 degrees
and so on..
I'm really new to this and i'm sorry if that's a stupid question :<

Start with example code for driving the stepper motor. Then calculate how many degrees equals one step. Use a variable to save the current Position of the stepper in units of steps. Everytime the Sensor reads a different value, calculate how many steps to take, run the stepper and maintain the variable.

I see you are getting close votes on your question. I strongly suggest you do some basic C (or C++) tutorials. Asking a "question about variables" is really nothing to do with motors or sensors. Do some tutorials and then you will understand how to use variables. The Arduino is programmed in C++ if that helps.

Based on your description, the program needs to know only the new target setting and the current position. That means you need two variables. Algorithmically, it would look as follows (written in C-like pseudo-code):
// initialize global variables (might need float instead of int)
int target_pos = 0;
int current_pos = 0;

void setup() {
    // add code to set up pin IO mode, prepare communication with the sensor...
}

// function to read the sensor
int ReadSensorFunc(void) {
    int reading = 0;   // local variable to store sensor reading
    reading = ...;     // add code to read sensor
    return reading;
}

// function to adjust the motor position
void AdjustStepMotorFunc(void) {
     // add code to to adjust the stepper to (target_pos-current_pos);
}

void loop() {  // repeat forever
    target = ReadSensorFunction()   // call sensor read function
    AdjustStepMotorFunc()           // call position adjustment function
    current_pos = target_pos        // update current position
    // add code to delay for 10 minutes
}

This code initializes the position as zero. In case it's not zero when the controller is turned on, you'll need additional code in setup() to assign current_pos the correct value based on user input.

Initially you read the value of sensor to some variable, like:
previous = readSensor();

Every ten minutes you have to call a function ( logic using timer interrupt / RTC /millis() ) which reads the current value from sensor and compares it with previous value to get the offset. Then you pass it to the function which adjusts motor speed. Update 'previous' variable
offset = readSensor()-previous;
previous = readSensor();
adjustSpeed(offset);


text:
Can only write 5V or 0V, not something in between
I'm working on a bigger project, and needs to give out a voltages between 0 and 5V. I've written this code:
int ledPin = 12;      // LED connected to digital pin

void setup(){
pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop(){
analogWrite(ledPin, 255);
delay(2000);
analogWrite(ledPin, 0);
delay(2000);
analogWrite(ledPin, 127);
delay(2000);
analogWrite(ledPin, 128);
delay(2000);
}

If I've understood it right, this should first give about 5V, then 0V, then 2.5V and againg 2.5V. However my voltmeter only reads 5V and 0V, 2 seconds at each. I've attached my voltmeter to pin 12 and ground. The arduino board is also grounded.

You don't say what board you're using, but you may want to check that pin 12 is a PWM  pin on your board. You may find the page on analogWrite() on the Arduino site useful.

on Uno pwm pins are marked with ~

Most Arduino boards do not have true analog output that can produce voltage range. To check if a particular board has true analog output check the specs and look for pins labeled DAC or Digital-to-analog converter.  Be aware that the supported voltage range will vary depending on the board.
The analogWrite() function uses Pulse Width Modulation to simulate analog output.
If you need true analog output you will need to attach a Digital to Analog Converter(DAC) to the arduino. e.g. https://learn.adafruit.com/mcp4725-12-bit-dac-tutorial
UPDATE:
If your goal is to drive a motor with a SN754410 you should be able to use the PWM analog output to drive it at varying speeds.  Here is an example: http://web.ics.purdue.edu/~fwinkler/616/sn754410_Arduino.pdf

Now it works! It helped using an PWN pin. But should it not also work with one of the analog pins? Or are these pins actually only analog in the reading prosess?

A0-A5 are analog inputs only -- there is no true analog output on the UNO, only PWM.

Some ARM-based Arduinos (e.g. Due) have DACs on-board.

The PWM pins output a square wave from 0 to 5V. If you want something more like a DC level, then run the signal thru a Resistor-Capacitor (RC) Lowpass filter.
1K and 10uF should work well to smooth the squarewave.
http://sim.okawa-denshi.jp/en/CRtool.php
On an Uno, pins 3,5,6,9,10,11 are the PWM pins and output at a frequency of ~ 490 Hz or 980 Hz, with a duty cycle from 1 to 254. 0 is full off, 255 full on.

good info, but you shouldn't need a filter to satisfy a voltmeter, they are slow at math

@dandavis - on the contrary, the opposite.  DC voltmeters are not designed to measure changing signals; if you want to use one, you must first stabilize the signal such as with the proposed filter.  Otherwise you need to use an instrument appropriate to a changing signal, ie, a scope.

i just meant that both a dmm and analog meter will show about the same thing with or without RC, not accurately display the peak, duty, etc...


text:
How to achieve active 4G LTE communication?
I'm not sure if this is correct place to post this, if not PLEASE redirect me to the proper page, as this matter is quite pressing to me.
My entire day was spent researching different methods of inter-Arduino communication, and for my project, using 4G/LTE/LTE-M is clearly the route I need to take. However, I cannot find an answer to my problem:
I see a lot of information about how to continuously upload information to a IoT service/provider, or to a dashboard website. That's great. Problem is, I need an Arduino with a LTE shield to talk to another Arduino with a LTE shield. Suddenly the internet shuts down and I can find next to nothing about communicating between two Arduino's using LTE shields, much less keeping that connection active.
Of course this could be accomplished by uploading data to a IoT site via Arduino A, and retrieving stored information via Arduino B, but I'm afraid that will induce too much latency into my system. I need this to be as FAST as possible.
The module I have my eye set on currently is this one: https://www.cooking-hacks.com/documentation/tutorials/4g-gps-lte-wcdma-hspa-3g-gprs-shield-arduino-raspberry-pi-waspmote-tutorial/#step10
Is there a way to connect directly to another LTE device? How to I keep that connection always active? I know this question is a little broad, but I don't even know where to look! Internet connectivity is not my strong suit. From what I've gathered, I need to set up one Arduino as a server and the other as client. UDP may be the option I'm looking for, but I'm not totally sure. Every single tutorial/explanation I've seen is connecting directly to a webpage or other online service and NOT another LTE device.
Any help or direction is greatly appreciated, thank you!

You won't find any solution - because it is impossible; 4G LTE is not a peer-to-peer protocol.

What is your original design problem? What are your requirements?

@Milliways Then how do digital phone calls work? What about active connections like facetime?
@ MikaelPatel I just need the most basic active connection between two LTE devices, whatever or however that might be.

@HavocRC Facetime and other peer2peer services use a server. Even you can use a server like Firebase to enable communication between the devices. Connecting between 4G to 4G is not possible at all. You may use Bluetooth/WiFi or RF for local communication.


text:
How to get around passing a variable into an ISR
Okay so you aren't able to pass a variable into in ISR. This is causing problems for me. I'm using a rotary encoder, and I need it to be connected to an interrupt pin and running a ISR. When using this method, no pulses are ever skipped and the knob works great.
Currently I have the ISR setup like this:
void vhISR()
{
  // this checks the PINE register for a 1 or 0 on the 5th bit (or 6th)
  // I'm bit shifting the result so that variable is either true or false for comparison, not 16/0 or 32/0
  rotCurrentA = (PINE & B00010000) >> 4;
  rotB = (PINE & B00100000) >> 5;

  if (rotCurrentA != rotLastA)
    {
      if (rotCurrentA != rotB) // cw
        {
          voltageHigh += knobResolution;
          rotLastA = rotCurrentA;
        }
      else // ccw
        {
          voltageHigh -= knobResolution;
          rotLastA = rotCurrentA;
        }
    }
}

The code simply varies voltageHigh by 0.1V increments. The problem is this: I need to do this same 0.1 variations on several other variables, depending on which one I select. I need to increase/decrease a voltageLow, a timer, and a resistance, all that need +/- 0.1 increments (but on different ranges. For instance, voltLow is somewhere between 0.1 & 5, and VH is somewhere between 6 & 10). Normally what I would do is just pass the variable I needed by reference into the function and have the function increment/decrement that variable....but an ISR is not a normal function and you cannot pass a variable into it.
How do I get around this? I'm not sure if that's enough information to go off of let me know.

why not use the Encoder library?

Not an option. This is working perfectly, aside from this small issue.

a switch statement based on a global variable with the current selected setting?

Don't change the variable in the ISR.  Just keep track of the number of clicks and add them to the appropriate variable in code.  You'd need to be turning off interrupts to use those variables anyway, so just replace that code with the read and modify.

I would follow Delta_G's advice, and write an ISR that counts the steps
and does nothing more. As a general rule, you want to do as little as
possible within an ISR. I would even avoid floating point and just count
the raw number of steps:
// Count of rotational steps updated in the ISR. Must be unsigned in
// order to avoid signed overflow, which is undefined behavior.
volatile uint16_t rotation_count;

void vhISR()
{
    static uint8_t rotLastA;
    uint8_t rotCurrentA = (PINE >> 4) & 1;
    uint8_t rotB = (PINE >> 5) & 1;

    if (rotCurrentA != rotLastA)
        return;
    if (rotCurrentA != rotB) // cw
        rotation_count++;
    else // ccw
        rotation_count--;
    rotLastA = rotCurrentA;
}

// Return the number of rotational steps since the last call. Should be
// called often enough to avoid overflowing an int16_t.
int16_t get_rotation()
{
    static uint16_t last_count;

    // Avoid a data race: rotation_count should not be modified while we
    // are reading it.
    noInterrupts();
    uint16_t count_copy = rotation_count;
    interrupts();
    int16_t delta = count_copy - last_count;  // this is signed!
    last_count = count_copy;
    return delta;
}

Note that the raw count is an unsigned number which can roll over modulo
216. The value returned by get_rotation(), however, is a
signed number which, owing to the rules of modular arithmetic, is
immune to the rollover of the raw count. As long as you call
get_rotation() often enough (more often than every 32767 steps),
the returned value will always be correct.
Then, in your main program, you can use this to update whatever variable
you want:
const float knobResolution = 0.1;
float voltageHigh, voltageLow, resistance;

// The variable that the user has selected for changing.
enum {VOLTAGE_HIGH, VOLTAGE_LOW, RESISTANCE} selection;

void loop()
{
    // Set a pointer to the selected variable.
    float *selected_var;
    switch (selection) {
    case VOLTAGE_HIGH:
        selected_var = &voltageHigh;
        break;
    case VOLTAGE_LOW:
        selected_var = &voltageLow;
        break;
    case RESISTANCE:
        selected_var = &resistance;
        break;
    }

    // Update the selected variable.
    *selected_var += get_rotation() * knobResolution;
}

Note here that the selection enum is probably redundant with
selected_var. You could use the latter to keep track of the user
selection, then you would not need the switch/case.

This is awesome! Thank you for typing it all out for me. I'll have to mull this over soon and implement once I understand everything. Thanks!

Okay so you aren't able to pass a variable into in ISR ...

Not as such, because the ISR is triggered by hardware, and therefore you don't pass arguments to it.
However there is nothing stopping you having a global variable which the ISR can access (preferably declared volatile) so the ISR can change its behaviour depending on what the global variable holds.


text:
RFID working with interrupts
I recently created a rfid project with the sensor rfid rc522. I used the instructions mentioned by this site and works perfectly. However, I intend this project to be battery supplied and I want to make the system use as low current as possible using the low power library. Well I need arduino UNO hibernate until an interrupt by the rfid is occured. Any proposals on how am I going to detect an interrupt by the rfid?
(PS) If there is any better battery saving library that can detect interrupts while keeping arduino slept, then feel free to propose it to me.
Thank you in advance.


text:
Can an Arduino emulate a USB mass storage device?
Question:
Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?
Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?
This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.
Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?
Research:
I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?
Possible Solution:
The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?
Diagram:
Arduino USB Port -> USB Cable -> Embedded Device USB Port
Arduino GPIO -> USB Module -> USB Cable -> Embedded Device USB Port
Requirements:
Connection via USB cable between Arduino and an embedded device's USB port.
Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

Not with an UNO. Could you expand on what it is you want to achieve? What is the end goal here?

Sure. I want to be able to emulate a USB thumb drive for an embedded system that has a USB port. You usually plug in the USB thumb drive into the embedded system, and then it reboots when it reads a file from the USB thumb drive. I'd like to develop something where I can emulate the plugging in/unplugging the USB thumb drive with that file in it's folder.

Couldn't you just use a regular flash-drive, but have the Arduino disconnect and reconnect it. Using something like a MUX (multiplexer), or maybe even a few relays. Just get a usb extension cable, and cut it in the middle. Then connect the 4 wires inside via the MUX/relays.

On a side-note. The newer raspberry pis can act as a Mass Storage Device.

The Raspberry Pi sounds promising. I want to develop a program to upload/download the binary file on the mass storage device. Maybe the Pi is a better option?

The MUX or relays might be a good idea to emulate the insertion/removal of the USB thumb drive.

Anything else you want to know?

This is indeed not a fit for an Uno, though one of the ARM or 32u4 based boards (Arduino, Teensy, or other) could work up to the on-board storage size or with an SPI flash.  In the raspberry pi world only the boards without a hub in the way (such as the zero or model A) can do it, but pi's add a lot of delicate software state.

What are the Arduino 32u4 boards? I read about the AVR boards a little bit, but I'm not sure how they differ from the popular Arduino boards. Do you have a suggestion for an ARM board for this particular configuration?

The Arduino functions as a USB client device, not a USB host.
You can get a shield which claims to allow the Arduino to operate as a USB Host to allow it to control various USB devices including thumb drives: link

check out http://elasticsheep.com/2010/04/teensy2-usb-mass-storage-with-an-sd-card/

The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947

This (Arduino is USB host so e.g. memory stick could be read by Arduino) is the opposite of what is being asked (Arduino acts as memory stick).


text:
Dual OLED displays showing the same image via SPI?
Is it possible to connect two oled displays via SPI to my Uno and send a single image to both displays, with each refreshing at an identical rate?
I have gotten a single oled display (SSD1306) to work using the U8g2 library, however i am not sure which pins can be shared in a dual display setup. There are no CS pin on my displays, only GND, VCC, SCL, SDA, D/C, and RST.
thanks!

Those displays use I2C, not SPI.

Here is a link to the displays I purchased: http://www.ebay.com/itm/141494092860?ul_noapp=true
I have a single screen running using the 4 Wire SPI bus setup in the U8g2 lib, is that possible if the displays are I2C? I'm new to this, so honest question...

My bad. The labeling made me think it was I2C, but apparently it support both I2C and SPI. Since in 4 wire SPI, you can only write to the display, and not read, I don't see why you shouldn't be able to connect two displays. Just connect all six lines in parallel.


text:
Tiny RTC I2C module not working
I bought a Tiny RTC I2C module and it doesn't work.
When i run the TimeRTCSet from TIME library all i get is:
Unable to sync with the RTC
0:00:00 0 0 1970
0:00:01 1 1 1970
0:00:02 1 1 1970
0:00:03 1 1 1970
0:00:04 1 1 1970
0:00:05 1 1 1970
0:00:06 1 1 1970
0:00:07 1 1 1970

The module is connected like this:
Vin -> 5V
Gnd -> Gnd
SCL -> A5
SDA -> A4
I'm using arduino uno.
I tried with a simple i2c scanner, but it returned two devices!
Scanning...
I2C device found at address 0x50  !
I2C device found at address 0x68  !
done

Only the clock is connected. I tried removing the battery for night to reset it, but it didn't fix it.
Could you help me?

Could you please edit your question to include a link to the I2C RTC you are using.

The RTC module includes a memory module which is also addressable via I2C hence the 2 addresses. Have you tried sample code like here: https://www.elecrow.com/wiki/index.php?title=Tiny_RTC

Looks like the RTC is running correctly but has not been initiated with the current time?

This issue can be fixed by deleting the library downloaded using arduino library manager and replacing it with the library from github.

Try using the example code from the MD_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.

Thank you for help. I fixed the issue. It was caused by the library which I got from arduino library manager. I deleted it and downloaded the library from github. Now it works great.


text:
How to convert string to byte array on arduino
Well my title pretty much sums it up , how to convert string to byte array? i cant find any usefull code

You asked this already and I answered it here https://arduino.stackexchange.com/questions/58105/http-request-as-bytes/58106#58106

Well, the C string is already byte array.
If you mean Arduino's String class, then it has c_str() method.
Both needs reinterpret cast to const byte pointer:
byte const* byteArray = reinterpret_cast<byte const*>(yourString.c_str());

Yeah the Arduinos String , i did not understand the last line , i am sorry if i post stupid questions and i am new to all of this so i dont have experience

What did you ment by reinterpret cast to const byte pointer?

@Ivanh23 There is a difference between char and byte signedness so it must be cast by reinterpret_cast. I've added it into the answer.  But be warned, it's valid only as long as the yourString exists and wasn't changed. If you change the yourString, you have to get correct pointer again.


text:
Using usb port to communicate with standalone atmega328p circuit
noob here
So I managed to get my circuit to be a standalone circuit (as pictured below). I want to use this circuit as an input to a game on my computer. What I want to know is could this micro-usb breakout board https://www.diyelectronics.co.za/store/breakout-boards/2414-micro-usb-power-switch-breakout-module.html
 be used to communicate with the computer. Where would the data pins (d+/d-) connect to the atmega328?
Any help will be most appreciated

ATmega328p is not a right choice for a game controller. from the ATmega family ATmega32u4 would be better (Arduino Leonardo and Micro). it has native USB with HID capability. but it is not available as DIP package

@Juraj So I would need a breakout board for the ATMEGA32u4?

Arduino Micro is a breakout board for 32u4. Micro Pro is even more compact (without the ICSP header)

@Juraj Ah okay, I will consider this option: thank you.

as I read in comments that it is a controller for a game you develop, then you can of course implement a basic Serial communication between your sketch on Arduino and your PC application

@Juraj I wouldn't be able to use the Atmega328 though right? If I want serial communication?

not without an USB adapter chip

@Juraj okay in that case it might be better if I use bluetooth then. Thank you for your help

The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.
Assuming you are emulating an Arduino Uno, then something like this:
https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464
is what will come closest to mimicking the USB function on an Uno (ie a serial connection).
This shows how such a device would be connected:
https://www.jaycar.com.au/usb-serial-converter

Oh, so basically without a usb to serial adaptor, this won't be possible? Thank you for saving me time @user85471

Yep. Long answer is that there may be a software USB implementation that allows this but you're better to look at something like an ATmega32u4, which is what is on a Leonardo, but they only appear to come in surface mount packages (but breakout boards exist).

does the ATMEGA32u4 have native usb capability?  @user85471

Something else to think about, there are many USB protocols.  The linked to item in the answer likely uses a USB serial protocol.  Keyboards use a USB human interface protocol.  I assume gaming consoles which connect to computers using a USB port also use the USB human interface protocol.  So the linked to device may not work.

You need to look at the chip specifications here. In the specifications it says: "Complies fully with Universal Serial Bus Specification Rev 2.0".  However, note, that does not say what USB protocol is supported.  That is up to the software.  You need to do some leg work and figure out which USB protocol your game pad is using.  Or if you can use your keyboard as the gaming input.

@st2000 hmm these are all factors I hadn't considered, admittedly. Just to clarify, however, this circuit is the input to the game and the game is a game that I am developing. I am exploring communication types for my game and have explored bluetooth, now I want to see if i could use USB

Bluetooth like USB can contain many protocols. Listening to stereo, talking on the phone and using a keyboard all use different Bluetooth protocols.  You need to narrow your question down to the specific protocol your game will use.

@st2000 Also true. I have used the bluetooth module HC-06 before for a very similar project. How would I know what protocol that falls into?

I want to say "HC-06 Bluetooth serial..." which I just copied from the aliexpress web page.  Check this wikipedia.org page for a list of bluetooth protocols.  Most of the time, when people are creating projects, it is easiest to use the serial protocol embedded into Bluetooth or USB protocols.  But, as you might already know or have a feel for, sending music, for example, this way would not work very well.

There are way cheaper ones on eBay.
Search "USB Serial" on eBay.
In 2014, I used them without any issue.
You have to order few more than you need, because some of them are DOA.
It is an old question, still some people stumble on this question.