text:
How do I pass an Int Array into void for a foreach loop?
I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:
int example[] = {1, 2, 3, 4, 5};

void setup () {
    Serial.begin(57600);

    #define foreach(item, array) \
        for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)
    }
}

void Words (int w[]) {
    foreach(int *v, w) {
        Serial.println(*v);
        delay(500);
    }
}

void loop () {
    Words (example);
}

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?

The problem lays in sizeof array which can not be correct when foreach is called from Words(int v[])  function. If you put Words code directly in loop then it should work: did you check that?

Yes that does work, but I just want to be able to call from the void to save space and keep my code clean and more readable, I will be calling it many times with different arrays so to have many foreach loops is going to get rather messy.

Then your only option is to explicitly pass the array size (number of items) as an extra argument.

How is that done?

What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between
void f(int* array)

and
void f(int array[])

In particular, inside f() the compiler won't be able to know the actual size of array: for the compiler sizeof array will always be the same as sizeof(int*), i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.
If you want your foreach macro to work correctly, you have to pass it the actual array count of items as an additional argument:
#define foreach(item, array, size) \
    for(int keep = 1, \
        count = 0;\
        keep && count != size; \
        keep = !keep, count++) \
    for(item = (array) + count; keep; keep = !keep)

And also pass the count of items in Words:
void Words(int w[], size_t size) {
    foreach(int *v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

In loop() you can use sizeof example, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):
void loop() {
    Words(example, sizeof example / sizeof example[0]);
}

You could even define a macro to compute the count of items in an array:
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

It will work as long as you use it with an argument that is completely known by the compiler:
void loop() {
    Words(example, ARRAY_SIZE(example));
}

Important comments on your original code
You mentioned that you want to "save space", but defining a macro will not help in this regard, as a macro is NOT a function, hence its binary code will be repeated everywhere it is used. It can just help make your source code shorter and possibly clearer.
The way you defined your macro seems weird and overly complex to me: why use 2 for loops when you need only one?
It would have been possible to define it in a simpler way, for example:
#define foreach(type, var, array, size) \
    for(type* var = array; var != array + size; var++)

It would be used as follows:
void Words(int w[], size_t size) {
    foreach(int, v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.

Adding to the reasons why it's a bad idea to define that macro:

If you want to keep your code readable, inventing syntactic sugar and implementing it with macros is the wrong way of going about it. If the language designers did not do provide a construct, there is probably a reason. This is particularly true if you are not a complete master of the language.
Premature optimization is always a bad idea. First, modern compilers are very good about optimizing stuff. Second, unless you have measured the performance of your code in great detail and deemed the performance unacceptable, you are wasting effort and making the code harder to maintain. Third, what you think may be an optimization may result in worse code in a future version of the compiler, or in a different hardware architecture. The list goes on.
Never use preprocessor macros unless there is no other way of doing what you want to do (there usually is). There are countless articles detailing why you should not, but here is a short summary: macros pollute the global namespace, are hard to test and thus hard to debug, have no type checking, introduce subtle (and not-so-subtle) bugs, obscure calling semantics, and generally make the code unreadable. That we are having this discussion here is proof enough :)
In this particular example, you are relying on the fact that the array example[] is defined (meaning: declared and storage is allocated, and in this case initialized, for it) in the same translation unit as your macro. Had this not been the case, sizeof would not have worked
If you want to inline code, use inline functions. If you want to define constants, use const. And so on.

In your case, you are far better off declaring your arrays as vector<int> and using either iterators or the range for in combination with auto type declarations:
#include <vector>
std::vector<std::vector<int>> example = {
  {3, 1, 4, 1, 6},
  {2, 7, 1, 8, 2, 8, 1, 8},
  {5, 7, 7, 2}};

...

  for (auto v: example) {
    for (auto i: v) {
      // do something with i
    }
  }

Isn't this a lot more readable than your foreach macro?
Needless to say, you need to make sure that your tool chain supports C++11; the 1.6.7 version of the Arduino IDE running on Linux definitely does.
Obviously, there are occasional reasons to break the rules I mentioned above, but until you know exactly what you are doing, it's better not to.


text:
Is it possible to have an array of int arrays?
I have a huge number of arrays, each with a series of numbers each referring to an LED on a strip. I want to be able to address each one by a number, so the logical solution to that for me was to make the whole thing into an array. Can that be done, or is there a better work around that can be implemented?

Yes t is possible: you should take a look at http://www.cplusplus.com/doc/tutorial/arrays/ and search for "multidimensional arrays" there.

My word, my mind is blown. Thanks for that @jfpoilpret. I'll see what I can do with that.

I have question. What if wee have array a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; and then use another array to gather arrays before defining, za[] = {a[], b[]};
or za[] = {a, b};
I try it before with led array, who another person defining letters as binary code, and I was trying update that code and use next array to store set of letters which will use defining arrays from rows with binary code.

Yes you can have arrays inside arrays.
The array would be declared as:
int arrayName [ x ][ y ];

where x is the number of rows and y is the number of columns.
The example below declares and initializes a 2D array with 3 rows and 10 columns:
int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

To access the value of 27 (and save it into myValue):
myValue = myArray[2][6];

What if I want an array of pointers to arrays?

https://stackoverflow.com/q/11363226/6075112 and https://stackoverflow.com/a/936702/6075112

It would be worth adding than this 2D array is actually an array of 3 arrays of 10 numbers. Not all programming languages use row-major order.

source: Stack Exchange

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

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

sort: votes


text:
Arduino struggling to power a large LED strip
I'm building a word clock and its a grid of 20x20 letters, each with its own LED (I know, its absurd for just a clock). I've recently got the LED's on a strip. Its the WS2812B type, just like the neopixels. There are 3 rolls of 5m strips and a single 1m strip. When I tried to power the 1m strip, everything worked perfectly and all looked quite lovely. But when I tried the 5m strip (just one of them), this happened: https://www.dropbox.com/s/5w1lok6wa7dfvzd/IMG_0046.MOV.mov?dl=0
If you didn't see the video I recorded of it, for a second or two after powering the arduino (uno) on, it works as expected but not long after it all stops the colors and fades to red, sometimes it just instantly jumps to it, like the second time in the video. I don't know what happened but all I can guess is that the arduino is not able to power the strip properly. Any ideas on what I should do to be able to power a total of 16m of these strips?

Each LED needs 60mA. Do the math.

So that would be 24 amps right?

And now you know why they don't use 2812Bs for it.

So how in the world would I go about carrying that out?!

Use discrete RGB LEDs, and restrict them to 4mA per color. It will still be a lot of current, but far less than full 2812Bs.

I've already got the 2812Bs so it would not be ideal to change them, what can I do to make it work with what I have?

Don't run them with values higher than 50 per channel. That should keep the total current below 5A. Which will still require you to power them externally.

Alright then, so heres my thinking. The grid is 20x20, so if I have a power source every for every 2 rows (each one being 20 LED's so a total of 40 LED's for every power source). What do you think of that?

That will work, but it will still be 10 2.5A supplies.

Yeah, seems like the best option though, unless you have any other ideas I think I will have to go with that.

I'd still run them lower than full brightness. Most people can't tell the difference between 230 and 255 unless they're right next to each other, and even 100 is still decently bright.

Thats a good point actually. If I did that, is it easy to work out how much power it would need if the brightness were lowered?

The LEDs use PWM, so it's approximately linearly proportional to the value used.

Thats good to know, well thanks for your help, hopefully it will work!

@MatthewInglis according to the internet (http://web2.murraystate.edu/andy.batts/ps/PowerRatings.htm) a 250watt computer power supply would be able to supply 25A on 5V.

@MatthewInglis Just be warned that 1) with a duty cycle of 50%, instead of 24A you will have a 12A AVERAGE current; while this is the right value to pick for thermal considerations, if your power supply is not rated for 24A peak it won't work properly (because the instantaneous current will be always 24A). 2) using an ATX power supply can seem good but you COULD have some problems due to the fact that they expect some load on every rail. Usually the feedback rail is the 5V, so it should be sufficiently stable, but... Well, a dedicated 5V 25A power supply is better

WS2812 use around 1mA when they are off. So that's already 400mA with no LED lighted. USB can supply around 500mA. So you only have 100mA available.
Each led package has three colored leds inside; Red, Green and Blue. Every color will use around 20mA when fully turned on.
So you can only turn on 5 colors at full brightness at 500mA.
Using a 2.5A supply you could go up to 105 colors, or 35 leds full white.
This would be more than enough for a word-clock, as most leds will be off.

Thats not enough for our word clock, as I said in the description our clock is 20x20, which is 400 LED's

The point is that you aren't lighting all leds at the same time. The word clock is quite useless if all leds are on all.

You're trying to power a consumer which draws more current than the arduino could provide.
To fix this, you need an transistor and a ~5V battery (e.g. 4.8V NiMh, or a stronger batteries plus suitable resistors, to not burn out the leds)
Look at this (awesome paint) shematic to understand the principle.
The arduino will switch the transistor through S2 which then closes the circuit.
Through S1, the arduino can set the LEDs values.
Note that for savety, you should also set a diode between S1 and the LEDs, so the battery cannot burn out your arduino, if the LED strip is cheap made.
The reason why the behavior at your setup differs might be because of a capacitor on the arduino which works similar to a batterie (With extreme little capacity).
The capacitor might provide enough power to run the LEDs for a very short periode. After discharging, the capacitor needs some time to recharge and thus it may vary in effect.

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


text:
How to write modular code for arduino?
I would like to create a program with separated modules, is this this possible using Arduino IDE?

Also see https://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control

While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.
Specifically, in the Arduino IDE create a new tab with some name foo.h, and in your main tab, add #include "foo.h" at the top of your code. What this does is essentially copy paste the code from foo.h into your code during the build process. While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.
You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."
And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as delay() or Serial unless you add #include "Arduino.h". However, for IDE versions less than 1.0, use #include "WProgram.h". This will give you access to those functions.

Arduino sketches can include Libraries (see https://www.arduino.cc/en/Guide/Libraries).
In order to work with the Arduino IDE, such a library is required to adhere to a certain folder structure and naming convention (as described in the above guide).
Other than that, it's similar to modularized code in any other language. The canonical language in Arduino libraries is C++.
Since a regular Arduino IDE installation already comes preinstalled with a multitude of libraries, you can take a look and go from there.
I recommend that you look through the example sketches (from the "Examples" menu option). Whenever you see an #include statement at the top of the sketch, you have a hint where to look next in order to gain a better understanding about the inner works.

The sketch code can be easily split into several files by creating a new tab (file) without file name extension or .ino (source). No need for #includes as the Arduino IDE combines these files for the build process.
For proper modularisation make a Library or see the link above for further information on using .h/.c/.cpp as modules.

I would like to create a program with separated modules, is this this possible using Arduino IDE?

the answer depends on your code.
writing modular code is mostly a thought process:
1) you have to design your code to a logic model: rather than setting an led on pin 2, you design your code to set a pin, use that code to set a pin specified as LED_PIN, and then define LED_PIN to be pin 2. With this approach, you can simply redefine LED_PIN in your new project to use the same code.
2) you have to design your code top-down: rather than start writing your code right away, break it down to logic blocks, design the input and output of each block so that they work together cohesively. this is the toughest part of writing modular code.
after that, breaking the code down to .c/.h files is a piece of cake.

Well.... The answers are interessting but depend on what JuanV is thinking about when he say "separated modules"...
For me, as an "old timer software dev", "separated modules" mean I build a central bloc of code (a nutshell) and the user download module which are automaticly "plugged" to the nutshell, expanding the feature.
A bit like a printer driver you add to your system, and which add feature for all software.
When I look at my past dev using this, I must admit I've some problems thinking of that on Arduino.
If you are looking for that you must think about various problems:
1) how to update? Maybe with an Android App getting the code from the Web and sending these data to the Arduino via Bluetooth. You can also think of adding a Wifi interface on the Arduino
2) where to store the new piece of code... It's seem you can write on flash "on the fly" but seems to be complicated
Due to this second point, maybe the easiest way would be to create a nutshell which will "interpret" data (so which read a kind of small script) and then you'll have just to send the data.
I suggest to have a look at the CNC made with Arduino. In most cases they use a  GCode interpreter. GCode is a descriptif langage for CNC machine. So the interpreter read the code and according to the code, send "orders" to the machine.
Maybe such a thing would be a good starting point.
On the other way, if what you call "modular approach" is just the way of building lib and re-use them, Lord Gonk answer is the way :)


text:
What NRF24L01 module is this?
I received my NRF24L01 Module today but I'm having a hard time finding any resources about this particular combination of modules!
https://i.sstatic.net/Tiwyj.jpg
I tried searching up the v200 1812A but no results...You would think the seller would have some documentation on his page but nothing.
Does anyone know what I'm dealing with here?
Thank you!

What numbers are on the chips?

@Majenko Both the modules display the same V200 1812A, the only slight variation is that one says WSCOM and the other WSUSB

I asked what is on the CHIPS not on the MODULE.

Excuse me, the WSCOM module has a chip with the markings (ST MICROELECTRONICS) 78754 32F03DF4O6 PHL B17 A

That sounds like an STM32F0 ARM M0 chip?

I highly doubt it. You can see the sheer difference in size and pins on the chip

The actual number is not what you read (it can be hard to distinguish some letters / numbers), but is 32F030F406.

They are transparent bridge modules that are designed specifically to work together. It's intended to be kind of like a wireless UART.
This AliExpress Seller details how to use them.
You need one UART and one USB module. You plug the UART module into the USB module and plug the USB module into your computer. After about 10 seconds the modules are paired together.
You then separate them, and you can connect the UART module to your Arduino or other board.
Now you have a wireless UART between your computer and your Arduino.
Alternatively, since they have an STM32F0 chip controlling them you could hack them to do other things using stm32duino.

Ah thanks! Is an Arduino library available to work with it? That's all whats left what's keeping me to work on it!

To use it as is there's nothing to "use". You just plug it in (once it's paired) like you would an FT232 cable.

So wait, I can't connect this to my arduino? I thought that I would've been able to communicate between my pc and my arduino... Even that seller page never mentioned the usage of an Arduino

Once paired you connect the UART portion to the Arduno. Like you'd connect the TTL UART side of an FT232 cable to the Arduino.

Alright, 1 last question. Since the breakout of the UART module differs alot from the "standard" NRF24l01 module, how should I connect the RXD and TXD part of the WSCOM module to my arduino? I dont suppose I can just hook it up to my Arduino Micro's RX and TX?

If you're not using them for the USB interface then yes, you can. Or to any other pins and use SoftwareSerial. It's. Just. Serial.

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


text:
How to perform two tasks in one loop in Arduino?
I am trying to make a weather monitor using Arduino. I want my weather monitor to send me a message of the weather data every 5 hours using GSM sheild. Also, there is an LCD on my weather monitor which shows live weather conditions. The problem I am facing is that the delay of 5 hours in my code also applies to the LCD which updates the LCD every 5 hours and not every second as it should. Please tell me how to run these two functions simultaneously.

see the BlinkWithoutDelay example

Here is a simple abstraction (Timemark) that makes it very easy to write. https://github.com/mikaelpatel/Arduino-Timemark/blob/master/Timemark.h

please post your code

Consider using a finite state machine to track multiple tasks.  Specifically, the state in which you send your message once every 5 hours.  And, the state you update your LCD, perhaps once every second.
As your tasks are associated with time, consider using the built in Arduino call to millis() to find how many milliseconds the Arduino program has been running.  This will not block your program.  Instead it will immediately return with a number you then need to manage.
To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay.  Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number.  Use this to drive your state machine.  Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).
Note, millis() will eventually roll over as it is of type "unsigned long".  That is, it will roll over once about every 50 days.  If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.

note: the BlinkWithoutDelay example "accounts for the roll over "

Something along the lines of this pseudocode should help you.
unsigned long weatherUpdate; // Use unsigned longs for millis times
unsigned long screenUpdate;  // You need to worry about wraparound less often
unsigned long timeNow;

setup {

  unsigned int interval1 = 0; // 0 Should be whatever delay you need
  unsigned int interval2 = 0; // 0 Should be whatever delay you need

  updateScreen();
  screenUpdate = millis();

  updateWeather();
  weatherUpdate = millis;

}

loop {

  timeNow = millis();

  /*
     These if statements are true when the interval between the current time
     and the last time the if ran is greater than the required interval. For
     organization purposes, maybe create separate functions for when you
     update your screen and weather functions instead of just replacing
     the function stubs I've included.
  */

  if((timeNow - screenUpdate) > interval1){

    updateScreen();  // Do what you need
    screenUpdate = millis();  // Update time since last run

  }

  if((timeNow - weatherUpdate) > interval2){

    updateWeather();  // Do what you need
    weatherUpdate = millis();  // Update time since last run

  }

}


text:
Can I connect an Arduino GSM Shield directly to a PC?
Is it possible to communicate with and use the GSM shield directly from the computer, without using an arduino board?

You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

Power
  It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.

thanks. A follow up: I'm assuming I wont be able to use the existing Arduino libraries (gsm, softwareserial). Do you know of any that I could use?

@sferaud A GSM shield is usually be controlled as a modem using AT commands. You don't need "libraries" to make an operating system control a modem. You may need an "application" or maybe a "driver" but never a "library".

Actually that depends a bit if you want the operating system to treat the modem as a general purpose network interface, or if you want to use it more explicitly, similar to how it would be used by an Arduino.  In the latter case library code (maybe even Arduino stuff backported to processing?) could be an option.


text:
Arduino GSM Shields stacking
I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

Yes, that is easy. You need multiplexer (MUX) to forward communication pins (2 & 3) to the right GSM shield. Google for it to find the one that suits your budget.

Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The product page says each shield may require up to 1000mA.
Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.

Stacking might be hard, since they communicate on pins 2&3.  But if you work around that somehow, you could use Software Serial to access multiple GSM devices.
I think the GSM library has hardcoded the pins, and it might not share well with multiple, but you might be able to use SoftwareSerial or AltSoftSerial to do multiple connections, but that would be less straightforward.

authors: الأسطورة واو


text:
Timing taking longer than expected
This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.
https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png
^ So you don't have to look it up yourselves. previousMillis is initialized to 0.
However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.

Check F_CPU when compiling and your lfuse setting. See http://www.engbedded.com/fusecalc for a convenient tool.

Hey, sorry it took so long to get back. I'm using the arduino IDE, and I can't find the settings you're talking about in the preferences section, so I'd assume everything's fine on that front. I can turn compilation/upload to verbose and post that, if you think that would help.

Never mind, check the answer I just posted.

Arduino IDE has the fuses settings in boards.txt. Either you "Burn Bootloader" or use your programmer standalone with the avrdude utility.

Factor 8 in timing smells like wrong fuses.
Perhaps you don't use an external oscillator, but the internal one?

It's a factor of 20, isn't it? And I'm pretty sure that it's using the external 16 Mhz oscillator on the board, unless that has been damaged somehow. I also just noticed that the second board is showing a factor of 16, coincidentally.

I take that back about the second board. I just doubled the delay in the code and the observed delay stayed the same. I am very confused.

You're right: it's hard to get 8 from a 4 and a 5. (Not sure how I assumed 10/5 just to explain the smell/odor ;) But then, your question is even more a miracle.

On all of the new boards I had tested (excluding the first one that I said worked), I had not burned the bootloader. Burning the bootloader made the timing normal! If anyone can tell me why that's the case, I'll accept your answer as the "correct" answer.

Burning the bootloader also (usually) sets the fuses, as the particular fuse settings are specific to the bootloader. Thus DataFiddler's answer has the why, you have found the how to fix.

:) so you deserve a +1 as well ...

Awwww thank you


text:
Arduino box stops working: Reading RFID tag and sending data over network
This is a simple Arduino program which reads RFID tag and sends the data over a network (lora).
The program works fine in as i run it, the arduino reads RFID and sends it over the network (lora)
but
after a few hours it stops responding it neither reads nor sends the data over network (lora network).
I am very new to arduino and have no idea what causes the box to stop responding, kindly help.
When i restart the boxes or upload the code to it again, it starts behaving normally for a few hours and then goes back to not responding.
    /*
   Typical pin layout used:
   -----------------------------------------------------------------------------------------
               MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
               Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
   Signal      Pin          Pin           Pin       Pin        Pin              Pin
   -----------------------------------------------------------------------------------------
   RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
   SPI SS      SDA(SS)      10            53        D10        10               10
   SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
   SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
   SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
   Red LED                  A0
   Green LED                A2
   Blue LED                 A3
*/
/***********************************************************************************************/
//#include <SPI.h>
#include <MFRC522.h>
//#include <HID.h>

// Cooking API libraries
//#include <arduinoUtils.h>
//#include <arduinoUART.h>
//#include <arduinoMultiprotocol.h>
#include <arduinoLoRaWAN.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above
#define MAX             10         // Maximum Buffer size
#undef Debugg
/******** RFID Reader initialization**********************************************/
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
//char rfid_old[MAX];
byte *buffer;

/******************************LoRa Initialization********************************/
// Pin definition for LoRaWAN module error LED:
const int error_led =  7;
//////////////////////////////////////////////
uint8_t socket = SOCKET0;
//////////////////////////////////////////////

// Device parameters for Back-End registration
////////////////////////////////////////////////////////////
char DEVICE_EUI[] = "0000000097E471E1"; // 0000000097E471E1 / 00000000518AD184
char DEVICE_ADDR[] = "97E471E1"; // 97E471E1 / 518AD184
char NWK_SESSION_KEY[] = "00EBB4C1FCDFF52878B1725CBDFF0BA1"; // Configured for TTN
char APP_SESSION_KEY[] = "4EDC3AB4F79C565685109ECD4AF4604C"; // Configured for TTN
char APP_KEY[] = "70B3D57ED0000300"; //APP_EUI
////////////////////////////////////////////////////////////
// Define port to use in Back-End: from 1 to 223
uint8_t PORT = 1;

// variable
uint8_t error;
uint32_t cFreq[] = { 867100000, 867300000, 867500000, 867700000, 867900000 };
char rfid_arr[MAX];
char stampleErrorChar[] = "4AD6A6A65784AEBA2B"; // this data is sent from the WService When Stample Error-> Error
/* *******************************START Initialize Indication LEDs******************************* */
int greenPin = 6;
int redPin = 8;

void setup()
{
  Serial.begin(57600);
  //LoRaWAN example - Send Unconfirmed packets (no ACK)
  pinMode(error_led, OUTPUT);
  digitalWrite(error_led, LOW);

  LoRaSetup();
  RfidSetup();
}

//-----------------------------------------------------------------------------
// Name.: RfidSetup
// Descr:
//
// In...:
// Out..:
// Ret..:
//-----------------------------------------------------------------------------
void RfidSetup()
{
  SPI.begin();                        // Init SPI bus
  mfrc522.PCD_Init();                 // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
}
void LoRaSetup()
{
  LoRaWAN.ON(socket);
  LoRaWAN.factoryReset();

  // Channel parameters
  for (uint8_t i = 3; i < 8; i++) {
    LoRaWAN.setChannelStatus(i, (char*)"on");
    LoRaWAN.setChannelFreq(i, cFreq[i - 3]);
  }
  for (uint8_t i = 0; i < 3; i++) {
    LoRaWAN.setChannelDutyCycle(i, 302);
  }

  for (uint8_t i = 3; i < 8; i++) {
    LoRaWAN.setChannelDutyCycle(i, 99);
  }

  LoRaWAN.setPower(5); // [N/A, 14, 11, 8, 5, 2] dBm
  LoRaWAN.setADR((char*)"off"); // Adaptive data rate
  LoRaWAN.setDataRate(5); // [250, 440, 980, 1760, 3125, 5470, 11000];
  LoRaWAN.setDeviceEUI(DEVICE_EUI);
  //showErrorResult((char*)"2. Set Device EUI ", LoRaWAN.getDeviceEUI());
  LoRaWAN.setAppEUI(APP_KEY);
  //showErrorResult((char*)"3. Set APP EUI ", LoRaWAN.getAppEUI());
  LoRaWAN.setDeviceAddr(DEVICE_ADDR);

  LoRaWAN.setNwkSessionKey(NWK_SESSION_KEY);

  LoRaWAN.setAppSessionKey(APP_SESSION_KEY);
  //showErrorResult((char*)"6. Set App Session Key ",error);
  LoRaWAN.setRetries(3);
  LoRaWAN.saveConfig();
  LoRaWAN.joinABP();
}

void loop()
{
  // Look for new cards
  if (! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  else
  {
     error = LoRaWAN.joinABP();
     if (error == 0)
     {
       char* UId = GetUid(mfrc522);
       if(UId != NULL)
       {
          BlinkGreen(500);
          delay(100);
          // Send it!
          error = LoRaWAN.sendUnconfirmed(PORT, UId);
          Serial.println(error);
          delay(100);
          if(error == 0)
          {
             Serial.println(LoRaWAN._dataReceived);
             BlinkGreen(1000);
          }
          else
          {
             BlinkRed(1000);
          }
        }
        delay(2000);
     }
  }
}

char* GetUid(MFRC522 mfrc522)
{
    // Optional: Dump data about the cards
    //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    buffer = mfrc522.uid.uidByte;

    for (int i = 0; i < mfrc522.uid.size; i++)
    {
      sprintf(&rfid_arr[i * 2], "%02X", mfrc522.uid.uidByte[i]);
    }
    mfrc522.PICC_HaltA(); //command the card into sleep mode
    return rfid_arr;
}

void BlinkGreen(int delayTime)
{
  digitalWrite(greenPin, HIGH);
  delay(delayTime);
  digitalWrite(greenPin, LOW);
}

void BlinkRed(int delayTime)
{
  digitalWrite(redPin, HIGH);
  delay(delayTime);
  digitalWrite(redPin, LOW);
}
void showErrorResult(char* errorMessage, uint8_t error)
{
  if(error == 0)
  {
    Serial.print(errorMessage);
    Serial.println("OK!");
  }
  else
  {
    Serial.print(errorMessage);
    Serial.print(" Error: ");
    Serial.println(error);
  }
}

A pure guess from your symptoms would be either a memory leak or a counter overflowing.  I'll look at the code and get back to you.

Is you Arduino overheating? can you start a second couple of hour run within minutes of the first?

@Matt,
thanks guys. But if rfid_arr size was an issue, wouldn't the box be giving problem the first time we use it? because it works for few hours before it goes into not responding state. The rfid tag data looks like below
AEA00622
DE1CD403

The bad news is I can't see that much wrong with your code.

You need to set the Red and Green pinModes().  You've set error, but then don't use it.  I'm guessing the green LED is a new feature.  similarly you could refactor the blink green and blink red functions into one and pass in the pin number.
Are you sure that the mfrc522.uid.size is always less than 5?  In GetUid() you assume that i*2 will fit into the buffer rfid_arr which is 10 bytes.  sprint() always attaches a null onto the end of what it rights to the buffer so this will overflow if you write elements 9 and 10.

I really doubt either of those are the problem you are looking for, so would it be possible to stick loads of Serial.println() statements in and see where abouts it is crashing?

Make sure you put Serial.flush() after each Serial.println() or the crash itself may truncate your serial output and leave you looking in the wrong place.

Reply, thanks guys. But if rfid_arr size was an issue, wouldn't the box be giving problem the first time we use it? because it works for few hours before it goes into not responding state. The rfid tag data looks like below
AEA00622
DE1CD403

Matt, I did not get you mate. I have not changed anything in the code and the issue is still there. What do you see is wrong? or more precisely what shall i change in the code?
The rfid data looks like DE1CD403
Thanks a lot for your coooperation

(I misread you comment, so...)
What is the length of the RFID data is it 4 bytes or 8 bytes?  Is mfrc522.uid.uidByte[i] an unsigned byte? if so your format string should be "%02hX".  Otherwise if the value of mfrc522.uid.uidByte[i] is 0xFF then you will end up with rfid_arr[i * 2] = "0xFFFFFFFF" which if its the last byte will extend the array by 6 characters.  So if the RFID length if 4 bytes its a data dependent error and if its 8 bytes then its just a question of time.


text:
Arduino Rubber ducky?
So there is this hacking tool called a rubber ducky , the concept is that the device looks like a flash drive but the computer thinks it's a keyboard . According to what i know , a usb port has 4 wires , VCC GND and 2 for data , so i thought if it was possible to take a usb cable , cut it and connect it to the arduino accordingly , and send the computer that data so that he would think i connected a keyboard , and basicly create a fake reprogrammable keyboard

You mean buy an Arduino Leonardo or Arduino Micro and plug it in?

You can fake a keyboard using VUSB for AVR.

@Gerben I would never touch a solution like that even with someone else's barge pole. Bit-banged USB is very very nasty, and a 5V (non-USB) Arduino doesn't have a suitably compatible electrical interface to USB which risks damaging your hub or computer.

Most Arduinos can't be a USB keyboard (not without some really nasty bit-banging code and dodgy electronics).
Some can, though - such as the Arduino Leonardo or the Arduino Micro. And you don't need to cut any cables, you just plug it in.

i meant like if i take a usb cable and cut it and connect the according wires of the usb cable to the arduino and sending data , any chance the computer can see this data and think a keyboard or mouse has been connected ?

Why take a cable and cut it? Just plug it direct into an Arduino that is designed for the job!

I mean sending raw data , since when i connect and arduino , it sends the pc certain bytes that tell the pc that is an arduino , but i want to trick the pc  into thinking that is a keyboard

So you mean plugging in an Arduino that is designed for the task, like the Arduino Leonardo or Arduino Micro? Do you actually have the faintest clue what an Arduino Leonardo or Arduino Micro actually are?


text:
Arduino HC05 - AT commands won't respond
A little while ago i tried using AT commands on my HC05 bluetooth module using my arduino mega 2560 and it worked fine , skipping a few weeks ahead i tried doing the same , only now i suddenly doesn't work , i tried replacing the arduino and HC05 module , even used the same script for the commands. So i unplugged the module's VCC , pressed the button on the module , reconnected the VCC and the module was blinking every 2 seconds (it's in AT mode !) , now i go ahead to the serial monitor and using that script i typed the command i wanted to execute and it just didn't do nothing , i saw the serial LED on the arduino blink , but nothing was written in the serial monitor and nothing was changed in the arduino.
Does anyone know how to solve this ? it worked perfect before , but now it wont D:

Here's the solution!
First, you have to wire the board like the solution 2 in the instruction.
http://www.elecfreaks.com/wiki/index.php?title=Bluetooth_Shield
Then, Use this code!
/*********************************************************************
 **  Description:                                                    **
 **  This file is a sample code for your reference.                  **
 **                                                                  **
 **  Copyright (C) 2011 ElecFreaks Corp.                             **
 **  Created by ElecFreaks Robi.W /29 Sep 2011                      **
 **                                                                  **
 **  http://www.elecfreaks.com                                       **
 *********************************************************************/
void setup()
{
   Serial.begin(57600);
   Serial1.begin(38400);

}

void loop()
{
  int i = 0;
  char someChar[32] = {0};
  // when characters arrive over the serial port...
  if(Serial.available()) {
    Serial.print("------->  ");
    do{
      someChar[i++] = Serial.read();
      //As data trickles in from your serial port you are grabbing as much as you can,
      //but then when it runs out (as it will after a few bytes because the processor
  //is much faster than a 9600 baud device) you exit loop, which then
 // restarts,
  //and resets i to zero, and someChar to an empty array.So please be sure to keep this delay
      delay(3);
    }while (Serial.available() > 0);
    Serial1.println(someChar);
    Serial.println(someChar);
  }

  while(Serial1.available())
      Serial.print((char)Serial1.read());
}

Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.


text:
Is there a portable timer interrupt library?
I have a need for timer interrupt (for the sake of this exercise - say I need to execute something every second)
I found code in many places on the internets that does this using ISR for 328/Uno.  (or specifically for other chips) But of course that does not work on other chipsets.
Is there a portable timer library that works across many/most/all arduino boards/chipsets?
For now it is a simple project - I have no other motors or tones, etc.
In my current project I have conditional compiles for different chipsets, to set up a callback/interrupt but would rather use a library that hides this all.

My guess would be no.  You are asking for a library that interfaces with interrupts and they are usually quite processor specific.  You would need a layer that interfaced to the user code and abstracted the hardware away into a replaceable module.

@matt, Right, I am wondering if someone wrote a wrapper - so that everyone who wants a timer doesn't have to write their own.  Just as I have three different conditionally compiled timer implementations - that could be wrapped in a library.  I will keep looking.  But what you say makes sense - since the lib writer couldn't know what other things the timers might be used for in the client code.  I guess it's not really going to happen for that reason

I think it would be hard, or impossible, to make such a library. Already there are problems with pin-change interrupt libraries, and Software Serial (which uses pin-change interrupts).
Plus, to have a generic "callback" might tempt people to do things which they shouldn't anyway in an ISR, like do serial printing.
Let's say you choose to use a spare timer (eg. Timer 1). You have the issue now that you won't be able to do (some) PWM output because that uses Timer 1.
The closest would be to lever off the existing millis() code and just have a test in loop to see if the time interval is up, and then call a function - however that wouldn't be an ISR.


text:
Reading the DotStar datasheet - power requirements
I'm trying to figure out my power requirements for a strand of Adafruit DotStar LEDs - APA102 Cool White, not the RGB. I'm not sure how to interpret the datasheet.
In the middle of the product spec table on page 1, under Power Consumption, it says 0.2W (MAX: 1W).  Which would mean at 5V, MAX would be 0.2A, or 200mA.
Then on page 3 in the electrical characteristics table under the symbol/Parameter "LOL/Sink Current Voltage" it says typ. 24.5mA; max. 26.5mA.
I plan on having the strand on full brightness most of the time.
So which is it?  200mA? or 26.5mA?

I expect you will have to run an experiment and measure how much current each unit draws at full brightness.
The APA102C spec sheet seems to mix together data about the whole unit (controller chip plus three LEDs) and the controller chip itself.  The “LOL/Sink Current Voltage (RGB)” line that shows “min. 22.5, typ. 24.5, and max. 26.5 mA” appears to apply to the controller, and probably to single outputs on that controller, which anyway would give a 3X multiplier.  (The Cool White strips have three white LED chips per unit, instead of 1 each R, G, B.)
Note, the Adafruit DotStar LED Strip - APA102 Cool White webpage suggests using their 5V 4A power supply to drive “a half meter or meter” and their 5V 10A supply to drive  “a couple meters”, which at 30 units per meter works out at 2/3 to 5/6 W of power supply capacity per unit.

You have correctly worked out:
I(A) = P(W) / V(V)

I = 0.2 / 5
I = 0.04A

MAX:
I = 1 / 5
I = 0.2A

From that it seems it will use between 40 - 200mA depending on brightness.
Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

More information on current sinking


text:
Made a Adafruit Flora unusable
I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs.  After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights.  When this orange color appears, it seems to indicate that the Flora has crashed.  If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.
The time between boot and crash is short enough that I can't upload a new sketch.
So how would I go about rescuing the Flora?
Is there a couple pins I can jumper to put it into bootloader mode?  Or some other way of resetting the Flora so as to remove the offending code?

Sounds like it might be a power problem, perhaps your LEDs are overloading your USB port (how many do you have?).  You might try disconnecting the LED strip to verify you can still program the flora.

@ChrisStratton: 42 pixels in the strand all set to bright white.  If I read the datasheet correctly each pixels draws a max of 0.2A - so that should be 8.4 amps!?  Sounds awfully high?

No, they should only take about 60mA each. But at 2.5A that's still too high for the on-board regulator.

And several times too much for a USB port, too.  Disconnect power to the pixels and you'll find your flora is probably fine.  But you'll need to rig up a suitable power supply if you want to turn more than a few of them on dimly.

42 pixels in the strand all set to bright white.

This exceeds the power supply capability of either a USB port or the Arduino's regulator.
Likely the circuit starts out working, then once the LEDs are all on drawing high power either a protective device such as a polyfuse / PTC fuse activates trips or the supply simply sags under load.  At this point the circuit either shuts down or starts misoperating, the ATmega may go into brownout protection mode, etc.
Disconnect power to your LEDs and you will probably find that the Flora is fine.
You will need to use a suitable higher current power supply if you want to light more than a few pixels of this type at any given time.


text:
What Arduino board with WiFi should I choose
I want to implement an Arduino module with some sensors and send the info through WiFi to a server. I'm looking for the best board or component combination to make this. What is the best board or solution you would use in my case? Maybe Arduino Yun or Intel Edison Kit for Arduino...¿?
I've developed a sensor module with Redbear Blend board which use Bluetooth to communicate with an Android app to send sensor data, but now looking for WiFi connection.
Sorry if it's a stupid question, I'm new in this Arduino world. Thanks in advance!

I'd recommend ESP8266 (model 07) based board.

Can be programmed the same way as other Arduinos
Cheap
Enough storage for code
Fairly low power
Large community (more code examples and better library support)

Ok, thanks, I'm checking it right now and it seems just what i was looking 4 ;)


text:
Do external battery packs need to connect to ground on the arduino?
I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.
For instance the 5V pin on the Arduino is actually 5V relative to the ground pin.
A 12V battery's + terminal is 12V relative to the - terminal. In this situation the - pin can be labelled Ground.
Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.
A battery with an LED and resistor attached has a circuit: Battery -> LED -> Resistor -> Battery.  An Arduino itself is a circuit: Power -> Arduino -> Internal Gubbins -> Power
By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.

In short, always connect the grounds!

@NickGammon Unless you don't need to, such as if you have an opto-coupler.

@NickGammon so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground. If the arduino has nothing to do with that circuit, then the negative battery terminal is enough. Is that correct? Thanks for your help

Yes, the signal needs to be in reference to something. So you would have ground on the servo going to both the Arduino and the battery negative terminal. Then the signal from the Arduino goes to the servo control pin, and the positive side of the battery to the servo motor pin.

I like the Majenko's answer, but I'm going to explain it with a different approach. You know that there are some quantities that are measurable in an absolute way (mass, lenght, weight) and other that need a starting point to refer. Think about the distance: you cannot say "New York" is distant 10km.. the question that obviously would come in mind is: 10km from what? So you have to decide a point in the world, from which you can measure the distance of every city.
The voltage measure the potential, that is the energy that a single charge would have. Now the question is: is the potential energy an absolute value? Of course not, i have to define a point where it is zero, and measure everything from it. In a circuit this point is called Ground, evry potential measured in the circuit is calculated to the ground.
The last step is to know that charges goes from the points at higher pot to the lowest one (the ground), usually preferring the path with lower resistsnce (but that's another story). A wire has the same potential all along it and in order to compare the voltage of arduino and the battery pack they must refer to the same ground.

so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground.

Here is typically how you might wire a servo:

Note the shared ground. The Arduino provides the control signal (data) via the orange wire. The battery provides the motor power via the red wire. The grounds must be shared or the voltages on each wire are meaningless.


text:
Why do I get "invalid operands of types 'const char*'" error?
I am making an Arduino alarm. This is the error:
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Here is the code that triggers it:
lcd.print("0"+hours+":"+minutes);

This code is similar, but worked before:
String none="00";
lcd.print(none+":"+none+":"+minutes);

I can post the full code if you need it. How can this be fixed?

Your first code took a String object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to String objects.
Your new code doesn't have any String objects at all - and you're not allowed to add strings to strings (both lowercase).
It will work if you change your new code to:
lcd.print(String("0")+hours+":"+minutes);
That turns the original string "0" into a String object, and then adds more strings to it.


text:
how to count blinking LED flashes using arduino uno boards and LDR?
i want to know code for counting the flashes of LEDs and display no. of flashes in particular time given.by using LDR.
basically i tried it with interrupts but i'm not getting it,so please help in this regard.

If you post the code of your attempt, we might be able to help you.

An hardware solution could be achieved by putting a photodiode or a photoresistance near the flashing LED. Connect it to a pin that supports external interrupt and you're done. With a bit more circuitry you can ensure that the value on the pin doesn't oscillate: put a Schmit Trigger after the photodiode or resitance with its output on the input pin.

The Arduino Uno already has Schmitt triggers on all its digital inputs. C.f. figure 14.2 on page 76 of the ATmega328P datasheet.

LDRs only give an analog output, proportional to the amount of light.
To make it give a HIGH and LOW value, you have to tweak the other resistor used in the voltage divider.
Alternatively you could use analogRead and add a threshold value in your code.


text:
NRF24L01+ Issues antenna
I have 2x NRF24L01+ communicating but they are unreliable. It doesn't matter if they are right night to each other or 100ft away. For some odd reason when I place my hand on the antenna it work perfectly. Why would this be?
I have one set up to send and one to receive. All I am sending from one to the other is a 3 digit number to turn on a relay.

Are they the modules with the power amp and SMA antenna, or the ones without the amplifier and PCB track or ceramic antenna?

And how well do they work if they are 20' away from each other? Too close and it will distort the signal. Too distant and the signal will be too weak.

Yes they are SMA. Here is what I bought link . About 30' away was my test and still the same issue. I found when I remove the antenna is works much better.

Those ones don't work well when too close together. The signal is too strong and distorts. You may be attenuating it with your hand making it work better. It should be good over 100' though.

I found a solution. As the signals where too close I found where I could tone down the signal strength using:
   radio.setPALevel(RF24_PA_MIN);

Because I didn't want to loose long range capabilities too I send my packet out 4 times at this lower signal and then increase the strength back to max to send out another 4 packets. This way my close range and far range relay will receive the signal.


text:
Unable to upload sketches after little oopsie (reversed input polarity)
So playing around with an arduino uno, I was powering it with a 12volt battery (putting power between Vin and Gnd) and I fat fingered the battery terminals, putting them in reverse (oops)
I see smoke coming out of the 5 volt regulator (the little 3 pin IC). I immediately pull out the battery thinking I've just bricked this thing.
After a minute or two I plug the battery in again (taking care to plug it in straight this time) and to my surprise it works, works pretty well. The last sketch I uploaded works perfectly fine.
I've been using the same thing for an hour or so. But now I wanted to upload another sketch and it doesn't upload. The voltages seem to be fine, I'm putting in 11.8 volts on Vin, there is 5.12 volts on 5v and 3.34 volts on 3v3
I thought there may be some problem with the voltage regulator, so I tried connecting it directly to the USB (powering it from USB) but still the same thing.
I find it intriguing that it works perfectly for everything except uploading new sketches, especially after such an explosive oopsie. Can any of you chaps deduce what the problem might be? I have a USBasp module so I can reburn the bootloader, but I doubt that's the problem.

You've blown the USB communications IC.  CH340/341 or FTDI or PLxxx or whatever.   Hook a USB-Serial adapter (uh, CH340/FTDI based, ironic, I know) to D0/D1 pins of Uno, also the ground lead to the Uno ground pin, and voila! you're back in business.   How do I know this?  I've done it twice... Different errors though, I'm not a complete idiot!)

The atmega328 that runs the sketch is fine, but the communication is broken somehow.  See the steps in https://arduino.stackexchange.com/a/13293/6628

Good find, I tried doing the serial test (shorting reset to gnd and then connecting tx to rx) and it seems to work fine (in that communication happens).
I'd deduce that the problem is happening between the USB controller (the little atmega chip) and the main controller (the atmega328). I'd have to search through the schematic to find it, but for now I've just uploaded the sketch directly, using ICSP.

Just remember that by programming using ISP you overwrite the bootloader, so you need to put that back when to determine if you fixed the board.


text:
Arduino LiquidCrystal_I2C fast overwritting
I have an arduino board connected to 2 temperature sensors, 2 switch buttons and 1 lcd display.
When the switch button changes to off, "off" is printed on the lcd display. When the button state is on, the temperature is printed on the lcd display.
The problem is when it shows "off" its still possible to see the temperature value for "1 millisecond" each second. I don't know what is causing the "off" message to change for a millisecond.
Source code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Streaming.h>

#define DS18B20_SENSOR1 2               // pino de dados do DS18D20
#define DS18B20_SENSOR2 4               // pino de dados do DS18D20

int buttonState1 = 0;
int lastButtonState1 = 0;
int buttonState2 = 0;
int lastButtonState2 = 0;

float Temp1, Temp2;

OneWire oneWire1(DS18B20_SENSOR1);       // Objeto do baramento One-wire
DallasTemperature sensor1(&oneWire1);     // Objeto do sensor DS18D20

OneWire oneWire2(DS18B20_SENSOR2);       // Objeto do baramento One-wire
DallasTemperature sensor2(&oneWire2);     // Objeto do sensor DS18D20

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup(void)
{
  Serial.begin(3000);
  Serial << F("Teste do Sensor 1") << endl << endl;
  Serial << F("Teste do Sensor 2") << endl << endl;
  sensor1.begin();
  sensor2.begin();
  lcd.begin();
  lcd.setBacklight(HIGH);

  /*
   * Control Variables
   */

  pinMode(5, INPUT);
  pinMode(7, INPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void turnAllOff1(){
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
}

void turnAllOff2(){
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
}

void printTemp1(){
  lcd.setCursor (0,0);
  lcd.print("Sensor1: ");
  lcd.print(Temp1);
  lcd.print("C");
}

void printOff1(){
  lcd.setCursor (0,0);
  lcd.print("Sensor1: ");
  lcd.print(" off   ");
}

void printTemp2(){
  lcd.setCursor (0,1);
  lcd.print("Sensor2: ");
  lcd.print(Temp2);
  lcd.print("C");
}

void printOff2(){
  lcd.clear();
  lcd.setCursor (0,1);
  lcd.print("Sensor2: ");
  lcd.print(" off   ");
}

void loop(){
  buttonState1 = digitalRead(5);
  buttonState2 = digitalRead(7);

  if(buttonState1 != lastButtonState1){
    if(buttonState1 == HIGH){
      sensor1.requestTemperatures();
      Temp1 = sensor1.getTempCByIndex(0);
      turnAllOff1();
      if(Temp1 < 36){
        digitalWrite(13, HIGH);
      }
      else if(Temp1 > 38){
        digitalWrite(11, HIGH);
      }
      else{
        digitalWrite(12, HIGH);
      }
      printTemp1();
    }
    else{
      printOff1();
    }
  }
  lastButtonState1 = buttonState1;

  if(buttonState2 != lastButtonState2){
    if(buttonState2 == HIGH){
      sensor2.requestTemperatures();
      Temp2 = sensor2.getTempCByIndex(0);
      turnAllOff2();
      if(Temp2 < 0){
        digitalWrite(10, HIGH);
      }
      else if(Temp2 > 2){
        digitalWrite(8, HIGH);
      }
      else{
        digitalWrite(9, HIGH);
      }
      printTemp2();
    }
    else{
      printOff2();
    }
  }
  lastButtonState2 = buttonState2;
}

You need to use INPUT_PULLUP pin mode and connect the buttons between the pins and ground.
pinMode(5, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);

Later on you will also have to debounce the button but that is another question (where you can find plenty of answers already).
Cheers!

No sir, that doesn't solve the problem. I even looked up on the debounce problem. If I use "INPUT_PULLUP" it won't recognize the state of the button hence not showing the "off" message.

You also need to change the button logic (buttonState2 == LOW) as pushing the button will given a LOW signal with PULLUP.


text:
I'm new here. Where to look for documentation for my specific board
sorry if this isn't the done thing. I have a little red space invader shaped board that has an arduino chip on the back from a conference. There is an LCD display and I've just got it to function correctly (there was a power issue.
ATE1 E
0
ATE
1

The above is what the screen is displaying and I can't make heads or tails of it. Any ideas?
I've tagged this with arduino-micro because I think it may be that although I've had relative success using 'SparkFunProMicro' board in arduino IDE
EDIT: I've been able to get some more board info from arduino IDE. VID:1B4F, PID:9204, BN:unknown board, SN:Upload a sketch to get it.

Its unclear what you are asking, but I'm guessing Iding the boards is the first step.  Maybe a photo of the board would help.  Sparkfun boards are normally red and they use the Vendor ID of 1B4F.  They make a 5v Pro Micro with a Product ID of 9205 and a 3.3V version PID=9203.  They also make a Leonardo with a PID of 9206.  So you PID is in the right area, but god knows what it is.  Can you read the back of the ICs to see what they say?

Quote from Tech Note Wiki: All SparkFun ATmega32U4 boards share the same VID - 0x1B4F, and they all have unique PIDs. 5V Pro Micros lay claim to PIDs 0x9205 and 0x9206 (one for the bootloader, one for the sketch). 3.3V Pro Micros will show up as 0x9203 and 0x9204 for bootloader and sketch, respectively. And the Fio v3 has 0xF100 and 0xF101.

an arduino chip on the back - what chip? Part number?


text:
Unable to upload code to my digispark ATtiny 85 after upgrading bootloader
I've just received my digispark ATtiny85 (model B, I believe). I'm using Pop_OS for my PC, had a bit of a headache getting the arduino IDE recognising the device but after some trial and error I got there.
When uploading a sketch I would then get erase errors and if I recall correctly it was error -71.
I couldn't work it out but found out that my boards came with v1.6 of the micronucleus firmware. So I upgraded to the latest which is v2.6. Now when I upload a sketch however the output looks like the following
Sketch uses 718 bytes (11%) of program storage space. Maximum is 6012 bytes.
Global variables use 9 bytes of dynamic memory.
Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
Warning: device with unknown new version of Micronucleus detected.
This tool doesn't know how to upload to this new device. Updates may be available.
Device reports version as: 2.6
Warning: device with unknown new version of Micronucleus detected.
This tool doesn't know how to upload to this new device. Updates may be available.
Device reports version as: 2.6

I don't have a clue what to try next as everything feels like it should be at a working point. Not sure how to decipher "Updates may be available". I'm using the latest arduino IDE, with the digistump board manager url and using the latest micronucleus firmware for the board.
I tried to re-flash the firmware to v2.4 just on the off chance that the firmware was too new to be supported in arduino IDE but I received the same error as above but with just a different version number reported.

You have version 1.6.7 (current) of the digistump board package installed?

@timemage yes I believe I do. This json file http://digistump.com/package_digistump_index.json
With Digispark (Default - 16.5mhz) as the board chosen,

"my boards came with v1.6 of the micronucleus" I'm guessing you meant 1.06. So far as I've been able to tell 1.6 was never a version.

1.06 defines major version as 1 and minor version as 6 (2.6 also has 2.5 in the CLI text).

It seems the latest version (1.6.7) of the Digispark board support package is quite old, older than I'd have guessed. And so it does come with an old Micronucleus programming tool. The tool appears to compare the major version number of the firmware as found in the USB device version. And since the Micronucleus tool in the 1.6.7 package is expecting nothing newer than major version 1, major version 2 of the firmware is not going to work with it.
You have a couple of options.
Reprogram old firmware (1.11)
You already seem familiar with burning .hex files. So, if you want to use the latest official Digispark board support you need to burn the hex file for Micronucleus version 1.11.  I replicated your error, but using an OLIMEXINO-85-ASM which is highly similar to the Digispark but may not be identical.  After programming micronucleus-1.11.hex the board worked with the official Digispark board support package.
Use ATTinyCore
However, you could also just abandon that old official package and use ATTinyCore which does come with a Micronucleus bootloader new enough to program the Digispark board with Micronucleus 2.6. I tested that as well.
Patch a new Micronucleus tool into your old official support package
You can replace the Micronucleus tool with a newer one in your arduino15/packages/digistump/tools/micronucleus/2.0a4 directory. Incidentally, I have no idea where the 2.0a4 comes from, but it is not indicative of a Micronucleus 2.0 in any way that I can tell.
For testing I put the 2.6 firmware on the board, specifically the t85_default.hex file, and stole the Micronucleus tool out of the latest ATTinyCore board packages tools directory, by renaming the existing file an symbolically linking in the other one:
$ pwd
/home/user/.arduino15/packages/digistump/tools/micronucleus/2.0a4
$ ls
launcher  micronucleus
$ mv -iv micronucleus micronucleus.backup
renamed 'micronucleus' -> 'micronucleus.backup'
$ ln -s ~/.arduino15/packages/ATTinyCore/tools/micronucleus/2.5-azd1b/micronucleus
$ readlink micronucleus
/home/user/.arduino15/packages/ATTinyCore/tools/micronucleus/2.5-azd1b/micronucleus
$

And that works as well.


text:
Arduino analog pins
How many sensors can be used by a arduino uno and mega separately.?
Does each sensor can use the ADC of arduino simultaneously? If not how to use all the sensors simultaneously if possible?

How many sensors can be used by a arduino uno and mega separately?

Assuming you mean analog signals. As many as the number of analog pins on those boards. This can be extended by using an analog multiplexer and additional digital pins. The total number of channels is number of analog pins minus one plus log2 of the number of digital pins used to select the input channel, e.g. 8 additional analog channels through a multiplexer will require 3 digital pins for channel selection.

Does each sensor can use the ADC of arduino simultaneously?

There is a single ADC module which takes approx. 112 us to convert an analog signal to 10-bit digital number. There is no simultaneous conversion of multiple channels.

If not how to use all the sensors simultaneously if possible?

All sensor can be connected but only one at a time is sampled and conversion to digital number.
Cheers!

All AVR- and ARM-based Arduinos have a single ADC, connected to multiple input channels. If you require simultaneous sampling of multiple sources then you will need to use one or more external ADCs.

If not how to use all the sensors simultaneously if possible?

a few ways:
1) use external adc;
2) use a sample-and-hold circuitry on the sensors;
3) find a mcu that has more than one adc modules; some pic24/dspics have that. some atxmegas have that. and some arm chips have that as well, to list a few.
4) use multiple avrs, each for a sensor;
...


text:
Problem connecting 10W led + Led driver Directly Arduino Uno
can anyone give me an advice on connecting an 10W led + 12 volt drive to an Arduino Uno? it works without the board but when i tried to connect to Uno it doesn't work anymore. Thankyou

advice: don't do it.

Not unless you tell us what equipment you are using...

Yes, Thankyou, I'm using Led Driver Driver
Input Voltage: 12-24V DC
Output Voltage: 9-12V
Output Current: 900mA+-5%
can support 10pcs high power 10W led 3 in serial and 3 in parallel
http://www.ebay.com/itm/331653946252?_trksid=p2057872.m2749.l2649&var=540791276944&ssPageName=STRK%3AMEBIDX%3AIT

To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board.
More easy and reliable option would be using Relay Board.
You can visit this link and can get more idea....
http://www.electroschematics.com/8975/arduino-control-relay/

wow, thankyou so much, this is what i bought from ebay an Led driver
Input Voltage: 12-24V DC
Output Voltage: 9-12V
Output Current: 900mA+-5%
can support 10pcs high power 10W led 3 in serial and 3 in parallel
http://www.ebay.com/itm/331653946252?_trksid=p2057872.m2749.l2649&var=540791276944&ssPageName=STRK%3AMEBIDX%3AIT

You'll need a switch such as a transistor, and capable of handling 10W, to be driven by the Arduino and connect/disconnect the LED to an external 12v supply. There are many examples on the web. Remember to connect the 12v and 5v grounds together.

authors: ابو العز دعبول


text:
Controlling Enable Function on MicroStepper Driver
I'm having trouble using the ENABLE pin on my microstepper driver, I'm not sure of the exact model but it looks exactly like the one pictured here
Microstepper Driver
Here's my code:
#define MAX_LEN 8
#define MIN_INCREMENT 0.5
#define LIMIT_SWITCH 3
#define ENABLE 10
float buoyancymass = 4401.425;
float centrebuoyancy = 14.164;
float mainarm = 14.3;
float nosearm = 1.8;
float adc = 11.4;
float meanadc = 22.65;
volatile byte enable_state = LOW;

#include <Stepper.h>

const int stepsPerRevolution = 1600;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
float stepinch = 0.00524; // 1 step = x"

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LIMIT_SWITCH, INPUT_PULLUP);
  pinMode(ENABLE, OUTPUT);
  //enable motor
  digitalWrite(ENABLE, enable_state);
  //interrupt
  attachInterrupt(digitalPinToInterrupt(LIMIT_SWITCH), limitbrake, FALLING);
  // set the speed
  myStepper.setSpeed(30);
}

void limitbrake() {
  digitalWrite(ENABLE, !enable_state);
}

The problem I'm noticing is that when I set the pinMode(ENABLE,OUTPUT); my stepper doesn't draw current and therefor, doesn't drive. This occurs regardless of whether I set my enable_state to HIGH or LOW.
Funny enough, when I set it to pinMode(ENABLE,INPUT); it does draw current and drive the motor, but unfortunately my limit switch which I've attached an interrupt to doesn't disable the motor when its pressed.
Before you ask, I've tested the enable pin on my driver and my limit switch circuitry in other programs and they both work. I'm just having trouble with putting it together.
Here is the rest of my code if you were wondering.
float calc_margin(float pos, float mass) {
  // calculate margin
  Serial.print("Distance: ");Serial.println(pos);
  float batterymoment = mass*pos;
  Serial.println(batterymoment);
  float totalmass = mass + 12404;
  Serial.println(totalmass);
  float totalmoment = 149650+batterymoment;
  Serial.println(totalmoment);
  float buoyancymoment = buoyancymass*centrebuoyancy;
  Serial.println(buoyancymoment);
  float wheelmoment = totalmoment - buoyancymoment;
  Serial.println(wheelmoment);
  float wheelweight = totalmass - buoyancymass;
  Serial.println(wheelweight);
  float cgwheels = wheelmoment/wheelweight;
  Serial.println(cgwheels);
  float maindistance = mainarm - cgwheels;
  Serial.println(maindistance);
  float nosedistance = cgwheels - nosearm;
  Serial.println(nosedistance);
  float mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  Serial.println(mainmass);
  float nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  Serial.println(nosemass);
  float mainmoment = mainmass*mainarm;
  Serial.println(mainmoment);
  float nosemoment = nosemass*nosearm;
  Serial.println(nosemoment);
  float netmoment = buoyancymoment+(mainmoment*2)+(nosemoment*2);
  Serial.println(netmoment);
  float netcg = netmoment/totalmass;
  Serial.println(netcg);
  float staticmargin = adc - netcg;
  Serial.println(staticmargin);
  float answer = staticmargin/meanadc;
  Serial.println(answer);
  float percentage = answer*100;
  Serial.print(percentage); Serial.println("%");
  float result = answer;
  return result;
}

boolean check_margin(float test_margin) {
  if (test_margin > -0.04 && test_margin < -0.02)
    return true;
  return false;
}

float armcalc(float mass) {
  for(float x=0;x<MAX_LEN;x+=MIN_INCREMENT) {
    // calculate margin
    float margin = calc_margin(x,mass);
    if (check_margin(margin)) {
      return x;
    }
  }
  return -1;
}

float stepcalc(float arm){
  int arminch = arm*12;
  float numberofsteps = arminch/stepinch;
  int result = numberofsteps;
  Serial.print("Calculated steps: "); Serial.println(result);
  return result;
}

void loop() {
  // read input
  Serial.println("Enter mass: ");
  while (!Serial.available());
  float mass = Serial.parseFloat();
  float arm = armcalc(mass);
  if (arm < 0) {
    // Error message
    Serial.println("Error!");
    return;
  }
  Serial.print("Arm distance is "); Serial.println(arm);
  // step
  const int steplength = (int) stepcalc(arm);
  Serial.print("Number of steps is "); Serial.println(steplength);
  myStepper.step(-steplength);

  while(1);

}

An interrupt service routine which toggles state sounds like you are just asking for trouble. Even if it is not the cause of your problem, you would likely be better off with logic to assertively set the correct level. Are you aware of the issue of "contact bounce"? That could see you toggle the motor state a somewhat random number of times, with the result depending if that is even or odd...

I drive those with 12 Volts from a printer port. I remember mine should be also 5V-compatible. Plus, I have the feeling, that you don't exactly know, how these drivers work...

These drivers differ from the H-Bridge-design described here. You don't need to generate pulses for the coils, as you would do with a classic H-Bridge.

Connect your motor to A+, A-, B+, B- (a is one coil, b the other)

Connect Power (guess 12+ volts, mine take up to 48V) to GND and V+

Either connect 5V to ENA+(+5V) or a free arduino Pin and ENA-(ENA) to GND. This pin enables/disables the driver. If no input is present at this pin, the driver will not work.

Connect DIR+(+5V) to a free arduino pin and DIR-(DIR) to GND. This pin controls the direction. HIGH makes the motor turn right, while LOW on this pin makes the motor turn left.

Connect PUL+(+5V) to a free arduino pin and PUL-(PUL) to GND. This pin controls the speed. The more pulses/second one applies, the faster the motor turns. (Up to a limit, of course).

Sketch should be easy.
Plus: You could turn around the control connections, by hardwiring all +5V pins to 5V and use INPUT_PULLUP to switch the current flow on the negative lines. I know that these drivers are optical isolated and draw as little as 10 mA from a pin, if at all. So you should be safe.

I fixed the enable function and I'm able to control the motor, but I'm still unable to use my limit switch to set the enable pin on or off. Would you have any idea as to why that is?


text:
Issues on Arduino, LiPO battery and two mottors setup
My main objective with this project was to control these two DC motors with an Arduino Nano (it is not a UNO), powered by a 3-Cell 750mAh LiPO battery (both the motors as the Arduino itself). So, I came up with something like this (it is a simplified version):

If the load on the two mottors rise, could the Arduino be damaged by this current increase? Is the voltage too high for the Arduino handle? Is there any more issues that this setup can have?
When searching, I found that it would be wise to get a fuse between the power supply and the arduino (before reaching Vin). Is that necessary?

You're not controlling anything, they will run as long as the battery is connected.  Yes, you need the fuse - Lithium Polymer batteries do not tolerate shorts.

You mean shorts at the motor part? If it happens, it may damage the arduino? How the current would behave in case of a short before the first motor?

Any short of the battery can cause it to quickly overheat, burst, and even burn.  It has nothing to do with the Arduino being damaged, rather the connection of prototypes modules like this increases the chances of wiring being - even very briefly - wrong either during connection or if something moves later.

But how would a fuse between the first branch and the Vin be of any help?

The fuse should be between the battery and the rest of the circuit, so that in the case of a short it can hopefully disconnect the battery from everything entirely.

If the load on the two motors rise, could the Arduino be damaged by this current increase?

No, the motor current doesn't pass through the Arduino. It is completely separate.

Is the voltage too high for the Arduino handle?

Borderline. The regulator (a lowly 7805) may well get very hot at that voltage (depending on the Arduino's current draw) and go into thermal shutdown.

Is there any more issues that this setup can have?

Maybe add a small buck regulator to the 5V pin instead of using the on-board linear regulator. That will not overheat and will be far more efficient making your batteries last longer. Often marketed as "UBEC" (Universal Battery Elimination Circuit) and used throughout the model vehicle industry these are very easy to get hold of and are ideal for powering things like Arduinos from batteries like this.

So besides the temperature, this setup will work, right? If I can't find these regulators, is there any possible home-made circuit to replace it?

You will be able to find them unless you live in Vanuatu. Even then you can probably get someone to fetch one in a canoe. Building buck regulators is a bit of a black art and not a very easy task - you need to do the PCB layout properly or you end up with a lot of stray EMI being generated. But yes, besides the heat, it should work. I assume the "simplification" has removed the control circuitry?

The arduino itself probably isn't going to draw enough current to justify a switching supply.  Smaller RC BECs are linear anyway, and those large enough to be switchers may waste enough power themselves to negate the advantage for a light load.  An intermediate regulator at 9v can move some of the heat off the board, but will require its own capacitors.

@ChrisStratton It all depends on what the OP has connected to the Arduino. Add a bunch of LEDs and the load will rise.


text:
Atmel studio 7 - my own libraries
I like to use AS7 to make my programs.
I know c and some c++, but how things work from there I'm green.
I would like to know if there is a folder where I can store my own homemade c and h library files where they get to be available for all my projects.
Now I copy all the files into each of my projects and this works but I find it a bit tedious.

You should create your library as a separate project: File->New->Project and select C or C++ static library:

Add your library modules in this project. When building, this will create lib{your_project_name}.a file (in Debug or Release folder) - your library object file you can use in your other projects.
Usually I include in the same solution both the library project and target project (just library project file, sure the library and it's files resides in single place):

ORDO is the library name.
Some check list:

Include the library file in Libraries folder (shown above)
Specify the path to the library *.a file for linker (Toolchain->AVR/GNU Linker->Libraries). Note that there should be different paths for Debug and Release configurations.
Specify the path for library include files (Toolchain->AVR/GNU C or C++ Compiler->Directories)
In some cases, F_CPU definition might be needed for library project too (same as in your project, under Symbols).
When changes are made in your library files, use Build solution (F7) when building, if not - you can use Build project (which will be faster).

Setting project dependencies shall also lead to rebuilding the library automatically when needed (not tested, I usually just hit F7 :).

Thank you for a good answer, I belive i see where to begin now. just as to what to do next, lets say you wanted to make a reusable library for those ds18B20 sensors I see you got there... I have googled around trying to find out how to do this but I cant seem to find any that enlighten me.

I used library from Davide Gironi: http://davidegironi.blogspot.com/2014/09/a-ds18b20-1-wire-digital-thermometer.html - it has no external onewire module, it is basic, minimalistic, doesn't support bus enumeration etc but might be good starting point to implement own.

Nice idea, but what if my own library has Arduino dependencies? I get stuck at this point, because of course requires the Arduino core stuff

Please check AS7 + Arduino + Libraries: How?! and Tutorial: Using Atmel Studio 6 with Arduino projects


text:
No data sent over serial port in linux c++
TL;DR - I am attempting serial communication with Arduino with code that I found here and nothing gets sent over (Arduino programmed to respond, and I checked that it does with its serial monitor)
Hi there,
I was looking for a way to send information over to an Arduino Mega (2560) unit over linux serial port by C++.
I came across the following solution: Solution
I'm using this guy's code for write (I'm able to read data from the arduino) and use the same parameters (they work, as I'm able to receive data from the Ardunio).
I programmed my Arduino to send "Hi" over serial whenever it sees at least 1 bit of information, and checked it worked through the Arduino IDE Serial Monitor.
Yet when running the C++ code, the arduino doesn't respond. Do anyone might have idea why?
Full disclosure - I inserted @Lunatic999's code to a class so I can make an instance of it for my needs of the code.
fd = open(portNameC, O_RDWR | O_NOCTTY | O_SYNC); //open port ("opens file")

Serial Parameters:
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

Write (this code I put inside a function which I call)
unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( fd, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

Arduino code:
bool dataRecieved = false;
int ledpin = 13;

void setup() {
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(19200);
}

void loop() {
  while(!dataRecieved)
  {
   digitalWrite(ledpin,HIGH);
   if (Serial.available() > 0)
   {
     dataRecieved = true;
   }
  }
  digitalWrite(ledpin,LOW);
  delay(1000);
  digitalWrite(ledpin,HIGH);
  delay(1000);
  Serial.println("hi");
}

@Juraj sorry, didn't post the correct version with the correct baudrate. now it is fixed. thanks!

remove the blinking and only turn the LED off

@Juraj nothing changed

then the problem is on linux side and off topic here

Well I am trying to connect with an arduino, so it might not be that off-topic (also good for future references for anyone that might need it as well). Anyhow, I'd still be happy to wait for more insights on this problem.

You are aware that the Arduino resets itself the moment you open the serial port and spends a second or so in the bootloader? During that time anything you send will be ignored completely.

@Majenko My savior! I was aware of the fact that when ever the serial opens, the arduino resets. I neglected the time it took the bootloader to finish (and the PC had no usleep command after the init of the serial interface). If you'll write this as an answer I'll be more than happy to accept it.

The Arduino resets the moment you open the serial port.  Once reset the bootloader executes, which consumes (and discards since it's invalid) any serial data for a second or so before your sketch runs.
Because of this anything you send immediately after opening the serial port is ignored.
There are two commonly accepted "fixes" for this:

Delay for a pre-defined period after opening the serial port, and
Have the Arduino send a "READY" signal before doing anything else which your program waits for before sending.


text:
int on Uno more than 16 bit?
So I'm playing with a TFT screen and trying to understand the colourspace encoding.  I wrote a quick for loop to show colours from 0 to FFFF and to print the value of colour being displayed:
for (int q=0; q<0xFFFF; q+=0x80) {
  tft.fillScreen(q);
  tft.setCursor(0, 0); tft.println(q, HEX);
  delay(2);
}

I was surprised to find values greater than FFFF being displayed - which suggest that int is more than 16 bits.  It's running on a Uno.
What has happened?
(PS I now understand RGB565 encoding, so this is off-topic)

Socco, Shall we close this question? Next time start by telling us which tft screen you have and that you are using the adafruit gfx library and if possible show a working sketch. The tft.fillScreen has a unsigned 16-bits parameter. A value above 0xFFFF rolls over and starts from 0x0000 again.

I guess you're seeing some big numbers starting with FFFF...?
What you are seeing is not big numbers - it's misrepresented numbers.
You have an int. That's not a "16-bit number", it's a 15-bit number plus a sign bit.
When you print it the variable is promoted to a long and the sign bit is extended.
That long is then further mapped (cast) into an unsigned long to print it as hexadeximal (there is no negative in the hexadecimal representation on Arduino), and that extended sign bit is seen as a string of F.
For example, the value 0xABCD stored in an int is:
 1 010 1011 1100 1101

I broke off the first bit because that is the sign bit in a signed integer.  The actual decimal value of that is -21555.
Now when that gets cast to a long the sign extension copies the leading sign bit to all the other 16 bits to the left of it, resulting in:
1 111 1111 1111 1111 1010 1011 1100 1101

Because of the way that twos complement works, that string of bits still represents -21555 in decimal.
However, cast it to unsigned long for printing as HEX and you can see how you would end up with some big numbers.  It would give you:
FFFFABCD

So you can see that a 16 bit signed value can end up being printed as 8 hex digits, and all because of the way the print() function in the Arduino API works.
When working with unsigned values you really should be working with an unsigned variable - especially if those unsigned values (0 - 65535) fall outside the range of the signed variable type (-32768 - 32767).  Switch to using uint16_t and you will be able to both store and represent the values correctly.

You might find it useful playing around with this site to learn how different variable types represent and store the data within them as binary.

Thank you for your detailed explanation @Majenko - quite informative for me.  (1) However the display does not show leading FFFFFs - for example it now shows 26C E000 .  (2) I guess the for loop will never exit because 0xFFFF will always be greater than the evaluation of max signed int =0x7FFF  - (3) But this still does not explain why the display is showing numbers greater than 16 bit capacity, which suggests the print command is being given a number greater than 16 bits.  (4) The Uno is a Chinese clone received with other hardware - so maybe this is relevant?

It won't be because it's a chinese clone - it's still the same software running on the same processor - even if it is one from the rejects bin. You loop certainly will never end. You should change to an unsigned value that is larger than your maximum loop value. Use uint32_t instead for your loop, then cast it to uint16_t for your colour value.


text:
Arduino wire question
I am a complete newbie to Arduino and I just received an ARDX arduino starter kit (the one that comes in the transparent green case)
I have been following the instructions for Circ-01 for the blinking led light but I am curious about the wires. In the breadboard instructional picture it shows a purple wire that is supposed to connect to pin 13 on the arduino. But the kit did not come with a purple wire, it only came with black, red, white, yellow, and green wires.
I also tried following a tutorial on YouTube and the guy in the video used a purple wire that he said was the led "cathode"
Can i substitute another wire for the purple and? Or did I receive an incomplete kit? I am very confused and the breadboard instruction picture is not very clear.
Thanks for any help!

Go buy some Quality Street. Eat one of the nice purple ones. Flatten out the wrapper. Look through it at a white wire. It now looks purple. The colour of wires makes absolutely no difference to a circuit - it is purely for humans to keep track of what is what.

Personally I like to try to use red wires for +5V, black or blue for ground, and yellow for data. However as Majenko said in a comment, the colour is irrelevant to the operation.
The usefulness of colour is just that if you stick to a system (like red for +5V and black for ground) then there is a visual check you make when connecting up a circuit, so you don't accidentally put things in backwards, like you might if every wire is yellow.
Also, if you run half-a-dozen wires from one place to another, using different colours is another way of making it easier to see you have connected the correct things together.
Having said all that, the colour does not otherwise affect things.


text:
Leostick Receiving message from Uno using USB jumpers cables
I have a Arduino Uno which is looping over Serial.println("$testmessage"). Connected to this is a USB cable that i have cut and soldered male jumper leads to . I need to receive this message ("$testmessage") from the Uno using this USB cable without using the leosticks usb connector. After receiving the correct messgae from the Uno i plan to use Serial to send data from the leostick to my pc.
I'm stuck trying to figure out how to receive this message from the Uno.
Currently the the USB 5v and ground is connected to the leosticks 5V, GND pins. The Uno powers on and the the tx led is flashing every 100 milliseconds.
Can i just plug the green and white wires from the USB cable into D0&D1 and except it to work?
(Uno plugs into usb cable in the image)
https://i.sstatic.net/M0kbb.jpg

While USB is a serial protocol, it's a completely different serial protocol than the RS-232-style logic-level serial protocol that the Serial library supports.  So the approach mentioned in the question has no logical chance of working.
Also, the USB electrical signal is differential (double-ended, or line-to-line, rather than single-ended, or line-to-ground).  So the mentioned approach has no electrical chance of working.
What may work is to wire from Tx on the Uno to Rxd1 on the Leostick, and from Rx to Txd1, unless that conflicts with the Leostick's USB-Serial link.

I don't think this has any chance of working. You can't use USB to interface between the two devices, as the Leostick can't work as USB host. Your best bet is to use (software) serial.


text:
Making Servo Motor Automatically Move Based on Input
sorry if I sound incompetent, but I know nothing about coding. I have a group project where I must sort various balls into different tracks. The final issue I have is that I must use an arduino for this portion. However, none of us know how to program, and the only experience we have is from doing the lessons from adafruit (copy and paste written code).
What I am attempting to do is attach a paddle to the tip of a high torque servo motor. I will then automatically feed the servo signals, ranging from 0 to 5. Each signal tells which position for the servo to turn to. Could anyone please help guide me in how to write this code? I was thinking of using
this guide for my motor. However it uses a POT. My project must be completely automated. The positons also are all within 180*.
Thank you!

Re “I will then automatically feed the servo signals, ranging from 0 to 5”, where do the numbers come from?  Are the positions equally spaced, or arbitrary angles?

The numbers come from another sensor, which detects which ball is coming. I was not told which type of sensor this is, but I do know that what is given from it is a number corresponding to a different ball.
As far as position, there is only 3 positions I wish for this servo to turn.
90* vertical, 45*, and 315*. So in total It will only need to turn 135* degrees from the farthest two points, 90*-315*

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

So you have a "number" and you want to set the servo to some angle. The logic is very simple:

If number is 0 then set angle to 90
If number is 1 then set angle to 45

etc.
How you "get" the number hasn't been specified, so I will assume you just have an integer with a value between 0 and 5 inclusive.
Setting a servo's angle is as simple as writing that angle to the servo:
servo.write(45); // Set the angle to 45 degrees

So how do you join the two together?  Well, there's three different ways that spring to mind.

A string of if statements
A switch construct
An array

The first one is just like the bullet points above, just written as C:
if (number == 0) servo.write(90);
if (number == 1) servo.write(45);
... etc ...

The second method is very similar but can be more efficient when you know you only ever select one item from a list of options.  Read this to see how: http://hacking.majenko.co.uk/time-to-make-a-switch
The third option, the array, is especially good when you have a lot of options to manage and they are all the same result with a different value:
const int angles[6] = {90, 45, 315, 0, 0, 0};

// ... later ...
servo.write(angles[number]);