text:
Arduino reads string from another Arduino only if the string is in a loop why?
In my setup I have connected two arduino's Serially. An Arduino Mega is the on that is sending the string and a Arduino Uno is the one receiving it.

Arduino Mega : RX1(19),TX1(18) - Serial1
Arduino Uno : RX(10),TX(11)  - using SoftwareSerial
Gnd is connecetd on both boards

When I send a single string from the mega to Uno multiple times(In void loop)
I receive the string sent infinite number of times on the Uno which is to be expected:
Arduino Mega - Single string sent multiple no. of times
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
}

Now I want to only send the string a single time, so I inserted an exit(0) or an infinite loop after the delay that is always true.
Arduino Mega - Single string sent only one time
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
  while(true);
}

Arduino UNO - code is same for both cases
#include <SoftwareSerial.h>
SoftwareSerial s(10, 11);
void setup()
{
  delay(200);
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) ;  // wait for Arduino Serial Monitor
}
void loop()
{
  if(s.available()>0)
  {
     Serial.print("\nrec\n");
     delay(100);
     String b = s.readStringUntil('\n');
     delay(100);
     Serial.print(b);
     delay(40);
  }

}
Note : Arduino uno is receiving the string using : readStringUntil('\n')
But when I send the string only once I receive nothing on the Arduino Uno, can anyone help me figure out why this is happening
What I want to know is why the uno receives the string only when it's sent an infinite number of times and not when it is sent 1 time.
EDIT (July 8)
Still haven't got a solution that I'm looking for, if anyone needs any extra information to help me out please mention it to me.
EDIT (July 8-9)
Sorry it's my fault for writing Tx1 as 19  and Rx1 as 18 although I did not make the same mistake in the code.
When I pressed the reset button on the mega the string was received on the uno side.How did this happen?  Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string.
Why do I need to reset the mega in order to send the string , shouldn't it work when the serial monitor is opened?
Also I need the mega to send the string automatically without any forced/physical reset is that possible?
I'm asking this because sending a string is part of a larger code where values get updated as time goes by,and a reset will  reset all the values to their original state which I don't want happening.

A simpler way would be to put the print inside setup which is only done once.

that doesn't work either

My question here is not regarding how to print it once. I want to know why I am not receiving anything on the Uno when I only print it once. Even when I print in setup I do not receive the string on the uno.

Have you used the while(true) loop, without exit(0)? This is not completely clear

@chrisl yes I did. I tried once with exit(0) and checked if the string was received on the Uno , then I removed exit(0) and tried using while(true) and checked if the string was received on the Uno then I removed it and tried using goto statement and so on....

could use int cnt=0; in setup then change the pring to println(cnt);cnt++; this way you will see if you always are misisng the first string sent, or any ones after that.

two things to try: increase delay(), and remove delay()

Your posted code does not compile. Please do not post pseudo-code with stuff like "this OR that" in the middle of it. Post the actual code that doesn't work. Preferably one without exit in it. We can't be expected to debug pseudo-code.

In addition, post the entire code. Your snippet does not include setup which might have relevant information in it.

@NickGammon edited the question with relevant code.

How have you wired this up? I'm asking so I can reproduce it. One thing that springs to mind is a race condition. The Mega might be sending the string before the Uno is ready to receive it.

@NickGammon I have mentioned the wiring in the beginning of of my question. I will put up a diagram if that makes things easier.
You mentioned that it could be because of a race condition which is highly possible, but when I tried it - by inserting a delay right before the Serial1.println() it did not work. I tried various delay's up to 10 sec.

I can't reproduce that. With pin 18 (TX1) on my Mega connected to pin 10 (software serial receive), I get the expected message in the serial log if I reset the Mega (thus forcing it to send the message once). Note that you have pins 18 and 19 reversed in your question text.  When I said "how have you wired this up?" I was hoping you would actually show what was connected to where (or a photo). If you have 19 on the Mega connected to 10 on the Uno, then it definitely won't work.

@NickGammon You said you pressed the reset button in mega to force it to send once. How does that work. I actually just tried that now and it worked. Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string. Why do I need to reset the mega, shouldn't it work when the serial monitor is open? Also I need the mega to send the string automatically without any forced/physical reset is that possible?Since this is part of a larger code where values get updated as time goes by,and a reset just clears everything

If you want to ask a question about saving data into EEPROM then I suggest you make a new question. That is highly tangential to this one.

you are using an incorrect method for debugging .... do not send the same message multiple times ..... add a sequence number to each message so that each message is different

exit(0) is not the command to use, it is used to completely stop the program, although I'm not sure what happens exactly for an Arduino sketch.
To stop a loop (and continue, normally a break statement is used. This works inside a while or for loop and the sketch continues after the while or for loop where the break statement is executed.
Note, you also can start at the beginning of the while or for loop with the continue statement.

exit turns interrupts off and then goes into an infinite loop. Therefore any pending serial output is not done.

try putting a delay in the arduino mega code to make sure the uno is completely setup before it starts sending the data. I can see some delays in the uno code, so its possible that the arduino uno is not yet ready when the data is sent. Add a large delay, say 2000 to make sure uno is ready. Also there are neater ways to do this instead of just putting an infinite loop, unless the only goal of your program is just to send one string. You can use a flag that to disable sending.
bool isSent = true;

void loop()
{
  if(isSent)
   {
     isSent = false;    // set to false so we will never send again.
     Serial1.println("e2e4");
   }
}

Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string.
Why do I need to reset the mega in order to send the string , shouldn't it work when the serial monitor is opened?

Clearly there is a timing issue. When you open the serial monitor it resets the Arduino (in this case, I assume the Uno). So, the Uno resets, however the Mega doesn't reset because you didn't open the serial monitor there. Manually resetting the Mega forces it to send the data again (it would have sent it earlier when powered on).
In normal operation, of course you don't need to reset the Mega just to force a string "to be sent once". You have already proved that you can send a string many times, and sending a string once is clearly a subset of that situation. Sending n times is just (sending once) times n.
Your test setup, which requires powering both Arduinos at the same time, and then opening the serial monitor which resets one, but not the other, is what is confusing you. It is not that you can't send strings whenever you want, in normal operation.

exit turns off interrupts which will stop the serial output. I suggest something simpler like while (true);

i've already mentioned trying that


text:
Integrating Java program with arduino mega is it possible?
I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?
My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.
Note:
By integrate I mean that the Java program should run in the Arduino mega itself
Can anyone suggest a solution?

Do you want to run the Java program inside the Arduino, or do you want to use the Arduino as an IO device for a PC running the Java program?

@EdgarBonet I want to run the java program inside the Arduino.

Now click on the “edit” link just below your post and revise your question to make that clear. The question should be self contained, one should not have to read through the comments to understand it.

There is a project called uJ by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.
That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.
Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.
However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the dreadful excellent RxTx library for Java that works pretty fine after all, or the Firmata library.

source: Stack Exchange

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

sort: votes


text:
Reed Sensor matrix for chess board query
NOTE:
This is not a question that has been answered previously in similar questions.
I am using an arduino Mega
I have gone through Bergers Blog(schematic is in this link), but have been breaking my head on the logic of your sensor matrix, I have been breaking my head for the past few days on this one thing.

Initially he set all rows to HIGH then reset the 1st row to LOW to scan the reed sensors, let's assume that all the sensors in the 1st and 2nd row are closed.

My question is that since the 1st row is set to LOW won't it get shorted because the second row is initially set to HIGH?
Also, I used the same matrix as berger but instead I enabled the internal Pull up pins of all the 8 input pins, but yet again I faced the same problem of getting a short , since if a row 1 is set to LOW and row 2 is initially set to HIGH then One sensor in row 1 is closed and a reed sensor in row 2 below the sensor mentioned in row 1 is also closed. Then won't we get a short and random values show on the arduino.

Can you include the schematic in your question please? Things shouldn't get shorted because of the diodes.

@Nick Gammon,Aren't diodes used to solve the problem of ghost activation's.Also The  schematic is in the link.

The HIGH signal from the row can’t get anywhere because of the diode. Also, this matrix won’t work without the pull-up resistors.

@Gerben ohh ok..I understood but, won't the same happen to the LOW signal sent?

The LOW signal can get through the diode, and the de reed (if closed), to get to the column. It get then get through the reed of the other rows (if closed), but then can’t get any further because of the diode. Try printing out the schematic, and get some different colored markers, and try out the different scenarios, and see if you can get a short. Maybe that will help understanding it.

how do you know that you are getting a short between rows?

Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches.  For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing.  A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.
Adding a forward biased diode to every switch in a matrix prevents harmful shorts.  For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches.  However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased.  The diode connected to the row driven low would be reversed biased preventing the harmful short.
Using diodes on every switch is costly.  Most computer keyboard do not use this approach.  Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance.  In reality, almost all computer keyboard have an n-key-roll-over limit.  A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.
For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:

Mega has 70 inputs, 86 if you use a '2560 in a full breakout board.
I offer a couple of form factors to access all pins at http://www.crossroadsfencing.com/BobuinoRev17
Chess board will always have multiple pieces in multiple rows and multiple columsns pressed until near the end of the game. I'd wire up each square individually, make life a lot easier.  Read ports 8 pins at a time, 8 reads to have all 64 squares read.

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


text:
Arduino controlled by USB gamepad
I want to control my Arduino with USB gamepad. I know that exists library for USB keyboard for Arduino but I don't know any library for usb gamepad. I have PS3 styled gamepad. I dont want to use shield.
Any solution or help?

Does the controller act as a HID device?

Yes, Windows Device Managers says its HID-compliant game controller

If you've got a 32u4-based Arduino, I would start looking at the HID library, then.

and what model is your Arduino?

A USB host shield or mini board depending on your Arduino board should work.
https://github.com/felis/USB_Host_Shield_2.0
https://www.circuitsathome.com/usb-host-shield-hardware-manual/


text:
USB Mouse Passthrough
I am currently doing research for a project of mine. My goal is simple: I want to pass input from a physical mouse, to a microcomputer to process the input and modify, and send the input in the form of USB HID to a PC.

Mouse ---> Microcomputer (input modified) ---> PC

The Microcomputer preferably should be able to both send data to the PC (in the form of USB HID inputs as a mouse) and receive data from the PC.
I found the arduino Leonardo can act as a USB slave and emulate mouse movement, half of what I want. I need some microcomputer with capabilities to act both as a USB host and as a USB slave. I don't have experience with microcomputers, and I don't know how to find something with this feature.

Do you want to be able to change settings in the mouse from the computer? Can you explain what you want to modify? The mouse speed? Could it be possible to do this on the computer with a special driver? Which operating system?

I want the middleman computer to be able to modify the input to the main PC based on data from the main PC. A simple file pipe or something like that is enough for what I need. I assume it's possible with a USB controller in slave mode, because I've seen software based RGB keyboard controls, etc. However, in this case I don't need to access the mouse.

What do you want to modify? The mouse speed? Buttons? Auto-repeat?

I want to move a physical mouse, modify the movement in my microcomputer (e.g. multiply coordinates by two), then send it to the PC (the microcomputer will act as a virtual HID).

I'm not sure if that will work. A mouse does not know coordinates. If it is possible then it can be done on a linux computer as well without Arduino. I agree with the answer by @gdsports , attach a usb host shield.

Even in an incremental mode, the increments reported could be multiplied.

The cleanest solution to this problem would be to use an MCU with dual USB interfaces, one capable of being a USB host.   There are a few such parts in the STM32F4 lineup, and likely other brands as well, but not immediately clear if there are any with existing Arduino support.  Hardware wise, I believe you can do it with an inexpensive STM32F446 "Nucleo" board, though the pins of the USB interface are only available on headers, which you would need to wire to USB connectors.
A USB host shield is a possibility, but it's a bit "tacky" as a solution since it involves hanging a fairly sophisticated controller off a more primitive MCU, making an "upside down" architecture, and more expensive than an all-in-one solution, but it could be where you'll find the most existing code to support your effort.
One of the simplest things you could actually do would be to use a ps/2 mouse instead of a USB one, and interface that by bit-banging its simple serial interface.  Then you could use a board like a Leonardo or one of the Teensy series which has a customizable USB device interface, to present to the host computer as a USB mouse.

I was thinking about using a pi as USB host, then passing coordinates over GPIO to an arduino slave. But I feel like there will be input delay.

I like the nucleo as an option, I'm just worried that it may be too complex for me to understand, and I don't think I have the proper tools to solder on a header for usb (I have never purchased a small computer like this before).

It will indeed be challenging integrating the firmware - while a lot more capable, the examples also are far less turn-key than Arduino code.   In terms of attaching a USB port, what I did was to get a cheap USB extension cable, cut it in half, and crimp female header pins to it to plug into the board expansion headers (though watch out, the color code in cheap USB cables is usually completely wrong!).  These are all skills worth learning, but each takes time.  If this is the first time, you probably want to go with the host shield or the ps/2 mouse where you can stay purely Arduino.

thanks for the heads up. I found a nice little board while browsing adafruit, the Trinket M0 that i fcan couple with a USB host controller. https://github.com/gdsports/usb-metamorph/blob/master/README.md I found this github repo that has a lot of info about USB and stuff. I'm not even sure what the repo is about, I just skimmed over it, but the trinket m0 with USB host shield looks promising.

Hmm, while that combination might work, I worry that could bring the risk of the worst of both worlds; the atypical,only quasi-Arduino M0 platform, and the indirectness of the host shield.

The nucleo seems like my best bet. How do I research this further? What should I look for to determine if the computer has the functionality to work as a device and a host? It's not clear to me what I'm looking for in datasheets, etc. Thank you.

The hardware has the functionality, the issue is more that you'll need to do a lot of non-trivial software work, best case would be having to smoosh together two full example projects, figure out the semantics of handoff between them, wrangle a compiler more directly, etc.  Definitely worth the effort if making a product, less clear for a one-off and likely not if unfamiliar with such tasks.
Whatever you choose, start by getting each of hosting the mouse and emulating a mouse working independently.

Okay, thanks. It seems like I will need to actually order the device and tinker with it for a bit. I'm just wondering in general how I can tell which computer has what USB functionality. How did you figure out that Nucleo has this functionality? Was it through the SoC datasheet or something else? I'll probably be ordering a leonardo or something with the same SoC, just to get started with device emulation (i.e. slave device acting as USB HID).

So I found this: http://www.st.com/en/microcontrollers/stm32f446.html?querycriteria=productId=LN1875 We can see that there are two entries under USB, "USB OTG FS and USB OTG FS/HS", so I guess that says that there are two usb controllers capable of operating in OTG mode. Is this correct?

I know that I have already asked a lot, but how would i differentiate between USB ports and a USB controller? If I understand it is true that one host can have many ports, and multiple ports don't necessarily mean multiple controllers.

I hadn't recalled both being host capable, but that may be the case.  A given USB function can only support one connection, multiplexing is only possible by inserting hubs, which is not a complication you'd likely want here.

Plug a USB Host Shield into the Leonardo.
USB mouse --- USB Host Shield --- Leonardo --- PC

USB Host Shield Library
Circuits@Home Project
/*
 * USB Mouse pass through. Works at HID report level. HID report is not decoded.
 * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
 * trackball/mouse. This is a proof of concept so is not guaranteed to work with
 * all USB mice/trackballs.
 */
// USB host mouse from USB Host Shield Library. Install using Library Manager
#include <hidboot.h>

// USB device mouse library included with Arduino IDE 1.8.5
#include <Mouse.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
  Serial.print("MouseRptParser::Parse");
  // Show USB HID mouse report
  for (uint8_t i = 0; i < len ; i++) {
    Serial.print(' '); Serial.print(buf[i], HEX);
  }
  Serial.println();

  // On error - return
  if (buf[2] == 1)
    return;

  if (len > 2) {
    uint8_t mouseRpt[4];
    mouseRpt[0] = buf[0];
    mouseRpt[1] = buf[1];
    mouseRpt[2] = buf[2];
    mouseRpt[3] = 0;
    HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
  }
}

USB     Usb;
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("USB host shield did not start.");
  }
  delay( 200 );

  HidMouse.SetReportParser(0, &Prs);

  Mouse.begin();
}

void loop()
{
  Usb.Task();
}


text:
Methodology for designing/prototyping LED patterns
Several of my projects go through this time-consuming and tedious phase:

design a LED pattern for a geometry of WS2812 LEDs
implement it with e.g. FastLED
write to Arduino and see results
goto step 1

The second step, implementing different ideas in C with FastLED (or similar) takes a lot longer than I'd like it to. How is this step usually solved? Are there higher-level software solutions? Specialised idea-testing hardware?
I'd like to easily try out ideas such as "what if these four LEDs blinked magenta every second, while a gradient was cycling around the gradient over here".

Check out https://www.bhencke.com/pixelblaze . This runs on an ESP8266 and has a web interface. Here you can create your own animations using a, somewhat custom, scripting language. You can almost instantly see the results, and tweak till you get it right.

i setup my strip to listen to sockets, and I can push about 100 RGB levels about 15 times a second before it gets choppy. I can then use JS to preview effects i think up and code quickly. I have an example at http://pagedemos.com/wcz9t2xytf76/4 ; i don't know how exportable it is, but it might give you ideas...

Pixelblaze sounds like just what I'm looking for. Just ordered one. Thank you @gerben!

For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called FadeCandy, which allows one to send various patterns to a WS2812 chain using a protocol called Open Pixel Control.
Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.
Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.

I'm not sure if there are already solutions for it (high chance there are, maybe in some DMX 'simulations'), however, it shouldn't be too difficult to make your own.
Use a programming language you like which can handle graphics, use the same data structure as you would with FastLed, and let the software program (you write) show the pixels on a screen. This means you don't need any Arduino code.
If you split the filling of the pixels and the showing of it on the screen, you can copy the resulting 'filling of the pixels' code on the Arduino.
Update
Another solution, if you want to experiment with the actual WS2812, is to program all patterns you want to check with FastLed, and let inputs (via UART or fancy knobs/buttons/menu) decide what patterns (and properties) are executed. The key is to program the patterns in a flexible way (so use functions with parameters for each property, and states for which pattern(s) are executed or executed next if you want to check some sequence).

Sorry for my unclear question! I'd like to test the pattern in real life. I'm playing around with diffusors and optical fibers for LED artwork, so I'd need it to happen on the actual hardware

The step that takes too long time for a useful design cycle is implementing these relatively simple ideas ("blue bubble starting here") in C/FastLED. I'm imagining I can't be the only one looking to find a higher-level solution for prototyping this.


text:
Arduino not working on cell phone power bank
I'm trying to power my Arduino Uno using a basic power bank (5V/2.1A Output), the Uno lights up for around 20 secs. and then stops taking power from the bank. What can be the issue? Am I making a huge mistake here?
Further details:
1. The power bank has a LED that lights up during the charging process, it doesn't light up when I connect jt to Arduino though (but powers the Arduino for a short span, after which the Arduino goes off)
2. The power bank is 10,000 mAh, 5V/2.1 Amps, charges my cell phone normally.
Edit: As requested, adding a photo of the whole setup.

Please tell more. Add the extra information to you question. Can you make a photo? How did you connect it? When you power the arduino uno with a usb plug that has 5v, then it should work. Perhaps the powerbank is the problem?

@Jot Added the details as requested. Also, the Arduino is working fine when connected to a cell phone charger.

Maybe the power drawn is too few, and the powerbank is shutting down. Try adding some load to the arduino (e.g. a 100-150 ohm resistor between +5V and GND)

@frarugi87 Yeah, I suspect this too. I'll try your solution and update here.

@Kv07 just keep in mind that 100 ohm at 5V is 250mW, so a 1/4W of resistor is very borderline. If you have 1/4W resistors, maybe it is better to put two in parallel (for instance two 150 ohm in parallel will draw 65 mA, with a power rating of 150mW each)

@frarugi87 No worries, I have a 1KOhm resistor.

@Kv07 1k resistor will cause a 5mA load; try putting them in parallel, but I think you'll need at least 10-20 in parallel to have a "good" load. In any case, adding and subtracting 1k resistors you can find the value of current  you need to keep the power bank "up and running", if this is the problem

1kΩ does not draw enough current. Do you have a 5v relay (use the coil as a load). Powerbank: http://ambraneindia.com/product/p-1122 I read a number of reviews that say that it turns off when the phone is charged, and a apple watch can not be charged with it, because a apple watch draws not enough current. I can not find the specifications for the minimal charge current.

@Jot my apologies for not giving the spec sheet in the question itself. I think the minimal charge current is too high for the power bank.

@frarugi87 I only have 5 units of 1KOhm resistors and some basic sensors like Ultrasonic/DHT11/LM35 etc. Can we work out a makeshift arrangement?

Some power banks can be forced to keep on, by only consuming more current for short pulses. See https://arduino.stackexchange.com/questions/55193/keep-battery-pack-awake-and-run-motor-every-6-hrs . This would keep the powerbank on, but not use as much power, leading to a longer runtime.

@Gerben The power supply shuts off after 2 good hours of supply in the other question, in my case, the power bank hardly supplies for 20secs. However, to my understanding, a current drawn less than the minimum operational current should shut the power bank in a short while, as in my case. I don't know what's going on in the other question though.

hi again
5x1k = 25mA, which is roughly the same current the arduino absorbs, so I think you do not have enough current pulled out of the powerbank.
Maybe you can attach a USB port hub and recharge your mobile while powering the arduino... If this works then it was this problem, and we can try figuring out what is the best solution to keep it alive without mobile (e.g. modifying it, or using Gerben's solution to use short pulses to increase the average current...)

Voila! Attaching another power absorber (my cell phone in this case) caused the power bank to supply current continuously to both the Uno and the Cell phone. Infact, I took output of the power bank and plugged it back into the input of the powerbank, even that worked! Thanks for your help. If you could write this as an answer, I'll mark it as the accepted answer. Cheers!


text:
Servo doesn't work in 'for' loop running under 'if' loop
This is my first StackExchange question. I'm relatively new to Arduino and I am trying to tinker with the components and functionality.
I have a RGB LED coupled to my breadboard with a servo attached. The LED only shows Red and Orange for some reason(Why?), SO I mended my code as per the LED behaviour. The code prompts the user for a color, and depending on that, the Servo should rotate along with the LED lighting up. My servo functions well only in 25-165 degrees range. The code goes as,
Here's the code:
# include<Servo.h>
int i;
Servo n1;

String color;
void setup(){

Serial.begin(9600);
  n1.attach(6);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(6,OUTPUT);

}

void loop(){

Serial.println("Enter color: ");

while(Serial.available()==0){
}
color=Serial.readString();

if (color=="red"){
  digitalWrite(2,HIGH);

  for (i=25;i<=165;i=i+5){
        n1.write(i);
        delayMicroseconds(250);
  //}
  n1.write(25);
  delay(2500);
  digitalWrite(2,LOW);
}

}else if (color=="orange"){
  digitalWrite(3,HIGH);

  for (i=165;i>=25;i=i-2){
    n1.write(i);
    delayMicroseconds(250);
  }
  n1.write(25);
  delay(2500);
  digitalWrite(3,LOW);
}
}

So basically when Red is in, I want the Servo to go from 25 to 165 & come back to 25, and vice versa for Orange. But the servo behaves in 2 ways;
1.When Red is entered first, it turns some angle(I guess 25) and stays there, the programme doesn't even loop for further input of color for a long period. Then whatever the input goes, Servo stops rotating, only LED works.
2.When Orange is entered first, it goes again to the same angle as red, and mildly buzzes, but input is accepted and Servo is motionless.
I simulated the same setup and code in TinkerCad circuits, and the behaviour is the same, so no particular problem with the hardware there.
I'm relatively new to understanding the Arduino workings and Fundamentals, any help is appreciated.
Also, the circuit setup is attached.
Any help will be appreciated.
Thanks!

Can you please make a circuit diagram using the provided tools

for (i = 175; i >= 25175; i = i - 2) {

This was a typo in the code that I pasted before, I have re-pasted the corrrected and updated code again.

@JoeS I have updated the Circuit Diagram using TinkerCad for your reference.

Try using delay rather then delayMicroSeconds. I don't think 0.25 mS is enough time for the servo to move even a few degrees.

@ChadG That Worked! The Servo is now running perfectly. I have one question though, when I connect the Servo and the RGB LED to a common ground on the breadboard, the servo keeps on buzzing, even at 90 degrees. But when I connect it to the separate GND pin on Uno, it works good enough without jittering till 25 degrees. What can be the cause?

This section of code is never going to run. The for loop says that i starts at 175, and while i>=25175 then execute the n1.write(i) and subtract 2 from i each time it does this.
for (i = 175; i >= 25175; i = i - 2) {
      n1.write(i);
    }

From the arduino servo example page, n1.write() should only ever be from 0 to 180, as it is the angle the servo is at. So you go from 175 to 180 and it wont move past that.
//angle: the value to write to the servo, from 0 to 180

#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(9);
  myservo.write(90);  // set servo to mid-point
}

void loop() {}

of course it should be 25 not 25175. it is a copy paste error with no need to explain.

Actually, this wasn't the error that is creating the problem. As said by you,it's a copy paste error.

https://arduino.stackexchange.com/q/53814/47552 This is the actual corrected version of the question.

I have updated the code in the question, but it still doesn't follow the for loop sequence.


text:
Can't get deep sleep to work on Wemos D1 ESP8266
I have a Wemos D1 (ver. 2015-08) and I am trying to get it to sleep. I've managed to get it generally up and running/got wifi to work etc, but the deep sleep function is beyond me.
I tried connecting RX<-D0 pin to RESET, also tried with a 10k resistor. Neither worked. I then tried D2 (listed as gpi016 on the back of the board) to RESET, this also didn't work. Any ideas? It seems like this would be an incredible chip if I could get it to sleep. The example sketch below uploads fine and contacts the serial monitor, up until the point it sleeps.
 /* Deep Sleep - Blink
 *
 * Blinks the onboard LED, sleeps for 10 seconds and repeats
 *
 * Connections:
 * D0 -- RST
 *
 * If you cant reprogram as the ESP is sleeping, disconnect D0 - RST and try again
 */

// sleep for this many seconds
const int sleepSeconds = 5;

void setup() {
  Serial.begin(9600);
  Serial.println("\n\nWake up");
  pinMode(BUILTIN_LED, OUTPUT);
  // Connect D0 to RST to wake up
  pinMode(D0, WAKEUP_PULLUP);
  // LED: LOW = on, HIGH = off
  Serial.println("Start blinking");
  for (int i = 0; i < 20; i++) {
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(100);
  }
  Serial.println("Stop blinking");
  Serial.printf("Sleep for %d seconds\n\n", sleepSeconds);
  // convert to microseconds
  ESP.deepSleep(sleepSeconds * 1000000);
  Serial.println("sleep finished");
}

void loop() {
}

Could you say a few more words about what you actually observed, what you expected to observe, and how they differ? Have you tried disconnecting everything from the serial port of the ESP8266, as suggested by one tutorial? (Alas, this makes debugging much more difficult).

definitely you gpio16 (D2), as that is the pin that is used for waking up from deepsleep ... note Serial.println("sleep finished"); won't be executed after the chip wakes up, the ESP will basically shutdown, then reboot after deepsleep period ...

oh, GPIO16 is D0 on the weemos d1 mini  and D2 on the "non" mini ...why can't they just label GPIO16 as GPIO16!!!

One question about your board What board you must to select for the Wemos 2015-08 under arduino 1.8.5?? Wemos D1 R1 or Wemos D1 R2/mini???

If you need deep sleep, you should not use boards with USB-to-serial chips which cannot be sent to sleep. Think about using a "naked" ESP-12f and an external USB UART which only will be connected for programming.

I had to physically connect D0 to RST to wake up the wemos.

the confusion may be that ... D0 on the Weemos d1 mini is gpio16 ... D2 on the Weemos d1 is gpio16

Welcome.  Please be sure to take the tour at https://arduino.stackexchange.com/Tour

In fact it works well using a wire between D2 and RESET pins. But sending the program to the board, you must first disconnect these pin (the arduino IDE will send a hard reset during process, so this D2 reset must not be in place). When the program is uploaded to the ESP and start running, you connect D2 and RESET and it works well, ESP will go to deep sleep mode as expected.
Because it is not a mini, the board has another chip (usb) that will not got to sleep mode, so on my board it will use about 17mA in deep sleep (compare with 80mA in wifi normal operation). Still worth the trick.

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


text:
ESP8266 & Initial State
Has anyone been successful in connecting an ESP8266 to the Initial State IoT platform?
On the platform there is only one example with Cactus ESP. I tried it but it did not work because I have a NodeMCU.
Can you please share your Arduino code?

If you use the Arduino IDE Board Manager to install the support for ESP boards
an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.
This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.
The problem with the HubTest.ino code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor.  You don't have that so all the AT commands are not going to work.
However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example.  You need to look at how that code forms a connection and make HubTest.ino work in that way.  I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.

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


text:
Why is my servo spinning over 360 degrees?
I decided to try out my servo on my Arduino. I'm pretty new to this and I can't seem to figure out why this is happening. My servo will spin for about 5 seconds in one direction and then it will spin the opposite way for less than a second and pause for about 3 seconds. This is the code I uploaded to my Arduino:
# include <Servo.h>
const int servopin = 8;
Servo servo;

void setup() {
  Serial.begin(9600);
  servo.attach(servopin);
  servo.write(0);
}

void loop() {
  servo.write(0);
  delay(5000);
  servo.write(180);
  delay(5000);
}

I believe the servo is a Tower Pro Micro Servo 99 (either 9 might be a g) SG90.

An RC hobby type servo which rotates more than a full rotation is either a continuous rotation or possibly "sail winch" model, not an ordinary one.  Continuous rotation servos are typically made from ordinary servo chassis with the feedback potentiometer and associated stop removed, so they may be hard to visually distinguish by anything but model number and behavior.

pause for about 3 seconds ... and then what?

you only tried 0 and 180 ?  no experimenting of any kind??

How long does it take to spin 180º?

I might want to try decreasing the range, e.g. start from 10 instead of 0, or finish at 170 instead of 180. Here is an example:
# include <Servo.h>
const int servopin = 8;
Servo servo;

void setup() {
  Serial.begin(9600);
  servo.attach(servopin);
  servo.write(0);
}

void loop() {
  servo.write(10);
  delay(5000);
  servo.write(170);
  delay(5000);
}

After checking it works, try experimenting with different ranges to see how your servo reacts.
For me starting at 7 instead of 0 did the job.

When I am getting started with my Servo motor SG90, I have experience the same issue, and finally I have solved the issue. I have used external power supply for Servo and my Arduino with laptop USB port and control signal from Arduino to Servo motor make my Servo motor to spinning continuously.
Make sure ground reference of power supply of Servo motor and Arduino are same.


text:
Low-power detect rise and fall of input signal
For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).
I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).
Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.
I looked at monostable circuits but they only detect (generate a pulse) on rising.
Does anyone have a solution (which only costs a few uAmps) for this?
Thanks.
Addendum:
Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...
Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep >10mA (too much for battery).

Powerless or deep sleep may not make a sizable difference. Anything below 1 µA is less than the self-discharge of the battery. I have an ATmega running since 2012 off the same pair of AA cells, sleeping most of the time.

what generates the input signal? what is the voltage and available current, if any?

What board are you using? 10mA is quite a lot.

You can generate a pulse on any edge of a signal using some logic gates. For instance combining a rising edge detector with a falling edge detector and adding a time delay would probably achieve what you want:

simulate this circuit – Schematic created using CircuitLab
Simulate it here.
The length of time the pulse is on for is (roughly) defined by the time constant of R1 and C1.  That's T=RC, so in this instance 100 x 0.0000001 =  10uS.
for a time of (say) 30 seconds, you will want to massively increase those values. For example, 470uF and 80K would give you around 32 seconds.
Power consumption? Well, that's all dependent on the logic gates and how you build the circuit.  74HC chips are pretty efficient now (far better than the old 74LS ones), but you will want to reduce it down to as few chips and gates as possible. That means converting the circuit to just one gate type (for example NAND) and reducing redundancy in the circuit to minimise power consumption.

You can replace all the gates by a single XOR between the current and the delayed input.


text:
Connecting Arduino to a Peltier Module
I am trying to make a cooler using Peltier Modules, the Peltier Modules and the fans switch on when the Temperature sensor attached to the circuit reads above a certain threshold. But I know that Arduino can only handle a couple of MilliAmps as its functionality, in such a case, how can I control my 480W circuitry (12V/40A) using Arduino?
I'm very new to all this and will appreciate a detailed answer.
EDIT: To the best of my knowledge, this is not a duplicate of another question as the other question says I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno., whereas my application requires much larger current than that.

@gre_gor Edited the question to address your concern.

There are solid-state relays (such as this one) capable of switching the currents - 40A - you're talking about and may be a better choice than a mechanical one. Note that it will probably need to be mounted to a heat-sink.
You're Arduino then only needs to drive enough current to switch the relay. The example I gave above is not a recommendation as I've never used it; it's just the first one I found that is spec'd for enough more than 40 Amps to not be operating at its limit. I'm sure there are others as well.
The current it will draw from the Arduino is not specified; this is something you will need to find out about whatever relay you choose, to be sure it won't exceed the Arduino's 20 mA pin-driver spec. It is spec'd to require a heat sink.

When the relay draws more current, than the Arduino's pin can provide, you can simply use a small transistor to switch this current

You are correct the Arduino can only handle a few mA at 5V.  In order to do what you want you need to use the Arduino to switch relays that can handle the current.

Where can I get the relevant info to work with these relays? I tried looking up on the internet but the stuff was a bit too complex for a new tinkerer like me.

You are looking for one of the multitude of blue cubes that google will return if you search for "12V 40W relay".  The problem is narrowing it down to one that meets you requirements.  You have two connections on the logic side, + and -, which are your switching lines connected to the Arduino.  On the other side there are usually 3 connections, Com[mon], NO(Normally Open) and NC(Normally Closed).  With no voltage applied at the logic side the NO connection will be switched off, the NC connection will be switched on.  When you apply a logic voltage NO switches on and NC switches off.

The ratings/voltages are usually printed on the relay.

Make sure your check de DC rating, not the AC rating. DC ratings tend to be a lot lower.

@Gerben can you elaborate?


text:
Traffic signal simulation: A minor doubt
I am trying to simulate a traffic signal with a provision of a pedestrian button, that when pressed, stops the traffic for a while. Here are the conditions I'm trying to meet,
One green LED (on pin 10) lit for 3 seconds (the first LED to light up).
- Then one orange LED (on pin 11) lit for 1 second
- Then finally one red LED (on pin 12) lit for 3 seconds.
Two-colour light (pedestrian)
- The pedestrian light is constantly red (red LED on pin 9) and only turns green (LED on pin 8) once the button (on pin 2) is pressed.

On button press If the button is pressed while the car traffic light is green, the orange light is lit for 1 second, then the car
  lights turn red for 5 seconds during which the green pedestrian light
  is green.

After those 5 seconds, the pedestrian light turns red again and normal functioning resumes (car traffic light returns to green)
And here's my code for the same,
int status=0;    //mode:state of button pin
int buttonpin=2;//pin related to pushbutton
void setup(){
  pinMode(10,OUTPUT);   //Green LED to pin10
  pinMode(11,OUTPUT);   //Orange LED to pin11
  pinMode(12,OUTPUT);   //Red LED to pin12
  pinMode(9,OUTPUT);    //Pedestrian Red on pin 9
  pinMode(8,OUTPUT);    //Pedestrian Green on pin 8
}

void loop(){

  digitalWrite(9,HIGH);//Pedestrian Red is on
  status=digitalRead(buttonpin);

  if (status==HIGH){
    digitalWrite(9,LOW); //pedestrian red is off
    digitalWrite(8,HIGH); //Pedestrian Green is on
    digitalWrite(11,HIGH);//orange lights up
    delay(1000);//1second delay
    digitalWrite(11,LOW);//orange shut off);
    digitalWrite(12,HIGH);//red starts
    delay(5000);//5 second delay
    digitalWrite(12,LOW);
    digitalWrite(9,HIGH);
  }
  else{
    digitalWrite(10,HIGH);//green lights up
  delay(3000);//3 second delay
  digitalWrite(10,LOW);//green shuts off
  digitalWrite(11,HIGH);//orange lights up
  delay(1000);//1second delay
  digitalWrite(11,LOW);//orange shut off);
  digitalWrite(12,HIGH);//red starts
  delay(3000);
  digitalWrite(12,LOW);//red shuts off
 }
}

The problem is, the pedestrian button only works when it is already pressed at the time of Traffic Green starting(because of the if loop right there in code), but once Traffic green has already been green for say 1.5 seconds, it won't work as the if loop condition check has been already passed.
How can I mend my code to make the "On button Press" sequence explained above work at any time of the Green LED HIGH?
Attached is the circuit if the need be.

Edited code is:
#include <TimerOne.h>

int status=0;    //mode:state of button pin
int buttonpin=2;//pin related to pushbutton

void setup(){

  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  Timer1.initialize(100000);
  Timer1.attachInterrupt( buttonCheck );

}

void loop(){

  digitalWrite(9,HIGH);
  status=digitalRead(buttonpin);

  digitalWrite(10,HIGH);//green lights up
  delay(3000);//3 second delay
  digitalWrite(10,LOW);//green shuts off
  digitalWrite(11,HIGH);//orange lights up
  delay(1000);//1second delay
  digitalWrite(11,LOW);//orange shut off);
  digitalWrite(12,HIGH);//red starts
  delay(3000);
  digitalWrite(12,LOW);//red shuts off

}

void buttonCheck(){

   if (status==HIGH){
    digitalWrite(9,LOW);
    digitalWrite(8,HIGH);
    digitalWrite(11,HIGH);//orange lights up
    delay(1000);//1second delay
    digitalWrite(11,LOW);//orange shut off);
    digitalWrite(12,HIGH);//red starts
    delay(5000);//5 second delay
    digitalWrite(12,LOW);
    digitalWrite(9,HIGH);
    return;
  }
}

Will this work?

Reconstruct your code by ditching all those delay() calls (using delay isn't a good idea in almost all situations). Instead use non-blocking code with the millis() function. Refer to the BlinkWithoutDelay example of the Arduino IDE for this. Also it will be good to learn, how to code a finite state machine (sounds more complex than it is). There are plenty tutorials on the web for this.

While I agree that completely non-blocking code is better, for this purpose you could say, you have a "flow" which you want to "interrupt", so have a look at "pin interrupts".

you need a state machine to manage this behavior model

@Paul I have used interrupts in my code and edited the answer, will this work?

The cause of the issue, is the way you have implemented delay() in your sketch. It's true that delay() should be avoided 99.9% of the time, but it does have it's uses.
If you start with the BlinkWithoutDelay example that comes with the Arduino IDE, then add a counter variable and a switch statement, you can easily get the traffic lights "part" of your requirements working.
Adding the pedestrian button functionality using non-blocking code is more difficult (for me it's more difficult), but it's a problem easily solved using delay().
But what if you ever want your sketch to do more? What happens if you add another button to it? delay() is "blocking" code, so using it will probably "bite" you again if you try to add functionality to this sketch.
const byte buttonPin = 2;
byte secondsCounter = 0;
byte trafficLightState = 0;
unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;

void setup(){
  pinMode(10, OUTPUT);   // Green LED to pin 10
  pinMode(11, OUTPUT);   // Orange LED to pin 11
  pinMode(12, OUTPUT);   // Red LED to pin 12
  pinMode(9, OUTPUT);    // Pedestrian Red on pin 9
  pinMode(8, OUTPUT);    // Pedestrian Green on pin 8
  // I used a wire from GND to "buttonPin" as a switch.
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  // Get the current time.
  unsigned long currentMillis = millis();

  // If the button is pressed while the car traffic light is green,
  // the orange light is lit for 1 second, then the car lights turn
  // red for 5 seconds during which the green pedestrian light is green.
  if(trafficLightState == 0 && digitalRead(buttonPin) == LOW){
    digitalWrite(10, LOW);
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    Serial.println("Button Pressed. Orange light ON for 1 second, Pedestrian red ON.");
    delay(1000);
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
    digitalWrite(9, LOW);
    digitalWrite(8, HIGH);
    Serial.println("Red light ON for 5 seconds, Pedestrian green ON.");
    delay(5000);
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    Serial.println("Pedestrian red ON.");
    trafficLightState = 0;
    secondsCounter = 0;
    currentMillis = millis();
  }

  // Update the traffic light state every second.
  if(oneSecondTimer(oneSecond, currentMillis) == 1){

    secondsCounter += 1;
    if(secondsCounter > 7){secondsCounter = 1;}

    // Green traffic light.
    if(secondsCounter == 1){
      trafficLightState = 0;
      Serial.println("Green traffic light ON for 3 seconds");
    }
    // Orange traffic light.
    else if(secondsCounter == 4){
      trafficLightState = 1;
      Serial.println("Orange traffic light ON for 1 second");
    }
    // Red traffic light.
    else if(secondsCounter == 5){
      trafficLightState = 2;
      Serial.println("Red traffic light ON for 3 seconds");
    }
  }

  // Turn the traffic lights on/off as required.
  switch(trafficLightState){

    // Turn the green traffic light ON, pedestrian red ON.
    case 0:
      digitalWrite(10, HIGH);
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(9, HIGH);
      digitalWrite(8, LOW);
      break;

    // Turn the orange traffic light ON, pedestrian red ON.
    case 1:
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
      digitalWrite(9, HIGH);
      digitalWrite(8, LOW);
      break;

    // Turn the red traffic light ON, pedestrian red ON.
    case 2:
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      digitalWrite(12, HIGH);
      // Pedestrian green light ON ONLY if button was
      // pressed while the traffic light was green.
      // digitalWrite(9, LOW);
      // digitalWrite(8, HIGH);
      break;
  }
}

byte oneSecondTimer(unsigned long delayTime, unsigned long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

this code doesn't work the way problem has been specified.

What's it doing differently?

In your original sketch and the new one you've added using TimerOne, you turn the Pedestrian Green light on the first time the button is pressed and then you leave it on until the Arduino is re-booted. I didn't see that listed as one of your requirements. Are you sure that's what you want to do? Have the Pedestrian Green light on regardless of the traffic light color?

What my aim is, when the traffic light is green, if the pedestrian button is pressed, it follows this sequence: On button press If the button is pressed while the car traffic light is green, the orange light is lit for 1 second, then the car lights turn red for 5 seconds during which the green pedestrian light is green. Then the pedestrian light turns red back again and traffic light resumes its normal functionality. This is the problem in my (and your) code.

What happens when you press the button when the traffic light is green using my sketch? Is the output in the serial monitor correct? One more thing to check would be to verify the button and LEDs are wired correctly.

Well, I ran your code a coupe of days ago on Tinkercad, I don't remember the exact output your code gave but certainly remember that it wasn't what I wanted. I reckon the wirings were correctly done, you should try your code on Tinkercad too.

I tried it on an Uno and it worked perfectly.


text:
Communicating with magnetic sensor - TLV493D-A1B6 over I2C
I'm using the TLV493D-A1B6 sensor connected to an Arduino Uno: I've attached all necessary documentation at the bottom.
This is a 3D magnetic field position sensor that detects the magnetic field strength of a nearby magnetic field in the X, Y, and Z directions. I am NOT using the 2GO evaluation board. The sensor uses I2C protocol for communication.
I have this sensor all wired up, soldered correctly to a PCB with pinheadings, and ready to go on my breadboard.
Also, I am using a bidirectional logic level converter that is recommended for this sensor. I can confirm this as the I2C scanner sketch detects the sensor and prints out its expected defulat address.
Specifically, I am having trouble understanding the data sheets and how to setup Arduino using the 'Wire.h' library to communicate with the sensor over I2C to obtain the X, Y, Z RAW/decoded readings continuously.
I have tried code from this thread:
https://forum.arduino.cc/index.php?topic=419380.0
I have tried code from this dedicated tutorial for this sensor:
 https://www.allaboutcircuits.com/technical-articles/tutorial-and-overview-of-infineons-3d-magnetic-2go-kit/
I have even tried code from Github for this sensor:
https://github.com/IRNAS/TLV493D-3D-Magnetic-Sensor-Arduino-Library/blob/master/TLV493D/TLV493D.h
Using any of the above, I will get readings of "X=-1, Y=-1, Z=-1" or the sensor will output random readings of "255" and "0" when exposed to any magnet.
I've written my own code and have failed vigorously to get anything but random, clearly wrong readouts, this was my latest attempt, I chopped this code down for simplicity and clarity. I've also tried variations using the I2C.h master library, but no luck:
#include "Wire.h"

const int tlv_addr = 0x1F; // obtained by i2c scanner; all default address of tlv sensor - 0x1F, 0x5E, or 0x3E
const int config_reg = 0x00; // I have scene this in other examples of code for this sensor, I cannot find the "configure" or "command register" address on any of its datasheets
const int lp_mode = 0x05; //Have found this on the data sheet as the low power mode command
// Note: I switched from const byte to const int for HEX assignments because I get a warning when compiling the sketch about this and I found online that this is the solution?

void setup() {
  Wire.begin();   //join I2C bus
  Serial.begin(9600); //start Serial
  while(!Serial); //wait for Serial to be available

  Wire.beginTransmission(tlv_addr); //initiate communication with sensor
  Wire.write(config_reg); //set pointer/access configuration register
  Wire.write(lp_mode); //from what I read, the sensor defaults to power down mode on start up, so I send the low power mode command to the configure register to activate the sensor in low power mode which should cause it to start "sensing"
  Wire.endTransmission(); //end configurations
  delay(100); //delay to allow time for sensor the update
  Serial.print("Setup Complete\n\n");
}

void loop(){
  Wire.requestFrom(tlv_addr, 3); //request the 3 raw, UN-decoded bytes from the sensor's readings of X, Y, Z axes

  //---- Read in each byte of sensor data one by one for each axis ----//
  byte Bx = Wire.read(); //Have scene the "*" added to the beginning of the variable on a lot of code, not sure why this is necessary?
  byte By = Wire.read();
  byte Bz = Wire.read();

  //---- Print Out Sensor Axis Readings ----//
  Serial.println("X= ");
  Serial.print(Bx);       //Have also scene "&" added to the beginning of the variable on a lot of code like Serial.print(&Bx);?
  Serial.print("\tY= ");
  Serial.print(By);
  Serial.print("\tZ= ");
  Serial.print(Bz);

  //Expecting something like this: 01011011
  //Getting -1 or 255 or 0 randomly?

  delay(1000); //arbitrary delay
}

And furthermore, I understand that these values needed to be decoded to make sense of the actual data, I have no idea what is going on the register map sheet and why they are shifting different bits of segments of each byte, seemingly like totally picking the bytes apart then reordering them, and then casting them as integers to get real data?
I am very new to Arduino and especially to I2C. If you could please help me understand especially what I'm missing from the data sheet, or what I'm doing wrong in the simplest of terms, I want to intuitively understand whats going on at every step so I can do this again with another I2C sensor on my own. If anyone could please help me with this.

sensor:
https://www.infineon.com/cms/en/product/sensor/magnetic-position-sensor/3d-magnetic-sensor/tlv493d-a1b6/
datasheet:
https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6-DS-v01_00-EN.pdf?fileId=5546d462525dbac40152a6b85c760e80
Register Map:
https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6_3DMagnetic-UM-v01_03-EN.pdf?fileId=5546d46261d5e6820161e75721903ddd

In your code you read only the 3 first registers and write them to the variables Bx to Bz. These registers correspond to the correct magnetic values, but only the highest parts of them. The sensor measures 12-bit values - due to the higher precision - , but one register can only hold 8 bits. So the big 12-bit values are splitted into two parts. You will have to read all parts and put them together correctly to get meaningful results. Also the format of the values is a signed 12-bit value in two's complement, meaning that the decimal value is calculated by multiplying the value of the 12th bit with -1. You will have to convert this to a 16-bit two's complement for using the int type.
In the following part I will use the bitwise AND ( & ), the bitwise OR ( | ) and the bit-shifting operators ( << and >>). I will only shortly explain, how to use them. If you are not familiar with them, please refer to a proper C/C++ tutorial, which can explain this in more detail than this answer.

The bitwise AND will compair each bit of the left value with the corresponding bit of the right value. Only if both bits are 1, the corresponding bit in the output will be 1, 0 in every other case. I use it to mask some bits of the value away, effectively deleting these bits. Also note the different writing of literal values: In hexadecimal 0x0F or binary 0b00001111.
The bitwise OR will work as the bitwise AND, but will put a 1 into a bit, when at minimum one of the corresponding input bits is 1, and outputs 0 to this bit, if the input bits are both 0. I use this, to put all bytes of one value together into one variable.
The shifting operators << and >> will shift the bit values to one side. The bits, that are getting out of the values range are lost. On the other side zeros get shifted into the value. I use it for the proper alignment in bytes of a bigger value.

This is the important figure from the user manual. It tells you, that you will find bits 11 to 4 of the Bx value in the first register (11 is the most significant bit). The rest of the Bx value is to be found in the 5th register in the 4 most significant bits (bits 3 to 0 of the Bx value). So to get the correct values, we first need to read all the data (I will include the temperature here):
// Request 7 bytes from the sensor and return, if it didn't send enough (do not read, if there is nothing to read)
if(Wire.requestFrom(tlv_addr, 7) < 7) return;
// Read all registers to variables
byte bx_high = Wire.read();
byte by_high = Wire.read();
byte bz_high = Wire.read();
byte temp_high = Wire.read();
byte bxy_low = Wire.read(); // This has to be read together. We will split the values later
byte bz_low = Wire.read();
byte temp_low = Wire.read();

Now we put together the splitted values in one variable each. To avoid complications with types, I use unsigned int here, which is like byte, but containing 16 bit. For Bx we have to shift the high part 4 bits to the left, since the lower part needs 4 bits of space. Also we have to seperate the lower parts of Bx and By. Since the lower part of Bx lies in the highest 4 bits of the read value, we need to shift them right for alignment with the least significant bit. The rest works similar, but is a bit easier. The temperature value uses another alignment, but the principle is the same.
unsigned int bx_value = (bx_high << 4) | ((bxy_low & 0xF0)>>4);
unsigned int by_value = (by_high << 4) | (bxy_low & 0x0F);
unsigned int bz_value = (bz_high << 4) | (bz_low & 0x0F);
unsigned int temp_value = (temp_high >> 4) | temp_low;

Now we have packed the 12-bit values into 16-bit unsigned integers. We now have to convert them to 16-bit signed integers. But if we simply cast them, this would result in false values, since the complemented bit here is the 16th, not the 12th like in the sensor. For solving this we use the answer from this question:
int16_t Bx = (int16_t)(bx_value << 4) / 16 ;

There is one difference from the answer: We have a 12-bit two's complement, not a 14-bit one. So we have to shift 4 bits, not 2. This corresponds to dividing by 16 (a factor of 2 for each shifted bit).
Now you should have the correct measured values from the sensor.

You may have a second issue with your code. It read the registers every second, without regard to the state of the sensor. The datasheet says:

This sensor does not incorporate shadow-buffers for readout. Thus, it
  is mandatory to read the sensor data not during a running conversion
  to avoid corrupted reads.

So you might also get garbled values because you sometimes read the registers during the sensor writes in them. This may be not a great issue here (maybe it only happens once in a while). But you can circumvent this problem by either using the INT pin of the sensor for triggering a I2C read operation (at best via an interrupt) or by configuring the sensor to run in the "Master Controlled Mode", where it only does a new measurement, when the old values have been read from the registers.

This a great help and a tremendous amount of clarity, thank you so much for your answer.


text:
Feed values to an array using keypad interfaced with Arduino Uno
I am trying to input keypad values to an array. The code compiles without any error. When running the code, the code proceeds into the for loop and prints 'm' on the lcd, but doesn't execute "customKey = customKeypad.getKey();" and the below steps and keeps printing 'm' 5 times. I am not able to enter keypad values. Please help.
#include <LiquidCrystal.h>
#include <Keypad.h>

const int rs = A1, en = A0, d4 = A2, d5 = A3, d6 = A4, d7 = A5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, {
    '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } };

byte rowPins[ROWS] = { 13, 12, 11, 10 };
byte colPins[COLS] = { 9, 8, 7, 6 };

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,
    COLS);

//String inputString = "";
char customKey;
char a[5];

void setup() {
  Serial.begin(9600);
  //inputString.reserve(200);
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  if (Serial.read() == '1') {
    lcd.setCursor(0, 0);
    lcd.print("WELCOME !");
    delay(1000);
    lcd.clear();
    lcd.print("Enter UserID :");
    lcd.setCursor(0, 1);
    for (int i = 0; i < 5; i++) {
      lcd.print('m');
      customKey = customKeypad.getKey();
      delay(30);

      if (customKey) {
        lcd.print('*');
        a[i] = customKey;
      }
      if (i == 5) {
        a[i] = '\0';
        break;
      }

      delay(1000);
    }
  }
}


text:
Button Switch arduino
I'm trying to use my button as a switch (the led goes on after I push the button and the led goes off when I push the button again). I know I have the right circuit, because I also used a code from the internet, which looks really like mine. But my code doesn't work. The led doesn't go on. Does anyone know what is wrong with my code?
I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?
Here is the code i have written:
int ledPin = 8;
int buttonPin = 4;

int ledState = HIGH;      // the current state of the LED
int previousState = LOW;  // the previous state of the button
int readingState ;        // the current state of the button

void setup() {
   // put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
readingState = digitalRead(buttonPin);

if(readingState == HIGH && previousState == LOW){
  if (ledState == HIGH){
    ledState = LOW;
  }

  else{
    ledState = HIGH;
    }

digitalWrite(ledPin, ledState);
previousState = readingState;

}
}

and doing blink (using a time based trigger) works?

Yes I can get the LED blinking

Why don't you use the internal pull-up resistor? Did you use one externally? If not, your input is floating and the state is undefined.

I did use a pull up resistor

If you don't update previousState on each iteration, your outermost if statement cannot be true if previousState is high, if that's your question.

I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

previousState is set to high, and is never set again, so your if statement will never execute again because previousState is always set to high.
Moving the last line out of the if block sets previousState at every loop, and can then have a value other than HIGH, and then your if condition can be satisfied.
The penultimate line could stay in the if, or be lifted out, logically it shouldn't matter.


text:
Non-blocking MQTT library
Are there any MQTT libraries that do not block while connecting?
I'm currently using PubSubClient, and the connection part contains this code:
https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp

        while (!_client->available()) {
            unsigned long t = millis();
            if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
                _state = MQTT_CONNECTION_TIMEOUT;
                _client->stop();
                return false;
            }
        }

I'd like my main loop to continue, or a callback to be called, while the MQTT connection is established, rather than waiting for ages if the MQTT server is unavailable.
Update:
I wrote a modification to take a callback function, and called it in an else clause added to that if statement, and discovered that the blocking delay is not this while loop. I think it's in the _client->connect at the start of the method.

I had the same question and found an mqtt library that is completely non-blocking.

https://github.com/marvinroger/async-mqtt-client

You need to manually install it and the docs give instructions:

https://github.com/marvinroger/async-mqtt-client/blob/develop/docs/1.-Getting-started.md

It requires one additional library:

for esp8266: https://github.com/me-no-dev/ESPAsyncTCP
for esp32:   https://github.com/me-no-dev/AsyncTCP

I also liked the example's use of the Ticker library as a general tool for non-blocking code.


text:
using references to SFRs in gcc inline assembler
I want to write a driver that can use either timer0 or timer2, based on a choice made at compile time.
So I want all references to timer registers to be abstracted, e.g. OCRA for OCR0A/OCR2A, etc.
I could do it with plain macros, like so:
#define _CONCAT3(a,b,c)   a##b##c
#define CONCAT3(a,b)   _CONCAT3(a,b,c)

// set timer number globally
#define MY_TIMER 2

// define an alias for each control register
#define OCRA CONCAT3(OCR, MY_TIMER, A)

but for some reason I don't want to use macros there.
So I came up with this scheme:
typedef volatile uint8_t& tRegister;

constexpr volatile uint8_t& timer_register (volatile uint8_t& a, volatile uint8_t& b)
{ return MY_TIMER==0 ? a : b; }

tRegister OCRA = timer_register (OCR0A, OCR2A);

It works pretty well for all its awkwardness, but when I try to use this definition in an inline assembly directive, I get strange results:
asm volatile("lds r24, %0" : : "i"(&OCRA));

will get an error: impossible constraint in 'asm'
Now this:
asm volatile("lds r24, %0" : : "i"(&timer_register (OCR0A , OCR2A )));

will compile (and produce lds r24, 0x00B3 as it should).
By definition a reference to a static variable is a constant address, known at compile time, so I can't see why it can't be used in this context.
So my questions are:

what is going on there?
how to alias these registers (without macros) to please the inline assembler?

You could use pointers instead of references. With pointers, you have
the separate notions of “constant pointer” and “pointer to constant”. A
reference is a kind of pointer coated with syntactic sugar. However,
whereas you can have a “constant reference” (equivalent to pointer to
constant), I do not know how to declare a “reference with constant
address” (which would be the equivalent of a constant pointer). And
this is your issue: the "i" constraint in the asm statement requires
a constant.
Here is my take with pointers:
typedef volatile uint8_t * tRegister;

constexpr tRegister timer_register(tRegister a, tRegister b)
{ return MY_TIMER==0 ? a : b; }

// The `const' below is essential.
const tRegister OCRA = timer_register(&OCR0A, &OCR2A);

asm volatile("lds r24, %0" : : "i"(OCRA));

Of course, you then have to change all your OCRA = ...; statements
with *OCRA = ...;, which is awkward. But note that the avr-libc
defines the SFRs with macros equivalent to
#define OCR0A (*address_of_OCR0A)

If you want this convenience, you may have to resort to using similar
macros yourself.

Well thanks, but that's a workaround. I actually did something similar, but limited to the asm directives, so that I could at least use my reference aliases in the C++ code. I guess this fine docrine point about the difference between a reference and a constant pointer is just another small hole in the atrociously convoluted specs of C++ the poor guys who implemented the inline assembler fell into :D.


text:
SRF-02 UART, transmitting from one address to another
So I just starting playing around with UART and SoftwareSerial while playing with these SRF-02 Sensors - http://www.robot-electronics.co.uk/htm/srf02techSer.htm
I need help getting one to read to the other, I have been using this, makes sense logically, but doesn't work. I was thinking I'm missing something important for the synchronization of both sensors to one another.
Code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
  mySerial.write(cmd);//send the command to SRF02
  delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned int reading;
  SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from adress 0x00
  delay(70);//time for SRF02 to measure the range
  SendCmd(0x02,0x5E);//Get Range, returns two bytes (high byte first) from the most recent ranging to adress 0x02
   delay(10);//wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
  if(mySerial.available()>=2)//if two bytes were received
  {
    reading = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    reading |= mySerial.read(); // receive low byte as lower 8 bits
    Serial.print(reading); // print the reading
    Serial.println("cm");
  }
  delay(250); // wait a bit since people have to read the output :)
}


text:
What's the difference between DDRB and pinMode?
It's my understanding that the following lines are equivalent. They seem to be interchangeable in my sketch:
DDRB = 1<<DDB0;

and
pinMode(0, OUTPUT);

Is the first form (DDRB...) setting a micro-controller address directly? Is that assembler?
And is the second form (pinMode) using an included library? Maybe the avr/io.h library?
On a Digispark ATTiny85.

They are not interchangeable. DDRB = 1<<DDB0; sets PB0 to output, and it also sets every other I/O pin to input. It's not assembler, no. In assembler you would write sbi _SFR_IO_ADDR(DDRB), 0.

DDRB |= 1<<DDB0; would be equivalent to pinMode(0, OUTPUT);. The latter has the side-effect of being slower though.

@EdgarBonet if not assembler, what is it? C? Is it really the same language as pinMode(), just setting lower-level bits directly? thx

It is C (or C++, they are the same for this statement). The pinMode() form invokes a library function which does the same thing as the other form.

@EdgarBonet Did you mean to say,'......sets every other I/O pin of Port B to input"?

@MarsSojourner: Yes, indeed. DDRB only controls port B.

@EdgarBonet What if you want to set only bit 5 of Port B as an input? Would the programming syntax then be DDRB = 1<<DDB5; ?

@MarsSojourner: That would set PB5 as output and all the other PBn as inputs. To set PB5 as output without touching the other pins, use DDRB |= 1<<DDB5. To set it as input without touching the other pins, DDRB &= ~(1<<DDB5).

Yes, on a simple microcontroller like the ATTiny the two lines of code are equivalent.  The function pinMode(...) just looks up what pins relate to what ports in a table and set the right registers.
Using DDRB instead of pinMode(...) is fine as long as you are never going to run your code on anything else (or give it to anyone else to run), since you have now hard coded into your sketch what pins are to be used. It is more efficient to use DDRB though. You sacrifice portability for efficiency.
However, for more complex microcontrollers that have many many functions on a single pin, just manipulating DDRB (or the equivalent on the target microcontroller) may not be enough. You may need to switch the pin into GPIO mode, disable analog inputs on the pin, or other operations as well. All that will be wrapped up in the pinMode(...) function for you by the Arduino API so you don't need to worry about it.
So, in short, if you don't care about portability, and you do care about efficiency and code size (which may well be the case on an ATTiny) then yes use DDRB and its friends.

i understand that analogWrite() eliminates the need to enable output-mode completely -- neither DDRB nor pinMode() statements are needed. Is analogWrite() even less efficient than pinMode() + analogWrite()? -thx

The pinMode is redundant. PWM is a special mode that is not controlled by GPIO but a signal from a timer.

"as long as you are never going to run your code on anything else" --I assume the DDRB syntax is valid at least for the entire ATTiny line, if not beyond. No?

@johnywhy: It even works on the ATmegas. Note, however, that for setting pin 0 to output on an Arduino Uno you would use DDRD instead of DDRB, because pin 0 on the Uno is on port D rather than port B. With the pinMode() function you use the pin numbers that are printed on the silkscreen of the board, and you don't have to worry about the pin to port mapping, because the function takes care of this for you. You sacrifice efficiency for convenience.

@EdgarBonet yep, i understand the efficiency vs convenience tradeoff. Just confirming that the registers are, or are not, the same across the ATTiny family.

@johnywhy Have you heard of "datasheets"? All the registers and what they mean are in them...

I'm asking about your answer. You said "as long as you are never going to run your code on anything else", implying that no, the addresses are different even between different ATTiny's. Is that your intended meaning? thx

@johnywhy "anything else" even includes the same chip in a different board with different pins being needed to be manipulated. If you need to use pin B3 instead of pin B0 on a different board with the same chip you will have to change your code. Using pinMode, as long as both pins are numbered the same in the IDE, there will be nothing you need to change.

DDRB

is a register. Exactly: Port B Data Direction Register. See datasheet for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

DDB0

value was used.
Using this way of setting direction of a pin is much faster than  pinMode(0, OUTPUT);
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.


text:
Platform-independent functions for FastPWM?
I learned from answers here that pinMode(0, OUTPUT) is a platform-independent equivalent of DDRB = 1<<DDB0, on the ATTiny85.
Are there platform-independent functions for the following?
TCCR0A = 2<<COM0A0 | 2<<COM0B0 | 3<<WGM00;
TCCR0B = 0<<WGM02 | 1<<CS00;
TCCR1 = 0<<PWM1A | 0<<COM1A0 | 1<<CS10;
GTCCR = 1<<PWM1B | 2<<COM1B0;

Explanation of above code here. These calls enable FastPWM.
I checked the Arduino API reference, but not sure which are the equivalent to above. How to determine?

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_digital.c

It is highly unlikely there would be direct 1:1 functions that implement such discrete operations. Simply because such operations are pretty unique to a single family of microcontrollers. They are too low-level for an API to even consider wanting them.
Instead, there are higher level functions which may, if the chip requires it, include those operations.
The operations you list are all related to PWM, so the higher level function that would encompass them would be analogWrite().

Man, you're good! But, these fx are specifically to enable FastPWM. Any higher-level calls for FastPWM? thx!

Not that I am aware of in the standard Arduino API. We have them in the chipKIT API, and it's something we'd like to see adopted upstream, but alas not yet.

sweet! Chipkit is for programming AVR's with Java?

What on earth would give you that impression? chipKIT is for programming PIC32s with the Arduino API.

Why on Earth would you mention a pic library in an Arduino question?

It's not a library. It's a core. For the Arduino IDE. To implement the Arduino API. Like the DUE core or the ESP8266 core or the Maple core... OR... the ATTiny core. That's not Arduino. That's a third party core that implements the Arduino API. Exactly like chipKIT, just for a different architecture.

Ok, you mentioned ChipKIT API. i was not familiar with it. I assumed it had some relevance to this question. Your reply "What on earth would give you that impression" was unnecessarily disrespectful-- you spoke to me like i'm stupid. But i'm not stupid, i'm just unfamiliar with ChipKIT. No matter-- treating people like they're stupid is standard behavior for many people on stackexchange, including you too we see. Nothing unusual about it.

I was just surprised you got java from it somehow. I'd love to know the thought processes that resulted in Java...

i prolly saw java mentioned someplace in connection with chipKIT. My misunderstanding. http://chipkit32.github.io/chipKIT-core/core_how_to_hack_chipkit_core.html


text:
Reading SMS using Arduino Uno and SIM800L and print on LCD (16x2 alphanumeric) using serial connection NEED HELP
Well, I am making a device, which has to receive SMS and print the text using am LCD display. Now I have code that can receive SMS and store it into a string variable using serial connection.
Here is my code:
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;  //LCD pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
String Arsp, Grsp;
SoftwareSerial gsm(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(9600);
  gsm.println("AT"); //checking
  delay(1000);
  gsm.println("AT+CMGF=1");  //Set to Text mode
  delay(1000);
  gsm.println("AT+CNMI=1, 2, 0, 0, 0"); //Set to notification for new message, New message indication
  lcd.begin(16, 2);
}

void loop() {
  if(gsm.available()) {
    //Check if GSM Send any data
    Grsp = gsm.readString(); //Read data received from SIM800L GSM Module
    lcd.clear(); //Clear LCD Screen
    lcd.setCursor(0,0); //Set LCD cursor to First line, first row
    for(int i = 0; i<=100; i++) {
      //Print received string character by character
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(Grsp); //Print string which received from GSM (sms, sender, sms index, receive time, etc)
        lcd.print("        ");
        lcd.print(i); //Print the string index
        delay(500);
    }
  }
}

When my Arduino Uno is connected to PC and the Arduino serial monitor is already open,
it prints correctly this text received from GSM
"  +CMT: "+995599093230","","18/01/05,16:29:57+16"  0.

In this case I sent a message with text "0". When I disconnect the USB and connect my Arduino Uno to 9V power supply and send the same message text it prints:
"  +CMTI:  "ME", "+995598403536", 40)
In this case 40 is the index of the message received. I want to get the whole string as in the first case when the USB was connected.
I using Arduino GND and 5V to power the SIM800L. What I am doing wrong? Is this due to incorrect serial connection or incorrect code error?

What is your 9V supply?

Somethinf like this 9V Cell
https://www.google.com/search?client=firefox-b-ab&biw=1600&bih=777&tbm=isch&sa=1&ei=3bFPWvylDY3zsAG_h6uwBw&q=9V+cell&oq=9V+cell&gs_l=psy-ab.3...5364.6839.0.6980.0.0.0.0.0.0.0.0..0.0....0...1c..64.psy-ab..0.0.0....0.5s6BwlO-sC8#imgrc=0YK2n3P6ubCsVM:

Oh dear. Well, there you go then. Get a real battery or a mains power supply.

But fore some minutes  it works good, Is it real to get this problem using this cell?

Yep. Those batteries have almost no power.

And how can you explain me :)

I don't know how anyone can explain you. You're inexplicable.

It seems that you do not know exactly :D, and be carefull when are you commenting and see the screen every seceonds ;).

The PP3 batteries have around 154mAh. A typical AA cell has around 1500 to 2000mAh. Just a comparison. Add to that the fact that you're throwing away about half your power with the onboard 5V regulator...

Also asked at: http://forum.arduino.cc/index.php?topic=520835 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

The PP3 battery you are trying to use is far from powerful enough to run a SIM800L. It's barely powerful enough to run an Arduino by itself for more than a couple of hours if you're lucky.
The SIM800L, as the datasheet tells us, must be powered by a supply which can provide at least 2A.

The power supply range of SIM800L is from 3.4V to 4.4V. Recommended voltage is 4.0V. The transmitting burst will cause voltage drop and the power supply myst be able to provide sufficient current up to 2A.

The Arduino's on-board 5V regulator can't provide more than 800mA if you're lucky (far less if the incoming voltage is more than around 7V due to heat dissipation). Running from USB may allow peaks of up to 2A on a DCP USB socket without the Arduino's PTC fuse blowing.
A typical PP3 battery has an impedance of 1.7 ohms. That means a dead short circuit across the terminals would theoretically allow 9/1.7 = 5.2A maximum ever to flow. That kind of current would dissipate about 46W in heat inside the battery causing it to explode. Also at that current, given the typical low capacity of about 154mAh, the battery would be flat within about 100 seconds.
The maximum rated current for one of these batteries (at least, the maximum current shown on any of the graphs in the datasheet) is 250mA.
You need to power your SIM800L in a completely different manner, including two important things:

You need a power source that can provide 2A at the rated input voltage of your module (5V?)
That source needs to either be separate from the Arduino (except the ground, which must connect to the Arduino as well as the module) or if it is 5V may be used to directly power the Arduino through the 5V pin.


text:
Arduino is freezing after 10-15 minutes
I am having a problem with my Arduino freezing after a small amount of time. I'm using an RTC DS1307 breakout to keep track of the time and display the time on an LCD. It displays hours, minutes and seconds (updated every second).
Then I have 25V which is supplied by a transformer and connected to a set of LEDs through a CAT4101 constant-current sink LED driver. The Arduino board is powered by a 2amp USB transformer.
At a set time, the timer should set off the process to dim the lights.
Everything is working well if I set the lights to dim within a few minutes. However, if I leave the board on for more than 10-15 minutes then everything seems to freeze (i.e. the time on the LCD stops being updated and stays stuck at the moment it froze).
I originally thought it could have been something to do with my code. But I then skimmed everything down to the bare essential and just uploaded the code necessary to update the time on the LCD. And even in this case it freezes.
The only way I managed to avoid things freezing was to disconnect the CAT4101 pin 1 from Arduino's PWM and disconnect pin 2 from Arduino's 5V.
What could be causing this issue?
CAT4101
pin 1 = connected to Arduino PWM
pin 2 = connected to +5v
pin 3 = connected to ground
pin 4 = connected to ground with 2kOhm resistor
pin 5 = connected to LED cathode

UPDATE
Code below (I have stripped down the code by removing any additional functions and leaving only the bare code which is leading the application to crash).

#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal.h>

RTC_DS1307 rtc;
DateTime now;
LiquidCrystal lcd(7, 8, 9, 10, 11 , 12);

void setup() {
  Wire.begin();
  rtc.begin();
  lcd.begin(16,2);

 if (!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__)); // time = hh:mm:ss format, e.g. 06:01:01
  }

  lcd.clear();
}

void loop() {
  now = rtc.now();
  updateDisplay();
}

void updateDisplay(){
 int h = now.hour(); // Get the hours right now and store them in an integer called h
 int m = now.minute(); // Get the minutes right now and store them in an integer called m
 int s = now.second(); // Get the seconds right now and store them in an integer called s

 lcd.setCursor(0, 0); // Set the cursor at the column zero, upper row...
 lcd.print(" The time is: "); // ...with spaces to clear characters from setting alarm.
 lcd.setCursor(4, 1); // Move the cursor to column four, lower row
 if (h<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(h);   // Display the current hour
 lcd.setCursor(6, 1); // Move to the next column
 lcd.print(":");  // And print the colon
 lcd.setCursor(7, 1); // Move to the next column
 if (m<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(m);   // Display the current minute
 lcd.setCursor(9, 1); // Move to the next column
 lcd.print(":");  // And print the colon
 lcd.setCursor(10, 1); // Move to the next column
 if (s<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(s);   // Display the current second
}

In my opinion it is a small bug in the code. I can start saying random line numbers or.. You can put the CODE!!!

@Martin have you tried powered the CAT4101 with external source and not arduino? Try that and also place a capacitor in Vin as present in schematics of datasheet

Yes, code please, and LCD model number.

Does it still crash when running the blink sample code? If not, the problem must be in the code somewhere.

you are right guys, it's something in the code as the same setup still works with the simple "blink" sample code.
I have updated the post with my scaled down code, keeping just the core part which is still causing the system to crash.

Personally I'd avoid running it without delays. Just put a 50-100 ms delay between runs, or use the millis() function if you want to avoid the rest of the program to stop. Then I'd update just the fields on the LCD that I need, not all of them every time. So compare the h, m and s variables to the one you stored in memory and update them only if they differ. This will reduce the traffic on the lcd lines and reduce the possibility of a malfunction. And please, h, m and s will never be greater than 255, so PLEASE use byte, not int

Can you confirm that the problem still occurs with the CAT4101 not only excluded from the code, but disconnected from the circuit too? So you just have the LCD and the RTC module connected to the Arduino. Try the following, one at a time: [1] power it directly via USB, rather than by the 2A transformer [2] Ditch the RTC and have the LCD just update arbitrary numbers [3] Disconnect LCD and connect the RTC. After each rtc.now(), test if now.second() is the same as the previous call - if not then toggle the LED. If the LED stops blinking the program has frozen.

There is a problem with the library or the combination of the library and the Arduino system code. I have been running many tests now with only 1 line of text. After a few hours, I experience the same problem with a (20x4) display. I use different Arduino Mega's and displays so a defect in my hardware can be excluded. I also use 2 different power supplies 1 Is a lab supply hence the power supply can also be excluded. Using delay or millis() to slow down the refresh rated does not solve the problem (or may be part of it). If i find the solution i will post it here.

I would add a delay(100); to the bottom of your loop()
I'm betting even odds that solves it.