text:
Do Water sensors Rust?
I'm new to Arduino and still learning the basics.
I tried reading water level by using this sensor I left it in the water for about 5 minutes then I noticed it changing color (some parts darker than other)like the water is still over it .
So my question is do Water sensors really rust ? or is it my own imagination?

The color change you observed is probably caused a galvanic reaction between metals in the sensor and other metals that are present, such as the tank, piping, or dissolved metals in the water. Do not modify the parallel strips of metal on the sensor. This will render the sensor useless. To reduce the effects of galvanic corrosion, you can:
1) Reduce the current passing through the sensor. To do this, sample the sensor less frequently. For, example, sample it once every second.
2) If possible, remove sources of metal from the water. For example, replace metal pipes with PVC, and replace screws with plastic zip-ties.
3) Move the sensor further away from sources of metal.
4) Place a grounded sacrificial zinc in the water, close any other metal sources. If the water is circulating, place the zinc near the inflow opening.
5) Remove stray or electrical currents from the water. Connect the "-" pin (GND) and the water to the same ground.

I agree with every statement in this response but the one about the strips on the sensor.  From experience, This sensor is not effected or changed from tining the strips.  That is not to say that other sensors would not be more sensitive to this.  Wonderful insight!

Most metals will tarnish, rust, or corrode when left in water, especially in the presence of an electric current. To be safe, a water sensor should either be gold-plated or made of a conductive, insoluble, non-metallic substance.

& running AC through it helps as well - reverses the electrolysis process every cycle.

I have that same sensor, and found a couple things to help with this issue.  The first thing that I did with min was tin the contacts with solder (All 10 'sensor contacts' all the way down) and also, using the GPIO, only power it on about 1 second before I read it, and turn it off immediately after.  By reducing the amount of time current is running through it, you reduce the tarnish, and the solder i tined everything with is less likely to corrode than the raw contacts.

I'll use GPIO only at the moment until I get a soldering iron.
Thanks !


text:
How to use an 8x8 LED Matrix?
I have a LED Matrix just like this one

but couldn't find the data sheet for it (1855AS)
I asked around in my country and one guy told me to try attaching one side to 5v and the other to GND. Some LEDs worked fine and others didn't light up at all. In the end one if not more got burned.
So I'm here asking if anyone can tell me a way to figure out how it works.
I would appreciate the help!

BTW I don't have an Avometer!

I think all those 8x8 matrixes are pretty much the same. Here is some datasheet. I wouldn't be surprised if the pinouts are exactly the same. See bottom of page 3, for how these displays are wired inside. Also, you definitely need to use resistors, or the leds will burn out.

That's what they told me! But I don't think this one is. Would 220ohm resistors be enough ?

220 is a very nice value.

As you are testing the correct functionality of LEDs on matrix board, which means the LEDs are multiplexed together. The fastest way to check the pinout is to use a multimeter in continuity test mode and then connect the positive or signal wire ( the red one ) to an fixed pin  (usually start with one ) and the with negative or gnd wire ( the black one ) connect it one by one to the all the remaining pins. When you have finished move the signal wire to the next pin and rescan all the pins, repeat all the steps for every pins on the matrix board.
I don't recommend you to use directly 5v because it can be dangerous and you can damage the LEDs of the matrix display as there isn't a current limiting resistor.

Would it be ok if I used 3.3v and/or a 220ohm resistor and check each pin ? I don't have a multimeter at the moment. And thanks for your help!

I suggest you to use 3v3 with 220ohm resistor in series.. That will be OK.

You could check from where you have bought it. Maybe they have datasheet.
I found one similar, but before you must check if everything is the same and then do testing with power. LuckyLight

That might take a while, It's a bit far from where I live. And I don't think they'd be helpful.

What do you mean by that???

I mean the shop I got this matrix from is far from where I live and the people who work there won't be very helpful because everyone around here acts like they know everything which they don't. I said I asked around right? And just like that two got in a fight each one of them says he's better than the other. And thanks to them some LEDs got burned from the matrix! I'm sorry for speaking like this .. and thanks for your help ! :)

Dude... I gave you datasheet. Conect some resistors like 1k ohm and then test. You do not need to ask someone;)

With 1k resistor it will shine not so bright but you wont damage leds...

Thanks a lot :) I'm still learning so I don't understand everything in the data sheet but will try my best ! Thank you ^^

source: Stack Exchange

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

sort: votes


text:
Problems with (somewhat) large boolean arrays
I am writing a simple Conway's Game of Life implementation just to get to grips with the "Nokia 3310" LCD and I am having problems with boolean arrays. I am using an (unofficial) Arduino Pro Micro 5V/16MHz
Here's the code that is causing me trouble:
boolean buffer[84][48];

void setup(){
  for(int i = 0; i < 84; i++){
    for(int j = 0; j < 48; j++){
      buffer[i][j] = true;
    }
  }
}

void loop(){}

When I upload this to the Arduino, it seemingly freezes up with the RX led on and its COM port stops working. If I want to upload any other sketch, I have to manually pull the RST pin LOW (since the Pro Micro doesn't have a reset button).
I've been playing around with the code and found out that the source of problems is this line:
buffer[i][j] = true;

It also doesn't matter if I use true or false.
I have tried debugging with Serial to the computer, but the Serial communication doesn't work at all, so I tried using an LED to find out where the problem is. I don't have any "regular" LEDs on me, so I had to try with an Adafruit NeoPixel. The outcome was quite interesting. When I comment out the problematic line, everything runs just fine, the led goes red for 500ms then it blinks white every time the problematic line would run and then it goes green and stays that way. With the problematic line in place, the LED won't do anything, even turn red, which I put much earlier in the code than the source of the problem.
Does anybody have any insights that might be useful? (Also, I really hope it is not some stupid typo, I swear I read it through about twenty times)

According to http://arduino.cc/en/pmwiki.php?n=Reference/BooleanVariables, "Each boolean variable occupies one byte of memory." Meaning you are trying to use 4032 Bytes of RAM with your array which I assume you do not have (whatever this unofficial Arduino is -- it's likely to be less than that: the ATmega328 of the Arduino Mini has 2 kB of SRAM, the ATmega32u4 of the Micro has 2.5 kB).
You could try with a quarter of the field size for a start and see if that makes your problems go away.

It's usually the ATmega32U4 in a Pro Mini I think. That still only has 2.5 KB SRAM though.

The Micro has an ATmega32U4 (I guess you mean that, google says it's the same for the Pro Micro), but the Mini has an ATmega328. (I only know Pro Mini, that's why I assumed it's more like that :)

Yep, that was it. The possibility crossed my mind, but I guess I forgot to check it. Just to clarify - the Pro Micro is functionally identical (AFAIK) to the Micro, but slightly smaller (12 0.1" pitch header pins on the Pro Micro and 17 on the Micro) and was designed by SparkFun instead of Adafruit. Also, by unofficial I meant from eBay :)

Well, if each boolean takes a full byte, as fuenfundachtzig says, then you might try some bitwise hacking to fit 8 bools per byte on your own.  Maybe something like this:
unsigned int16 buffer[84][3];  //16 bits * 3 = 48 bits, per the original example

void init_buffer()
{
    for(int i = 0; i < 84; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            buffer[i][j] = 0xFFFF;  //all TRUE: each F is hexadecimal for 0b1111 in binary
        }
    }
}

bool get_buffer(unsigned int8 i, unsigned int8 j)
{
    unsigned int16 k = 0;
    while(j >= 16)
    {
        j -= 16;  //I can do this because i and j are passed by value and are therefore separate copies inside this function
        k++;
    }
    //now k is the array index and j is the bit position inside that element
    if(buffer[i][k] & (1 << j))  //(bitwise AND with 1 shifted left by j positions, so we only care about that bit)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
    //or, if your compiler supports it, you might replace the if/else with:
    return (buffer[i][k] & (1 << j));
}

As for the stylistic differences between my example and yours:

I like to completely specify my datatypes if I can.  Don't rely on the compiler to do what you expect because it may have options to that effect that are set differently than you think.
I like to use brackets for everything, even single statements, and make them obvious.  That way, there's no confusion later or additional bugs because a second statement was added to what used to be a bracketless single without adding the brackets.

The only exception to that is when I'm writing a series of almost-identical if's and I put both the if and the action on the same line, all aligned so that the subtle differences line up and become obvious.

I'll have to do something of the sorts. The good thing is, that the display I am working with takes 504 bytes to draw the full screen (84 columns of 6 bytes), so I will probably use bytes instead of uint16_t, but I will have to make sure bytes don't have any similar overhead.
Regarding your stylistic advice, I haven't yet had any problem with using just int, but I will have to look into it to know, when it causes problems. Also, I do a similar thing with brackets, but I like to leave the opening bracket at the end of the line after the control structure.
Cheers

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


text:
Device manager sees my nano as FT232 USB UART not as COM port
Until yesterday I had 2 arduino nanos (atmega328, 16Mhz, 5V), and they worked fine,when  I changed the cable and was able to upload code to them. Then I tried to make a breadboard arduino, but my PC (win8.1) was unable to see my FDTI 232RL USB2Serial converter as a COMPORT, so I tried to download drivers but nothing worked out.Anyway I decided to reinstall windows and now one of my Nano works just fine, but the Other appears as a FT232 USB UART at the device manager,so I stepped back... Can anyone help me with that?

Are they genuine Arduinos?

@IgnacioVazquez-Abrams may be related: http://hackaday.com/2014/10/22/watch-that-windows-update-ftdi-drivers-are-killing-fake-chips/

@AnnonomusPenguin: Hence the question.

Thanks everyone who answered me, the hackaday post solved my problem. I was able to unbrick my nano-clones.Now they work just fine.


text:
arduino usb android controller
i am pretty much newbie with arduino and want to start my first project so i may be asking stupid questions.
My goal is to make usb controller for android tv (running on raspberry pi or s905). I want it rotary, so turning will be "arrow up/down" or "left/right" (i dont know exact android tv menu controlling) and "return" on push. I found this rotary switch on ebay, is it suitable?
To communicate i want to use arduino. I found libraries MouseKeyboard, which might be suitable for my needs, will arduino nano support this library or do i need arduino uno?
Do i need something else, or just connect switch to pins on arduino and plug arduino to raspberry?
As i need this controller to operate in menu, not just in some application, will this work as some mouse or keyboard connected via otg to android and function immediately?
Thanks.

Yes, that rotary encoder is fine.
Neither the Nano nor the Uno support that library. You will need a device that has native USB support such as the Leonardo or Due, just like it says on the page.
The rotary encoder library you use will tell you how to connect it.
As for specific Android functionality, you will need to ask on Android.SE.


text:
Calculate time between 2 data of a sensor
I'm working on a project in my university and I'm having a trouble in calculate time. I have a conveyor and an IR sensor which I use to calculate the maximum and minimum distances of a box when it is moving on the conveyor. Then I want to calculate the time between the max and min distances of box. I have used millis() for timing but it is not accurate.
Here is my code:
int IRpin = 0;
float volts, distance,firstdata;
int k = 0;
float min;
float mang[150];
int m;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20)
{
Serial.println(distance);
mang[k] = distance;
k++;
}
else
{
if (k > 0)
{
  min = mang[0];
  for (int i = 1; i < k; i++)
  {

    if (min > mang[i])
    {
      min = mang[i];
      m = i;
    }
  }
  firstdata=mang[1];
  }

I store data the sensor send to me in an array. Now I want to calculate the time between firstdata [mang(1)] and [(min)]. I use 0A41SK Sharp IR sensor.
Thank you for your time and sorry for my bad english.

1st - please format your code properly. Most people won't bother looking at it the way it is now. 2nd - I see no millis() or any other timing calls in your code. 3rd - if you only use the mang array for finding the minimal value - you don't need an array at all - just remember the last minimal value (and eventually its time) - this will save you 600 bytes of memory and the corruption caused at the 151st reading of distance < 20. 4th - 'min' is not a good choice for variable name - it is often defined as a macro, which will cause you problems.

millis() not accurate enough? What kind of accuracy do you need?

Ok, yea...Please format this a little better (properly tabbed line spacing and such), and comments would go a long way to understanding this, because chances are people don't want to invest the time to decipher what's going on here without them. I'm not entirely sure what is going on here, but I'll just suggest what I would do in my understanding of the question, which is how to detect what the minimum and maximum value of the distance is and record the time at which each of these moments occurred.
I would have a float value to store the maximum and minimum distance as well as their times, and simply on every iteration of the loop check if the position was greater than the previous maximum distance or shorter than the previous minimum distance. If either of those are true, set the maximum/minimum distance to the current position and set the maximum/minimum distance time to the current time, using millis(). There's no reason I can see, if I'm understanding this correctly for an array to store all the data, it's just taking up memory space from what I see.
Hope this helps a bit, and, if I'm totally off base, again I'll emphasize the utility of comments in readability. Hope this helps and good luck.

I dont care much about code formatting, so i'll just leave you with 'indent' to satisfy the coding snobs that may have been flogged just a bit too hard by their programming teachers.. To the point (one of them) now; You're using int for your measurements against millis(). This will not fly if your measurements exceed 32 seconds, or if the runtime of the sketch exceeds 32 seconds. Please use unsigned long for all variables referencing millis().

I'm not exactly sure what you're trying to achieve with your code but from what i understood is that you're taking distance measurements to see if an object is front of your sensor and then you want to measure the time interval between each object passing by ....right?
Assuming my understanding is correct, what you need to do is first measure the distance to know if an object is there or not, and then if there isnt an object you start a 'timer' until an object appears and then print thy data to Serial Monitor....
//this is a comment...they make code easier to use and understand for you and others .....
int IRpin = 0;
float volts, distance,firstdata;
//don't Know why you need those...
/*int k = 0;
float min;
float mang[150];
int m;*/
boolean Exists;
boolean measured;

int startTime;
int Interval;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20) //an object is in front of the sensor
{
Serial.println(distance);
Exists = true;//object is present
}
else
{
Exists = false; object isn't present
}

    if (Exists == false) {// no object present

if(measured == false){//to see if the timer already began
    startTime = millis();
    measured = true;// so the code only runs once
    Read = true; //so that we only measure the time when the timer begins
    }}
else
{ if(Read == true){
Interval = millis() - startTime;
measured = false;

Read = false;

Serial.print(Interval);
}}

What I'm trying to do in the last snippet is to make sure that we only measure the time when nothing is present.

Please excuse any errors i might have done.I'm half asleep and in mobile so things look different


text:
Arduino Uno WebClient program not returning the exepected output
I have connected the Ethernet Shield to the Arduino Uno Board and do get the following error when I execute the WebClient program. Look like it's getting connected to the internet, because I am getting a response back. But, this is not the response I was expecting in the Serial console.
Can someone please help me?
connecting...
connected
HTTP/1.0 302 Found
Location: http://www.google.co.in/search?q=arduino&gws_rd=cr&ei=ap_2VJL0JqW_mwWc7IG4DQ
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=8d5e7471bdf891d2:FF=0:TM=1425448810:LM=1425448810:S=-gaX4w3RUPOn7YjK; expires=Fri, 03-Mar-2017 06:00:10 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=WNjkn45lMWxFTVOlW_qv6YQonIaJjd3_Aakemy7ddZ7_JqmPgaZPv_aGdqE8OptRIeV2vrYlFZRo1us7JgmnSJlmO0mfGdSNxEckDkAsqXcL7r-S7jU04eiH_zl8Q39_; expires=Thu, 03-Sep-2015 06:00:10 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Date: Wed, 04 Mar 2015 06:00:10 GMT
Server: gws
Content-Length: 281
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic,p=0.08

<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE>

302 Moved

The document has moved
here.

disconnecting.

You should learn HTTP protocol: you get a 302 status that gives you a new URL Location that will give you the expected result.

@jfpoilpret I should have been a bit more explicit in the OP. The requested URL and the new URL in the response are all the same.

OK, then did you copy the cookies set in the first response into the headers of the second request? Not sure how Google uses them but they are probably here for something...

nope - I am not setting the cookies - just calling the url

Well I guess this is what's missing: your program should first perform the normal request, then if response is 302, get the new location AND the cookies, prepare a nrew request to this location and send along the previous cookies; I think the last response should be OK then.

@jfpoilpret would you care to add an answer explaining how to do that? Thanks!

I wish I could, but my knowledge of Arduino Ethernet API is too limited (near 0) to provide a full answer with sample code; that's why I only provided some hint here as a comment. Anyone who can provide sample code to do that is welcome to post it as an answer. I guess that should be pretty easy for someone who knows the Ethernet API well.


text:
Detect external ground on an input pin
I am making a bike alarm for my bike. I haven't started yet.
Basically, I'm thinking of a pin to be connected to the metal post (to which the bike is locked.) I want to detect if that connection (to the ground via the metal post) is broken.
Is that possible?

If there is another connection from there to the Arduino's ground, and if you have an internal or external pullup resistor on the pin, then yes it should be straightforward.

I only want one 1 single wire from arduino to detect ground, not two/a loop

That's not going to work very well.  You could try something with captive sensing but it is likely to be unusably sensitive to false alarms (wind, rain, other bikes in proximity, even current leakage via tires wet with road anti-icing brine, etc).  The whole project is a bit impractical anyway - how will you protect against disconnecting the power source?

Well I was considering the fact that the thief could connect the wires directly excluding the post so preventing an alarm at all. Do you have any suggestions?

@ZeeshanAhmad do you use a chain, wire, or a bike lock to lock up your bike? If so, you could use the metal of the chain/wire/lock to form a circuit. If the circuit breaks (the thief cuts the chain or opens the lock), then we know to set off the alarm. Just a thought

But the lock is itself just one piece, so I can't defer between a locked and a broken/unlocked state. It is one piece of metal conductor.

How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.

I will have to try this, and see how it goes


text:
Arduino YUN server crashes after few hours!
I have made a simple server using the YUN SERVER and CLIENT Libraries./
The server runs on a loop and waits for a client to connect. After connection it sends the client a simple message and then disconnects the client.
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

#define PORT 6666
YunServer server(PORT);
int pin =13;

void setup() {
  Serial.begin(115200);
  Bridge.begin();
  server.noListenOnLocalhost();
  server.begin();
}
void loop() {
  YunClient client = server.accept();
  if(client.connected())
  {
    digitalWrite(pin,HIGH);
    //startup
    startup_msg(client);
  }
  else
    digitalWrite(pin,LOW);
    delay(500);
}
void startup_msg(YunClient client)
{
    client.print("SAndTerm");
    client.stop();
}

Well this code runs smoothly for few hours. But after that, it stops responding to any client request. I guess the server crashes.
I have to restart the YUN to get it working again.
Is there anyway I can run this without it getting to crash?
Well I want it to be running just like a normal server would.

Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date.
Here a link on how to do this
Another thing to try is to add delay(50); at the end of the loop() function. It prevents the processor from doing lots of work.

My YUN is upgraged to the latest firmware, and if you closely see the inside loop() there is already a delay of 500ms.
Anyway, I am just confused. It is suppose to behave like a server without any hassle. But its not.

I just noticed that. Maybe 500 millisecond is too much delay. 50 milliseconds is recommended on the Arduino website.
I would be happy to fix this easily by running it on my side here but I don't have YUN. I have Uno and Mega.
It looks like you are writing HIGH to pin 13 without making it OUTPUT. Assuming your goal is to turn on the led connected to pin 13, you should first make the pin OUTPUT once in the "setup()" function.
pinMode(pin,OUTPUT);
Also comment or remove Serial.begin(115200);  to see if that is the problem.
Finally, is this the whole code you are having problem with?

Thanks for your insights! Really helpful!
Well, i removed Serial.begin(115200) and set the pin 13 to output.
Now I just have to test this for few hours and see if it stays put without crashing.
And yes, this is the basic code I have now, but will be developing it for further work. Just needed to know if this was stable before proceeding!

Ok. Let me if it stops working again.

It has been over 24 hours. Did it work?

Sir, Its been 24 hours and its running without any problem.
I think you have fixed the problem.
Still I will be running it for few more days to check for any other issues.
Anyway it seems to be ok now! :)

Glad I was able to help you.


text:
Rounding to the next upper (or lower) 0.1
I'm reading from a temperature sensor. I get float values with 2 decimals. I want to round them to nearest 0.1.
This is my sketch:
void setup() {
  Serial.begin(115200);
}

void loop() {
  float temperature = 21.81;
  float rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.81 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.79;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.79 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.77;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.77 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.70;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.70 ->");
  Serial.println(rounded_temperature);
  delay(1000);
}

This is the output:
21.81 ->21.85
21.79 ->21.75
21.77 ->21.75
21.70 ->21.75

And this is the output I would... Rounded to "0" and not "5".
21.81 ->21.80
21.79 ->21.80
21.77 ->21.80
21.70 ->21.70

temperature could be also negative

this is not an arduino question ... it is a general programming question

@jsotola OP is using the round function, which is part of the Arduino library.

Using roundf() function:
float rounded_temperature = roundf(temperature * 10) / 10;

float variables do not have a number of decimal places. They are merely an approximation anyway. Instead it's when you print that you decide how many decimals to display.
Serial.println(temperature, 1); // Print with 1 decimal place

Or to put it into a string:
char buf[8]; // Room for 7 characters plus NULL terminator
float val=23.81;

dtostrf(val, -7, 1, buf); // 7 characters with 1 decimal place and left aligned (negative width)

mmm... My trouble is that  I send that data via MQTT to HomeAssistant. I want to send them as "my format" and not with the .50

Then format it into a string and send that. Use dtostrf to format a char[].

Isn't there a native function to round to .x0 instead of .50 ?

@sineverba Even if you do "round" the float chances are it won't be rounded. Like I said - floats are only an approximation. The only way to fix it to a specific number of digits is to change it to a different format - such as text. With dtostrf().

I often store the floating point data that I get from a sensor in integer to preserve the decimal precision that I want by multiple it by 10 before casting it into an integer. It is easier and more efficient (compare to string or float) to send over to another system. This is also how many sensors representing and store the floating data (e.g. TMP275) as well.
To achieve what you want, here is what I would do:
#include <math.h>

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

  float i=21.81;
  float j=21.79;
  float k=21.77;
  float p=21.70;

  // convert to integers
  int l = (int) round(i*10);  // 218
  int m = (int) round(j*10);  // 218
  int n = (int) round(k*10);  // 218
  int o = (int) round(p*10);  // 217

  // Convert back to actual floating point for display
  Serial.println((float)l/10);  //21.80
  Serial.println((float)m/10);  //21.80
  Serial.println((float)n/10);  //21.80
  Serial.println((float)o/10);  //21.70
}

Ok.... but 21.81 rounded is 21.80, not 21.90...

I change it to use round() instead of ceil().

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


text:
connecting two keypad with arduino
I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.
I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


text:
No data from U-Blox Neo-6M
I'm trying to get Neo-6M module to work with Arduino Uno, but it just isn't transmitting any data. It is getting 3.3V.
I've tried measuring the Amps and I got zero, so I'm afraid that the module could be broken.
Neo-6M wiring:

Arduino wiring (power):

Arduino wiring (data):

Arduino code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. "));     Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

I have tried several Ardiuno GPS sample data and could not get any data, but
I just used this 10lines software, and got data.

I run my board from the 5v Arduino tap as it has a 3.3v low drop off voltage regulator on board. So my belief is that you should also tap off the Arduino boards 5v supply.

Mine draws about 60ma from the Arduino board. The device should get a fix, then start transmitting over the tx line.  Indicated by the 'Position Fixed' led indicator on board, flashing once a second (at 9600 baud.)
Good luck, keep in mind that these boards are only about $7.50 on Amazon, order a couple for peace of mind. :)

It isn't enough to power the module with 3.3V. You also have to level-shift the Arduino's 5V TX signal to 3.3V that is acceptable by the GPS module's RX pin, using a 1:2 voltage divider.

You should also know that the Arduino's 3.3 V pin can't source more than 50 mA; your module's current draw may sometimes exceed this limit (max is 67 mA). Instead, connect the Arduino's 5 V pin (which can source up to 500 mA) to the VCC of the GPS module through an LM1117T 3.3 V regulator:

The input goes the Arduino 5V pin and the output goes to the NEO-6M VCC. Connect all GNDs together.
Then run a basic sketch like this:
#include "SoftwareSerial.h"

SoftwareSerial gps(4,3);

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

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

This will basically make the Arduino grab any NMEA data sent by the NEO-6M and forward it to your PC's serial monitor. If you receive legible data, it means you've established comms with the module. You can then upload your original sketch.

Acording to all those tutorials out there on this module it IS enough to use 3.3V from Arduino. The problem is it isn't drawing any current from the Arduino. And I don't need to transmit any data to the module.

@freemanovec It doesnt matter if you need to transmit; as long as you connected the module RX to the Arduino TX, the IDLE voltage of the line is 5V going into the module. You can simply disconnect the wire since you feel you dont need it. Also, unless you've studied the library code, you don't know how it performs its task; perhaps it is transmitting data even if its only to initialize the module.

The factory default for a ublox module is to output NMEA at 1Hz, you should get something even with no GPS signal. Assuming no one has changed the defaults on the module.  If you have some way to connect the module to a PC (e.g. TTL-232RG-VREG3V3-WE ) then trying to connect with the ublox U-Center software is a good idea, that makes it easy to change the power up default behavior.

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


text:
Can't display text on LCD 1602
Today I tried to display some text with my Arduino UNO and a LCD 1602A screen. I did find some schemas online, but I cannot get any character or "black boxes" on the display.
I connect wires like that :
Pin 1 : GND
Pin 2 : +5V
Pin 3 : 50K Pot.
Pin 4 : Pin 7 from Arduino
Pin 5 : GND
Pin 6 : Pin 6 from Arduino
Pin 11 : Pin 5 from Arduino
Pin 12 : Pin 4 from Arduino
Pin 13 : Pin 3 from Arduino
Pin 14 : Pin 2 from Arduino
Pin 15 : +5V
Pin 16 : GND
You can see my setup here : https://i.sstatic.net/u32sj.jpg
The LCD screen is lighten up, but nothing else appears. Pot. is working (increase or decrease light). I tried to change the LCD with another, but both are not working. I tested some many code, here an example :
/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Do you have an idea ? Thanks !

Looks like your pot is wired wrong. It should be between VEE and GND with the wiper to VO, not between +5V and GND.

Sorry to ask, but what's VEE ?

Actually, ignore that - I am thinking graphical LCDs that have a different offset voltage requirement.

I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.

Wiring on the photo and description you provided are not consistent. On the photo, LCD-RS (PIN 4) is connected to D12 and LCD-E (PIN 6) is connected to D11?
If so, initialization must be LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


text:
Read sensor data repeatedly after specified time?
I want to read sensor data using analogRead() after every 5ms. I have read other answers to similar questions but what I'm confused about is:

let's say, I made a loop to read sensor data using analogRead() at the end of which I write delay(50)
it means it'll take some time to read data(adc) , then it'll wait for 50ms
time to execute loop isn't same for every iteration so we get the pattern as: some time for loop execution, delay of 50ms, some time for next iteration........and so on
I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?
Thanks

do not use delay() ..... see BlinkWithoutDelay  example sketch

You store the time (millis()) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.
Something like:
unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}

It waited for 5ms, then last measurement=0+5=5 ms. Then it’ll do analogRead().  Let’s say analogRead() took 10ms, then mills()- last measurement() = 15-5 ms=10 ms so the loop will do another analogRead() although it’s not reading measurement exactly after 5 ms. So this will only work if loop execution time is <5ms

Indeed. It can't magically go back in time. Was there any question there?

You do something like this
unsigned long timerMesurement = 0;

void loop()
{
  if (millis() - timerMesurement > 5UL) {
    timerMesurement = millis();
    int measurement = analogRead(A0);
  }
}

Sigma, it should be >= for the right interval. It should also be timermeasurement += 5UL; for a interval that is fixed in time without increasing delays, the return value of millis() could have increased since the previous line.


text:
Identifying Bootloader ttyACM# device
I'm using a modified version of Arduino Zero Bootloader. I am trying to write software to automatically detect which USB device the bootloader is currently running on in order to execute bossac.
I have noticed a few unique characteristics when using "lsusb -v". Things like "bDeviceClass" is always 2. and "bDeviceSubClass" is always 0; However, I do not feel confident in using these traits to identify the bootloader. Is there any clear indication of bootloader so I can find the correct ttyACM#?

Have you tried ls -l /dev/serial/by-id? On my Ubuntu, it shows aliases with rather indicative names (ProductID in particular) and the alias points to the right ttyACM#.

The only things you have at your disposal are what is in lsusb -v. Using those you can craft a udev rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.
Here is one of my rules:
ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
  ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
  MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

That links /dev/board/arduino/mega2560 to whatever /dev/ttyACM* node got created when it was plugged in.  That is in /etc/udev/rules.d/50-boards.rules
More on udev here: http://playground.arduino.cc/Linux/Udev
A useful command is udevadm info -a -n /dev/ttyACM0 which lists all the attributes for that device which you can then use in the udev rule.


text:
EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected
I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.
When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.
I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.
While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.
I am currently testing my code with a simple serial relay sketch, ESP on Serial3.
I have nothing else connected to ESP besides vcc, ch_pd, gnd, tx and Rx.
I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx
I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.
I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.
I appreciate any and all replies, and will provide any necessary clarification.
Thanks,
Vl4d

Just a couple of silly questions, but I'm not very much into ESP. 1) when is the LED supposed to turn off? 2) you put the voltage divider only on the ESP RX terminal (i.e. on the arduino TX), right?

A wiring diagram would help.
Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.

I would also check the ground on the components. All of the ground pins need to be connected together. IC's get flakey with grounding issues.


text:
How to directly solder wires to protoshield to connect them to Arduino pins
I bought an assembled Arduino Uno protoshield version 5, similar to this:

I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).
I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:

Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?

I think they cheaped out when assembling this board. Notice that you can no longer stack any other shields on top, since the female headers are further to the inside. My guess it the board was designed to have stacking headers inserted in the outside row, and have the inside row free for soldering. Those headers are however a lot more expensive.

@Gerben You're absolutely right... I haven't noticed that detail, and since I can not even stack more shields, the very purpose to keep the female headers doesn't make much more sense. One more reason to remove them and use the holes directly (besides having some extra headers to put elsewhere on the board, with a saner ordering). Would you elaborate your comment in an answer? I'd upvote and perhaps accept it!

Instead of soldering wires, consider crimping on male pins compatible with the headers.  Or get silicone insulated wire and neatly solder it where each header pin is soldered to the board - it is admittedly a skill, but develops with practice.

For the signals, get some AWG30 wire and solder them underneath to the female header pads. For power, get some AWG22 or AWG24 wire and solder them to the top of the male header pads.

I did it, but the result is visually and conceptually very ugly, not to mention the wire running under the shield got uncomfortably close to the ATmega exposed metal pins (not terrible, but, c'mon...). Would you risk to suggest why on earth they didn't provide tracks from the pins to any free island? Similar to the triplets found around the center DIP IC area? That would be perfect!

Probably because they figured that everyone would just drop a solderless breadboard in the middle and use the female headers as they normally would.

If you use insulated wire it shouldn't be a problem - hand soldering to a single row at .100" spacing gives you plenty of elbow room compared to what you would have to deal with in reworking more modern electronics, where sub-millimeter pitch (typically 4 to 5 times denser) is the norm.

Accepting the answer because it actually works, but I ended up desoldering the headers (not a pretty work to do). For anyone with intention to solder the wires instead of plugging, there are two good options for the v5 of the board: buying the - by the way cheaper - unassembled kit (and not soldering the female headers) or buying a model with stacking headers.

Other boards bring the header pins to prototype area pins, as I do here
http://www.crossroadsfencing.com/BobuinoRev17/UnoScrewSheild2016.jpg

While disclosed, this is pretty close to "advertising" to fit here

@CrossRoads - It says on your website: "Assembled cards are $21.50 and ship flat rate boxes. Shipping and paypal fee added to all orders." I'm assuming the price is in US dollars, so for Canadians, our cost for one of your shields would be $27.17 CDN plus shipping (USD * 1.31 Exchange rate), plus paypal fee (USD * 1.31 Exchange rate), plus "the big one", duty of approx. 33% in CDN$ (Canada charges it to us on delivery). So, how much is the shipping and paypal fee?

I do all payments in USD via paypal, so I only see USD and paypal I assumes shows you the in-country price.  Shipping to Canada via Priority Mail International® Small Flat Rate Box is $25.95, international paypal fee on the card + shipping is $2.35.  We can fit several in the same flat rate box if you want more than 1.

It looks like you are missing the solder-less breadboard piece for your shield. The shield I bought came with one, and some 2 sided sticky "foam tape" to affix it to the circuit board.

If you use the shield with the solder-less breadboard, then it would be not be feasible to stack another shield on top of it because of the height of the components and jumper wires plugged into it.
I tested my shield and found the same thing you did, the header pins are not connected to any of the connection points on the board. That is dumb indeed.
As CrossRoads mentioned in his answer, there are other options, such as screw terminal shields. They sell them for $2.43 USD on aliexpress.com Screw Terminal Shield.

authors: นรินทร์ โอษฐ์งาม


text:
Streaming sensor data over UDP using an Arduino Yún - how to do it and how fast could it be?
The company where I work wants to do a proof of concept for our new product, a force-sensing platform.
The platform contains four three-axial load cells, so we have 12 channels, which are to be digitized at 2kHz and 16bits. This gives us 2.000 dataframes per second, with 24 bytes of payload each.
Our proposed architecture is as following:

The analog signals from the cells is acquired by a dedicated data-acquisition board;
The digital stream is sent to the ATmega on Yún over SPI;
The data is then relayed to the Atheros over Serial;
Finally, the data is transmitted over UDP (or TCP).

I wonder if it is a sensible way of doing it, with the following questions:

How would one normally use the Ethernet functionality? Can I call a function on the sketch, or do I need to put some program or script in the Linux, calling it from the sketch?
What would be the maximum transmission speed (in bytes per second) from the ATmega side to the Linux side?
What would be the maximum throughput of the Ethernet?

I have calculated 24 bytes * 2000 = 480 bytes per second, or a baud rate of 480 * 8 = 3840bps. Is that right?
I would appreciate any help, it could be just a link to the proper information resources.

The Yun is really two different computers (one AVR and on Linux) connected by a serial link. Basically the AVR is connected to a serial console on the Linux machine, so you can "type" commands into Linux by sending strings out the serial port from the AVR.
The serial link normally comes up at 250,000 buad, so that should not be a bottleneck for your application.
Typically, the AVR will "type" a command to run a Python program on the Linux side (called the Bridge) that will then communicate with AVR code using a high level protocol. Unfortunately, this "bridge" connections tends to be slow and flaky.
But you could do what you want very easily by just pumping netcat commands into the Linux machine from the AVR machine every time you wanted to send a UDP packet out. The overhead would only be a few serial bytes per packet (you'd send "nc -u   \r" where everything but data is likely the same for every packet).
Here is an example of a program that runs on thew AVR and periodically reads some data from temperature sensors connected via 1-Wire, and then runs a "curl" command on the linux console to record  the readings to a server...
https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino
In your case, your replace the 1-Wire reading code with SPI reading code, and replace the "curl" that sends HTTP data command with an "nc" command that would send a UDP packet (using the "-u" parameter).
With this technique, I think you could get something working very very quickly and likely easily meet your data rate requirements.
Note that while this is a great technique for getting a proof-of-concept working quickly, I would not use a setup like this in production. Instead consider something like a BeagleBone Black where you could read the SPI data and send the UDP pack in a single C program that ran as a normal Linux process.


text:
Reducing read time for reading DS18B20 temp sensors
I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances).   This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.
I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.
// Dallas 1 Wire (Main Area):

 //  ds.reset_search();
 //  delay(250);
  while (ds.search(addr))
  {
    for( i = 0; i < 8; i++) {
      Serial.print(addr[i], HEX);
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
    }

    ds.reset();
    ds.select(addr);
    ds.write(0x44, 0);        // start conversion, with parasite power on at the end

    delay(1000);     // maybe 750ms is enough, maybe not
    // we might do a ds.depower() here, but the reset will take care of it.

    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad

    for ( i = 0; i < 9; i++) {           // we need 9 bytes
      data[i] = ds.read();
    }
    raw = (data[1] << 8) | data[0];
    if (type_s) {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
    } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      //// default is 12 bit resolution, 750 ms conversion time
    }
    celsius = (float)raw / 16.0;
    Serial.print(":");
    Serial.print(celsius);
    Serial.print(",");
  }

I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors.  My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.
Is it possible to remove this delay after reading each sensor ?

Which library do you use? This one seems to do 'bulk' reading by default.

Reducing the bit resolution will reduce the time required, however some libraries get the resulting conversion entirely wrong, and need to be repaired if you do this.

After nearly a year and a number of experiments later, I've learned a little bit more about using these devices:
Issuing the sensors a Skip ROM command followed by Convert T command starts all devices converting temperature at once (pg.11 of the datasheet). Then you need only wait one delay period of {750,375,188,94}ms for a {12,11,10,9}-bit conversion, respectively, before you can start reading back the temperatures.
If the devices are being powered parasitically, the bus will need a strong pullup during the conversion; the 4.7KOhm pullup is not sufficient (pg.5 of the datasheet).
An arduino pin can source 40mA and I've found that a second pin directly bypassing the 4.7K pullup without the suggested transistor, will source enough current for at least 3 sensors (as many as I've tried so far) and I assume the technique could be extended to more pins. The strong pullup must be switched on within 10uSec after the Convert T command and kept on for the duration of the conversion. The 10uSec spec pretty much means you have to do this in the library.
I keep an abbreviated DS18B20 library around in which I assume the sensors on the bus are related, so it sets all of their resolutions at once and starts their conversions at once, and assumes that the bus is parasite-powered, which mine are, so it switches a specified pin as a strong pullup. I give up some flexibility that the full DSTemperature library would allow but it satisfies my temperature measuring requirements (so far) and simplifies my application code by black-boxing the above techniques.

Doing a search every time is quite inefficient. The search function is for if you don't know the device address - and it takes a while to do. In your case, presumably the addresses will never change. Find the addresses and hard-code them into your code. Or if that isn't practical, store them in EEPROM. And if even that isn't practical find the addresses once in setup.

Next, you need a delay while you take the temperature readings. Why not parallel those up? In a loop, tell all the devices to take a reading. Then wait one second. Then read them all (in another loop). That way the one-second delay is shared between all your sensors.
However from the page Gerben linked:

And it is NOT possible to run DS1820 sensors on a simple pull-up resistor. During the "Conversion" phase, it needs more power. And there are Application Note discussing this in length.

That suggest that if you are using parasitic power, my suggestion won't work too well (having multiple devices taking readings would make it worse).

I found this code on my disk from a couple of years ago. There don't seem to be any delays between reading sensors. There is a delay at the end of the main loop, mainly to stop spamming the serial monitor.
Notice the comment:

Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

See if that works for you.
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Streaming.h>

// Data wire is plugged into port 10 on the Arduino
const byte ONE_WIRE_BUS = 10;
const byte TEMPERATURE_PRECISION = 10;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress myThermometer [10];
int deviceCount;

void setup(void)
{

  // start serial port
  Serial.begin (115200);
  Serial << "Dallas Temperature IC Control Library Demo" << endl;

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial << "Locating devices..." << endl;
  deviceCount = sensors.getDeviceCount();

  Serial << "Found " << deviceCount << " devices." << endl;

  // report parasite power requirements
  Serial << "Parasite power is: " << (sensors.isParasitePowerMode() ? "ON" : "OFF") << endl;

  // method 1: by index

  for (int i = 0; i < deviceCount; i++)
  {
    if (sensors.getAddress(myThermometer [i], i))
    {
      Serial << "Device " << i << " Address: ";
      printAddress(myThermometer [i]);
      Serial << endl;
      sensors.setResolution(myThermometer [i], TEMPERATURE_PRECISION);
    }
    else
      Serial << "Unable to find address for Device " << i << endl;
  }  // end of for loop

}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

void loop(void)
{

  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  sensors.requestTemperatures();

  // now get all temperatures
  for (int i = 0; i < deviceCount; i++)
  {
    float tempC = sensors.getTempC(myThermometer [i]);
    if (tempC > -80)
    {
      Serial << "Device " << i << " Temperature: " << tempC << endl;
    }
    else
      Serial << "Unable to find temperature for Device " << i << endl;
  }  // end of for loop

  delay (1000);
}

Thank you for your answer.  I'm not using parasitic power, but my attempts at doing the readings in parallel failed-  possibly because my C skills are not great and partially because I am having difficulty understanding how the code works - or maybe it just can't be done.   Scanning the sensors on startup may be worthwhile doing at this point, but I deliberately scanned them in each loop so I could "hot plug" changes.

Look in the datasheet for using a "strong pullup" to supply extra current to to parasitically powered sensors. In my devices, I use an extra output port connected so as to bypass the pullup resistor (weak pullup), as a strong pullup. The datasheet shows an output port switching a transistor acting as the strong pullup. In practice, I've found that the port by itself sources enough current for 3 (the max I've tested) DS18b20 devices.

See amended post with another example.

Using a ESP32 with 2 cores you can read the temperature on two different ports simultanesly using two freedos tasks. Adding two sensors on one port is incresing the speed, adding 3 sensors per port is slowing down the number of reads per second.

In case the "Temperature Conversion Time (tCONV)" of each resolution is not fast enough ([MAX] 9-bit: 93.75ms; 10-bit: 187.5ms; 11-bit resolution: 375ms; 12-bit: 750ms), you can use more sensors.
For example, to get a half time (for 9-bit): 47ms:

You can use two sensors at the same measurement point, (they can operate in parallel , as long as the software can operate with each one of them) when reading one, the software starts converting the other.

Each one has its normal conversion time, but when doing the readings in an interleaved way, a shorter reading time can be obtained.
For 8 sensors, a time below 11.75ms can be achieved (for 9-bit).


text:
Communication between Arduinos using USB Host Shield
I'm working on a project that needs to use USB to pass serial messages between Arduinos (I can't use I2C or SPI for a few reasons – I especially need USB's support for hot-swapping and address allocation). So far I have the USB Host Shield set up on one Arduino Uno, connected to the standard USB port on another. It appears to be working, as can be seen when I run the board_qc:

The 'slave' Arduino is just running the following code:
void loop() {
  Serial.println("Hello");
  delay(1000);
}

On the master, I create a USB object from the USB Host library (https://github.com/felis/USB_Host_Shield_2.0).
USB Usb;

void setup() {
    Serial.begin(115200);
    Usb.Init();
}

void loop() {
    if (Usb.getUsbTaskState() == USB_STATE_RUNNING)
    {
        Usb.ForEachUsbDevice(&PrintAllData);
    }
}

void PrintAllData(UsbDevice *pdev)
{
    UsbDeviceAddress adr;
    adr.devAddress = pdev->address.devAddress;
    Serial.println(adr.devAddress, HEX);

    uint8_t msg = 0;
    uint16_t len = 0;
    uint8_t rcode = Usb.inTransfer(adr.devAddress, pdev->epinfo->epAddr, &len, msg);

    if (rcode && rcode != hrNAK) {
     Serial.print(F("\r\nData rcv: "));
     Serial.print(rcode, HEX);
   } else if (len > 0) {
     Serial.print(F("\r\nData Packet: "));
     Serial.print(msg[0]);
   }
}

I'm not getting any data through though. Does anyone have any suggestions? Or know of any helpful sample code?

It would be orders of magnitude simpler and cheaper to use the UART's possibly with a software protocol for addressing and tristating the drivers if you need to connect more than two.  If you really wanted to use USB, you would have to do a lot more than that - you would need to actually implement CDC/ACM protocol or whatever the slave talks, and if it is using a bridge chip, configure the baud rate, etc.

@ChrisStratton Are there any good Arduino libraries you know of for creating a simple USB slave device?

An ordinary modern Arduino already is a simple USB slave device, implementing either a vendor-specific USB serial protocol or a standard CDC/ACM function for the same purpose.

@ChrisStratton Yeah, I'm using Arduino Unos. It looks like the ACM class in the USB Host Shield will help.

Perhaps, but USB is still just about the worst idea I have ever heard of for communicating between ATmega-based Arduino boards...

@ChrisStratton Well, as I said in my question, I need the plug-and-play abilities of USB. I also would like to avoid needing more pins on the Arduino as more devices are connected. Both I2C and SPI don't support auto address allocation, and SPI needs an extra pin per device. This is why I'm trying USB. If you have any better suggestions, it's be great to hear them though.

No.  USB supports multiple devices even less than those two or uarts do - to support multiple devices with USB, you need an additional HUB which is not required with the others, and substantial additional software complexity too.  Add unique wiring to any of the others and it is easy to make them support auto-address assignment; but with a little cleverness they can support it without that too.

Can I point out that UART and USB use the exact same pins on most boards? In fact, USB is implemented by sending messages from the main chip to the serial chip using UART on most boards.

I'm voting to close this old abandoned question because it is based on a fundamental misunderstanding of USB and Arduino, and after two years of inactivity the poster seems unlikely to return to either accept an answer or revise their plans to something actually practical.

Have you tried this lib's documentation? It looks like just doing init() and then checking the task state is not enough.
Looking at the source code makes me think you might want to add a call to the main task/state machine, e.g. add a call to Usb.Task(); to your loop, before your if statement.


text:
SIM900 module not responding on hardware COM port
I've got my sim900 module working with arduino by using their software serial library, however, I want to eliminate arduino from the equation and have serial communication directly to sim900 module.
I'm using putty as my terminal emulator. It's serial is configured to COM1 19200 8 N 1 the same as device manager configuration for this port.
I connect straight from hardware serial on my PCs motherboard into serial-to-ttl interface board which connects to sim900 module. The board has 4 pins - VCC GND TX RX. They're all connected to my sim900 hardware serial as follows: VCC=5V GND=GND TX=TX RX=RX (Yes I know that it's always actually TX=RX and RX=TX, but when I connect it that way my interface board doesn't blink any led to indicate a transfer whereas it does when I connect TX=TX and RX=RX). The switch on the module is set to hardware serial pins as well.
So the only thing that happens when I send AT commands such as AT or ATI and press enter is that puttys cursor comes back to the beginning of command that I typed. No response.
I'm thinking that I'm not doing something that the arduinos software serial port is doing when it sends commands to sim900.
Can anyone help please ? It's literally been days of trying different configurations with no results.
In that time besides getting sim900 working with arduino software serial I verified that the hardware serial port on my motherboard is working correctly and the interface board is working correctly as well.

Are you providing an external power source to the sim900?

Yes, the external power is there

Well, all I can suggest is to add an Arduino. Otherwise, why ask us?

What you mean "why ask us ?" I'm asking because I have a problem that I want to solve !

Yes, but you have removed the Arduino from the equation, so I fail to see how we, the Arduino Stack exchange, can help you with it?

There has been a similar question about connecting to the hardware serial pins on an Arduino Uno. The schematics revealed that this might be a problem. https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf

Why would that be a problem ? I've had my interface board connected to arduinos hardware serial on the breakout connector and running a sketch that just prints out "hello world". I've had the "hello world" printing correctly  on putty. However, I wasn't able to program arduino this way.

@Majenko - Although SIM900 can be used with many platforms, it is most commonly used with arduino, hence the reason I'm posting here.

But you aren't using it with arduino. You had no problems using it with arduino, so your problems must be related to things that we have no knowledge about.

Where do you suggest I go then ?

authors: กานต์ แซ่โซว


text:
Is ATmega 328 on Arduino UNO already bootloaded?
I've seen many tutorials on programming a ATmega 328 via Arduino. If i'm right, the atmega need to be bootloaded. I thought to remove the atmega present on the arduino board. But to bootloading atmega we need another atmega on the arduino board. I can't buy a new one. After bootloading we need only one IC. So, can I remove the atmega which  is present on the arduino and directly program it? Can I consider it as a bootloaded one?

The original question is not answered. User wants to know if he has bootloaded the 328chip on breadboard, then after putting this chip on UNO board will it be programmed through the normal way of programming Arduino Uno board.

Arduino controllers are usually already bootloaded with Arduino. So yeah, you can use the chip on the arduino. Or you can buy a programmer to bootloaded empty chips.

In Arduino board, arduino controller means ATMEGA328P-PU already bootloaded. So, you can use directly. But if you buy only ATMEGA328P-PU chip or any other ATMEGA chip then you have to do bootloading for that.

Arduino boards come with the bootloader already installed. You only need to flash a bootloader to it if something damaged the original one. When you buy replacement chips, you generally have a choice of "factory fresh" ones (no bootloader) or ones that already have a bootloader installed, at a small difference in price.


text:
How to decrease a variable every second
I am trying to count down the variable "bankValue" with a certain costfactor
The code I tried will perfectly count down the bankValue..but..
#define INTERVAL_MESSAGE1 1000

unsigned long time_1 = 0;

const float CostFactor = 1.0;
float bankValue = 10.00;
const float CostButton1 = 0.004167;

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

void loop() {
    if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (CostButton1 * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
    }
   }

I want this the use in an if.
IF button1 is pressed then bankValue will be decreased by a costfactor every second.
I tried this in an if
  if(Pushed == HIGH){
    if(Pushed != StatePushed){
    Serial.println("Button1 OFF");
    }

    digitalWrite(relayPin, LOW);
  }else{
    if(Pushed != StatePushed){
    Serial.println("Button1 ON");
    }
                if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (Button1Value * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
        }
    digitalWrite(relayPin, HIGH);
     }

If the button is pressed, bankValue will decrease.
But when the button is not active....the millis timer keeps on running.
When switching on the button again, I see the bankValue decrease rapidly and not every second.
So the main question:
How can I decrease a variable every second when a button is active.

You are handling millis() wrong (should be if(millis() - time_1 >= INTERVAL_MESSAGE1) to avoid overflow issues), though that should not cause the seen behavior. Please show a full working sketch for the second code part

you may be attacking the problem from the wrong side ... you are checking the button state and then timing 1 second and decrementing the counter ... instead, you could continuously time 1 second intervals ... at each interval, check the button and act accordingly ..... you could also time 1/10 second intervals (ticks) and accumulate these when the button is pressed .... if 10 ticks have been counted, then decrement bankValue

Your basic main problem is that you don't know when the button was pressed.  Your timing algorithm always works from the "last time the value was decremented" - and that could be hours ago.  When you press the button the difference between millis() and time_1 could be massive, and it has to count up one second at a time until time_1 passes millis().
What you really need to do is separate out the button from the action. That makes it easier to manage.  You need to find the times when the button transitions from HIGH to LOW (pressed) and from LOW to HIGH (released). You're almost doing that right now, but not quite.  Then when you find the moment of being pressed you can say "From this moment forth you shall count."
For example you might change the first part of your code to be:
if (Pushed != StatePushed) {
    StatePushed = Pushed; // Remember the current state for the next time round
    if (StatePushed == HIGH) { // Released
        Serial.println("Button1 OFF");
    } else { // Pressed
        Serial.println("Button1 ON");
        time_1 = millis(); // Remember what the time is right now
    }
}

That then is a single atomic operation and you can now at any time examine StatePressed to see if the button is pressed or not, and also at the moment of pressing time_1 is set to the current millis() value, so you now know when the button was pressed.
Now you can add your second part using StatePressed as the trigger:
if (StatePressed == LOW) { // Button pressed
    if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (Button1Value * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
    }
}

However your method of comparing the time is not good. It doesn't handle the millis rollover problem.  Instead you should be using something more like:
if (millis() - time_1 >= INTERVAL_MESSAGE1) {
    time_1 = millis();
    ... etc ...
}

tried your solution. Nearly worked :-)

This answer is in response to Niles's answer based on Majenko's answer (phew! that was a bit of a mouthful).
millis() returns how many milliseconds have passed since your program started.
And your timing is off because you are adding INTERVAL_MESSAGE1 with time_1 i.e. instead of waiting for one second you are actually subtracting after every two seconds. Hence, you got half the value you expected. Remove that line. (And also don't use delay).
I have isolated your substracting part of the code. Run this and you should see the result (button is connected to D4):
unsigned long PreviousTime = 0;
const unsigned long THRESHOLD = 1000;
const float CostFactor = 1.0;
float bankValue = 10.00;
const float CostButton1 = 0.004167;

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

void loop()
{
  if(digitalRead(4) == 0)
  {
    if((unsigned long)(millis() - PreviousTime) >=  THRESHOLD) // You need to check time like this to avoid overflow
    {
      PreviousTime = millis();
      bankValue = bankValue - (CostButton1 * CostFactor);
      Serial.println(bankValue);
    }
  }
}

Note that millis() - PreviousTime is an unsigned long. No need to cast it.

I tried to use the solution post by Majenko and came up with something like this:
  if(Pushed != StatePushed) {
    if(Pushed == HIGH){
      if(Pushed != StatePushed){
        Serial.println("LED OFF");
        }
        digitalWrite(ledPin, LOW);  // turn LED OFF
        }else{
        if(Pushed != StatePushed){
        Serial.println("LED ON");
        time_1 = millis();
        }
        digitalWrite(ledPin, HIGH);  // turn LED OFF
        }
  }
         StatePushed = Pushed;

  delay(100);

  if(Pushed == LOW){
    if(millis() >= time_1 + INTERVAL_MESSAGE1){
      time_1 = millis();
        bankValue = bankValue - (coinValueB * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        Serial.print("€");
        Serial.println(bankValue);
                Serial.println(INTERVAL_MESSAGE1);
    }
  }

Pretty much how you suggested it...
but I realize I absolutely do not understand how millis() exactly works.
I have no idea what this does:
if(millis() >= time_1 + INTERVAL_MESSAGE1)

In a way, the loop works. But the timing is really off.
With my settings, every second subtracting 0.004167, should be 0,25 is one minute.
But it was only around half...0,13 or so

It is off because you are adding INTERVAL_MESSAGE1 with time_1. Just remove that line. And don't use delay.


text:
smart coding possible?
Is there a way to clean up this code...or do some smart coding?
In this example I use 6 relays, in the final code it will be 10.
Also I now use 5 switches and that will be 8, each with an own led. Now I only stated 1 led.
The code reads a button, and a few relays will get a signal. Also the buttonled will go on.
I will add more cases later. But I was wondering, is it possible/easier/just another way of writing the high/low to the relays and leds.
Can I somehow combine the LOWs or HIGHs within a case?
int relay1 = A5;
int relay2 = A4;
int relay3 = A3;
int relay4 = A2;
int relay5 = A1;
int relay6 = A0;

int led1 = 3;

int sw1 = 5;
int sw2 = 6;
int sw3 = 7;
int sw4 = 8;
int sw5 = 9;

int sw1Status, sw2Status, sw3Status, sw4Status, sw5Status;
int order = 1; // default is to set all relays off.

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

  pinMode(led1, OUTPUT);

  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
  pinMode(sw5, INPUT_PULLUP);

}

void loop() {

  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);
  sw5Status = digitalRead(sw5);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) {
    order = 5;
  }
  if (sw5Status == LOW) { // button 4 toggle
    if (order != 7) { // if order is not equal 5 turn on relay 1 & 4
      order = 6;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, HIGH);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, HIGH);
      digitalWrite(led1, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(led1, LOW);
      break;

    case 6: // if order equals 5
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

What? I really don't understand, what you are trying to ask.

haha..ow  sorry! What I am trying to ask....is this code OK? Or can it be simplified?
eg. Is it possible to combine LOW:  digitalWrite(relay1 relay2 relay3, LOW);

use arrays to hold variables ... also use arrays to hold the case relay values

If all are handled the same and they don't have individual names, arrays and for loops are what you are looking for.
const byte relayPins[] = { A5, A4, A3, A2, A1, A0};
const byte ledPin = 3;
const byte swPins[] = {5, 6, 7, 8, 9};

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  for (const byte relayPin: relayPins) pinMode(relayPin, OUTPUT);
  for (const byte swPin: swPins) pinMode(swPin, INPUT_PULLUP);
}

Even arduino C++ nowadays understands the foreach syntax.
BTW: for your final pin count you'll need other/additional hardware. Either a Mega or shift registers or port expanders.

I also figured out that I run out of pins on my UNO boards, that is also why my code is not yet complete.
Considering Arrays, it's completely new for my, and looks like a bit of magic to me.
Could you give me a example on how to use this. How would it look if; for example Button1 is pushed...and relay 1, 3 & 5 is HIGH and 2,4 & 6 are LOW

The simplest book on C or C++ should cover arrays in general. If your names are like relay1 you could as well use relayPins[0] instead, to deal with them individually.
BTW: your question was about "smart coding" :)

Arduino Uno has 3 ports.
You can read and write the ports as 1 byte.
With all the switches on one port, you can read them all at once.
For example, using D7 to D3 to read the switches:
switches = (PIND & 0b11111000) >>3; // read D7 to D0, mask off D2-1-0, move data to lower 5 bits

Then you could have case (switches): for the 0 to 31 cases that are possible.
With all the relays on one port, you can change them all at once.
For example, using D14 to D19 for the relays:
PORTC = 0b00110011; // Dxx, Dxx, D19,18,17,16,15,14 or A5,A4,A3,A2,A1,A0

to turn on relays 1,2,5,6, and 3,4 off.
The LED would still be on its own.


text:
From Arduino and breadboard to PCB
After building a working prototype with a breadboard, I was wondering what's next.
So I read about integrating the arduino into a PCB layout.
But in my case, it's worth it?
My project will use a Arduino Mega, futhermore some wired piezo switches therefore I need pcb connectors, and a small amount of resistor and transistors.
I am considering to buy a Mega of the shelf and use the contactpins on a header to fix it on my PCB. Also probably fix it with some screws.
It will save me a lot of pcb design time (a maybe some mistakes) and it will save me buying all diferent components. The  ATMega2560 alone is already around 10,-
I think I only need 10 or 15 pcb's, definitly no massproduction.
Your opinions...

Well, in my last job we're using own arduino mega clone with micromatch connectors (much more reliable than the original ones). But we didn't want to integrate it, it's easier to swap or test it (without that 300mm x 250mm board with relays, optotriacs, power supplies and many more.

Maybe a simple Prototyping Shield would be sufficient for you.

I agree with Majenko's proposal for a proto shield, or if you need a "flat" design beside the Mega get yourself a striped (one /two sided and in different sizes) vero board (its like a breadboard to solder)

You could even use Fritzing to design the most efficient layout for this option in regards to space/material saving or minimum solder points

Big fan of Veroboard - to add I have used VeroDes (https://heyrick.eu/software/verodes/) which is a free CAD tool for Veroboard design!


text:
How to use relay shield to control dc motor speed and direction?
I tried l298n before but its output voltage wasn't high
so I use relay shield but  it seems that the car can only go forward or stop
Can I control the speed and direction of dc motors?

Please can you expand on your question?  What do you motors need V and A?

You can change the polarity of the power going to the motor using only a single DPDT relay. You'd need a second relay to turn the motor on and off. Using a relay to control speed will wear out the relay pretty fast.

Using a mechanical relay to control the speed is not a good idea. But you can control the directions.
I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.
refer this
or you can use the devices like this which has direction control as well.

Most refer to relays when talking about mechanical devices which are either closed or open.  If you arrange several in an H-bridge configuration, you can make you car go forward, stop and reverse.  But controlling speed is not possible.

Ok thank you it seems the only choice is l298n

Yes you can, but the easiest way is by using a "motor shield".  There are more options than just L298N.
Are you sure it was the voltage that wasn't high enough, its normally the current (Amps)?
To do it with a relay you need to change the polarity of the feeds to the motor.  You could do this with 2 relays both connected all the time, but if you close the wrong one, you will short everything.  It would be better using a motor controller.

When I used l298n the output  voltage  was about 4.6V current was
about 120~130mA

the fast speed occurred when I connect 5V pin of arduino to the
positive of motor and GND pin to the negative of motor
I measured the current was about 120~130mA

But I used  the 9V battery to connect logic 5V of l298N ,the speed
didn't increase. I am sure I connected I don't know why it didn't work

Would this be better?
https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/library-reference?view=all

9V batteries can't provide a lot of power/current.

But i use 9V series 9V (18V)  it also seemed no difference to speed


text:
How do I know if bootloader flash was successful?
I just bought a raw Atmega328p microcontroller. I am attempting to flash it with the Arduino bootloader.
The process seemed relatively straightforward as I had just followed the posted tutorial (https://www.arduino.cc/en/Tutorial/ArduinoISP).
Everything seemed to go fine and I even got a message after the second attempt with a message of 'Burning Bootloader Done'. I am targeting the device as if it were an Arduino Pro Mini.
I then moved onto program the chip with an Arduino sketch via the FTDI programmer. However, the sketch upload fails. It says that it is out of sync. I verify that everything is wired up correctly, yet it still fails. I then remove power to the Atmega328p chip (just to see if I get a different error) yet I still get the out of sync error.
This has me questioning whether or not the bootloader was even flashed in the first place. So how do I know if the bootloader actually was successful? A couple things to note:

When I power on the Atmega328p, the PB6 output starts blinking immediately. I would assume that if there were a bootloader, there would be a moment of pause until the regular program starts. Should I expect to see a pause if the bootloader is on the chip?
If the bootloader is on the chip, should I even expect to see the Atemga328ps default heartbeat?
When I flash the chip with the bootloader, it says that it could take up to a minute to finish. However, it only takes 6 seconds until it states 'Bootloader Finished Burning'. This seems like it's happening too fast.

If we determine that the problem is due to something else (i.e. not the bootloader), I will begin a new discussion. However, right now I'm just curious how I know if the bootloader is actually on the device.

The LED blinks while the bootloader is running. That is the only "heartbeat" there is. If it blinks forever then there is no sketch installed.

See my page about burning bootloaders.
The sketch there has a "verify" option so you can check if the bootloader was burned.
See my post What happens when code is uploaded using the bootloader?.
With Optiboot installed you expect to see three flashes:

As for your other problems, see Have I bricked my Arduino Uno? Problems with uploading to board.
You may well not have set the fuses correctly.


text:
Do ISRs have to be defined in top level Arduino program?
I'm currently attempting to implement some interrupts on an Arduino project. Looking through some of the examples, it appears that all the ISRs are defined in the top level Arduino program. I'm organizing my project by C++ classes and namespaces, so I'm curious, is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++  namespace? This question has been spawned primarily for organizational purposes.
Otherwise, I could always just use a #include to import a file that defines the ISR such that they're imported to the top level.
Thanks!

Are you talking about a real ISR, or a function that you use with attachInterrupt()?

@EdgarBonet A function that I use with attachInterrupt().

Then it should be declared (not necessarily defined) from where you use it, or in an included .h.

Why don't you try it and see?

is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++ namespace?

Yes. Example here:
const byte LED = 13;
const byte BUTTON = 2;

namespace foo
  {
  // Interrupt Service Routine (ISR)
  void switchPressed ()
    {
    if (digitalRead (BUTTON) == HIGH)
      digitalWrite (LED, HIGH);
    else
      digitalWrite (LED, LOW);
    }  // end of switchPressed
  }  // end of namespace foo

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  digitalWrite (BUTTON, HIGH);  // internal pull-up resistor
  attachInterrupt (0, foo::switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

I put the ISR in the namespace "foo" and it compiled OK.


text:
SD.begin() causes SD card to pull 20mA in idle mode. Seem high?
I'm working on a project that uses an Atmega328p as the primary controller. I am using the Arduino libraries for programming.
I currently have an SD card in the project. I've done quite a bit of studying on current consumption of SD card and it turns out they're quite power hungry during read/write operations. However, when an SD card is not being interacted with, I believe it should go into an idle mode in which the power consumption is much less.
Now I've noticed that when I start using the Arduino SD library, specifically SD.begin(), the current consumed is approximately 20mA. This is a continuous 20mA without any read/write operations being used. Simply selecting SD.begin().
So I've got a few questions:
- Does this seem high for an SD card that is essentially doing nothing?
- What exactly does SD.begin do? I assume it configures some pins but does it do anything else? If it's just set up, shouldn't it 'set up' and be done? Why the continuous high current?

Current consumption depends entirely on the card used. Some (e.g., sandisk) will enter a sleep mode automatically. Some need to be placed into sleep mode. The SD library isn't clever enough to do that sort of thing.

So I'm really try to narrow down this high current draw between two things: the SD card or bad wiring/configuration of the Atmega328p. Given the fact that high current is only drawn after SD.begin() is called seems fishy to me. If were truly the SD card being power hungry in idle state, shouldn't it be pulling high current even without an SD.begin() call?

Not if the card starts in a low power state. SD.begin() would configure it ready for use.  Personally I always have a P-channel FET arrangement controlling the power to the SD card so I can turn it on and off at will.

It doesn't just set up some pins. It initializes the SD card with a series of command/response transactions where it determines stuff like the card supply voltage, block size, etc. Then, assuming there's a FAT file system, it must read the boot record and get stuff like the location of the root directory, sector size, etc. Only after this, and the method returns true, is it then ready to serve up files. That said, it should go  to sleep when idle, i.e. no reads/writes. I doubt the SD library does any stuff in the background, so is the current draw consistent even after begin() returns?

@TisteAndii Correct. I've completely stripped the project down to the barebones: #include <SD.h> void setup() {SD.begin(8);} void loop() {} and the 20mA draw still persists. It seems rather odd that this is happening. I had used the adafruit SD breakout board and did not experience this issue (https://www.adafruit.com/products/254?gclid=CjwKEAjw8ZzHBRCUwrrV59XinXUSJADSTE5k_iQcTM9kAJkN-TSNhhhlH9Nq5sMnh_l0TbCozVun7xoCgyzw_wcB). I don't believe there is any fancy power down circuit in the breakout board either.

How are you powering the SD card, now that you no longer use the adafruit breakout?  SD cards don't like 5volt.

Oh, totally missed what you said about the breakout. If the same card has worked well before with the Adafruit breakout and SD library, then the cause of your problem now is most likely hardware. Like Gerben said, 5V is not good at all, for supply or signals. You need a 1.8 - 3.3V source able to supply up to 200mA. Arduino 5V supply + LM1117 regulator would be okay. Level shifting's also required between the Arduino and SD card.

You should look here and see if it helps. Basically:

Ensure that SD.begin() returns true because the card won't sleep if not properly initialized.
I don't know if it's been fixed but the SD library may still have a bug that prevents it from letting SD cards sleep. So try the SdFat library instead.
Try another SD card, from a reliable source.
Connect external pullups or use the Arduino's internal pull-ups with the MOSI, SCK and SS pins so they don't float.


text:
How do I configure the Arduino IDE to look for source code in a subdirectory within the directory that holds my sketch?
I'm writing an Arduino program that contains various .h and .cpp files. Due to organizational needs, I have configured the directory that contains my Arduino sketch (.ino) to possess a subdirectory. This subdirectory contains related source code.
An example layout of my project directory is located below:
mysketch
    mysketch.ino
    mycode.h
    mycode.cpp
    mylibs
        mylib1.h
        mylib1.cpp
        mylib2.h
        mylib2.cpp
        mylib3.h
        mylib3.cpp

With this, I'm able to successfully #include the header files. However, the compiler then complains that mylib1.cpp, mylib2.cpp, and mylib3.cpp are not defined (however they are). I'm guessing that the Arduino only looks for source files within the same directory that the sketch lives in. Thus subdirectories contains source code are ignored.
I can then modify my directory layout such that all of the 'mylib.h/.cpp's' are in the same directory and the project compiles fine.
So my question: how do I configure the Arduino IDE to reference source code within a subdirectory? Also, I would prefer that the mylibs exist within the same directory, and not within the Arduino 'library' directory. This will allow me to then easily distribute the code as a single zipped folder.

In the Arduino IDE the answer is simple: you can't.
The Arduino IDE doesn't compile within the directory your sketch is in. Instead it writes out a fresh copy of all the files directly from the tabs in the IDE into a temporary build folder (munging them as it goes if they are .INO or .PDE) and then compiles them there. Anything else within your sketch folder is completely ignored.
If you want that kind of functionality you will have to use a different IDE.
For example, UECIDE lets you have a structure like:
MySketch/
    MySketch.ino
    libraries/
        MyLib1/
            MyLib1.h
            MyLib1.cpp
        MyLib2/
            MyLib2.h
            MyLib2.cpp

The behavior of the Arduino IDE with this sort of thing has changed over time so it depends on which version of the Arduino IDE you're using. With recent versions you can put the files in a src subfolder of your sketch folder and then do:
#include "src/mylib1.h"

or:
#include "src/mylib1/mylib1.h"

depending on how you want to organize the folder structure.
When doing this you may find that Arduino libraries often use incorrect include syntax in their source code. For example in mylib1.cpp:

#include <mylib1.h>

although wrong, would still work if the library was located in one of the Arduino libraries folders but with the library located in the sketch folder this no longer works and you need to change it to:
#include "mylib1.h"