text:
Ambiguity in Software Serial
HW:
2 Arduino ProMini 16Mhz, 5V
Software serial directly connected using male jumpers on bredboard.
I have creates a software serial port for communication between two arduinos, Parent and child
as per the documentation
http://arduino.cc/en/Reference/SoftwareSerialAvailable
mySerial.available()

should return the number of bytes available in the buffer.
and
mySerial.read();

should give me the byte or return -1 (255) on error.
http://arduino.cc/en/Reference/SoftwareSerialRead
here is my code snippet where i read the values
if(child1.available() > 0){
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

the Serial outputs are for debugging,
The condition for while is true. we go inside.
Now what i receive with child1.read() is the following
ParentReceived Something from child 2
255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

all i see is 255.
what i did:
     I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another
TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.

You haven't actually asked a question.

Update the question to show the definition of recBuffer1[].  Also include what the child is sending.

Yes, add code where we see the definitions of variables. Also, try bypassing the recvBuffer and directly write the value to the serial window to see if that variable is the issue or not.

Did you call softwareSerial.begin()?

I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of SoftwareSerial.
It's important to note that only one instance can receive data at any given time. You need to call listen() on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)
See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen

The question is - are you "listening"  to the port?
Per doc SoftwareSerial will discard the data if not in"listening state".
The real question is - when not in listening state how does "available" becomes > 0 (true) AKA there is data in SoftwareSerial "buffer"?
It really looks as if there is no real data in the buffer - character count 1 and up to 254 , the buffer content is 255 == -1 which "available" will evaluate as "true".
It can be verified using code to actually get the buffer character count returned from "available" and not just test for if () validity.
if(int count = child1.available())
{
    than print count - how many characters in buffer for real
or

if(child1.available() != -1) to test for real data in buffer.

if(child1.available() > 0){ // anything != 0 will ring true
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){// anything != 0 will ring true
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

I would suggest trying this with only one Arduino using Software Serial at first. Try using the receiver board's Hardware Serial to listen, possibly using its Software Serial for the debug output. The Hardware Serial is full duplex - it can talk and listen at the same time. Software Serial is not; only xmit or recv can run at one time, and nothing else on the board runs while it does. That can make synchronizing your two boards difficult if the communication needs to be bi-directional.


text:
I want to know how to record and play radio waves?
I want to make a universal remote.I have an ir receiver and transmiter. I.I can use it to control my tv and other equipment.I want to also control my dish network in the US. I checked and think that the dish uses 395mhz but i am not sure.How can i replicate a dish remote radio signal.I know it is radio signal and not ir. What part do I need for the arduino?

This is only a partial answer, but should be enough to get you started.
The parts are:

Build a receiver http://www.somerset.net/arm/fm_only_lowtech.html
Tune it to the right frequency
Use it to detect the codes sent from your remote
Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
Tune it to the right frequency
Transmit the codes
Success!

Step 3 is probably best done with a scope - you should find someone who has one, who can operate it, because they can be damaged.

source: Stack Exchange

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

sort: votes


text:
Difference between void setup() and void setup(void)
As it says in the title. I have been searching but I cant seem to find the answer.
What is the difference between void setup() and void setup(void) as well as void loop() and void loop(void)?

Absolutely nothing, in modern versions of C and C++. Specifying no arguments is the same as specifying void.
In old versions of C a function with no arguments took a single implicit int argument or allowed you to specify the arguments on a separate line, but no one uses anything like that nowadays.

Thanks. This is for the case of the Arduino. But what about other boards like say the Sparkcore? No difference as well?

It depends on the compiler, not the platform. But most are like this.

Up to C99, an empty parentheses meant any number of arguments (not just one int). Though obsolete in C99, it is still supported.

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


text:
how to block Arduino code until a certain event?
i am tring to enter a series of numbers using "keypad" to different variables..when simulate the code on proteus it only took the first "getkey()" function and ignored the rest ..
SO,
How can i block an arduino code until a key is pressed by keypad, in other words prevent the rest of code from being executed before a key is pressed

Please post your code here. We don't have crystal balls here :)

And a wiring diagram or schematic, since this is hardware-based as well.

It depends on how the "keypad" is implemented. If you've got it hooked up to a hardware interrupt, then you only need to add an interrupt handler for that event.
On the other hand, the more "straight-forward" implementation is that you have to poll the pins to see if a key was pressed.  Simply do that in a loop until you see a key press, call your event-handler method, and then continue to loop.

thanks a lot, I used waitForKey() function from keypad library and it worked correctly :)


text:
How to avoid the code interrupting itself?
I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.
I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?
Here's my code:
#define in1 12

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
}

void loop(){
 float rotationValue = analogRead(A1);            //read raw input from potentiometer
 float percentValue = rotationValue / 10.23;      //convert to percent 0-100
 Serial.println(percentValue);                    //print it to screen
 if(percentValue >= 0.0 && percentValue <= 1.0){
  digitalWrite(in1, LOW);                         //injector 1 off
 }
 else if(percentValue > 1.0 && percentValue <= 25.00){    //cycle at 100 millisec.
  digitalWrite(in1, HIGH);
  delay(100);
  digitalWrite(in1, LOW);
  delay(100);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){    //cycle at 50 millis.
  digitalWrite(in1, HIGH);
  delay(50);
  digitalWrite(in1, LOW);
  delay(50);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){      //cycle at 25 millis.
  digitalWrite(in1, HIGH);
  delay(25);
  digitalWrite(in1, LOW);
  delay(25);
 }
 else{              //cycle at 10 millis.
  digitalWrite(in1, HIGH);
  delay(10);
  digitalWrite(in1, LOW);
  delay(10);
 }
}

Dump analogRead() and move to interrupt-based ADC operation.

What is that? Could you give me an example?

You can't use threads on an arduino, they don't exist. you can get some pseudo multitasking going with interrupts, but that is not necessary in your case.
You should be able to refactor your code to avoid using delays without much work. The arduino library provides millis() to keep tract of the time since the arduino was powered on in milliseconds.
something like this could replace all the delays in your code
static boolean state;
static uint32_t time;
if(time < millis()){
    time += delayFromPercent(percentValue);

    state = !state;
    if(percentage < 1.0) state = false;
    digitalWrite(in1, state);
}

Then, somewhere else place
uint32_t delayFromPercent(float percent){
    if(percent < 25) return 100;
    if(percent < 50) return 50;
    if(percent < 75) return 25;
    return 10;
}

alternately, if you don't really want the discrete steps, you could use this instead
uint32_t delayFromPercent(float percent){
    return max(10, 100-percent); // don't return less than 10ms
}

you could change it to react a bit quicker by comparing the time plus calculated delay now rather than when it last set the pin, but that strays farther from what your initial implementation would have done.
In any case, this code will should be able to switch pin in1 without making the rest of your code slow down, as long as the other code does not use delays either.


text:
Arduino board to control microwave oven?
So I've taken apart an old microwave oven with a touch-sensitive LCD screen. I understand that I could die from playing around with this, so I've disconnected the high-voltage transformer and the magnetron. I'm also not going to remove any of the safety switches like the door switch. My question is, how is the microwave controlled? I'm thinking there is a computer chip somewhere in the circuit, and I'm looking to replace it with an Arduino board plus some extras, like AC relays and such. I'm curious as to how the microwave oven controls its functions, like power level, cooking time, and the beeping. Any advise as to how I could get started interfacing?
Is the power level controlled by PWM by any chance? Can you PWM alternating current?

It's pretty much all proprietary. It can be done, but you'd have to replace all the circuitry with the Arduino, interfacing with the existing magnetic and mechanical devices and doing everything in your own code.
Power level is controlled by PWM, but it's extremely low frequency PWM, on the order of 0.05Hz (20s period). That's why there are two different sounds that come from the microwave when it's not at full power; one when the magnetron is active, and one when it is off.

There is no power level in a microwave. It's just on or off. They lower the power by turning on the magnetron for a few seconds, and then off for a few second. You can actually hear this.
It's probably turned on by a relay, triac, or solid state relay. The magnetron is just requires a high voltage to work; nothing else.
The programmes, timing, and handling of the buttons is done by some microcontroller, similar to an arduino.

So the magnetron is just set at it's own "power level?" There's no variation of the output, it's just how long it is turned on? And I'm guessing if I set the power level on the LCD to full power, the magnetron would be on 100% of the time?

@user3211857: Correct.

Hmm, so if I wanted to control the operation with an Arduino, could I hook the Arduino up to an AC relay module, hook that up to the switch that turns on the magnetron, and program the Arduino when to digitalWrite(pin, HIGH)? Any ideas?

You wouldn't use a relay for pwm. Most relays can't switch fast enough .

You wouldn't use a relay for subsecond PWM. A microwave doesn't use subsecond PWM for its magnetron.

Just keep the door switches in series with the power going into the transformer. That way, the magnetron is disabled when the door is opened. Also use a relay that is rated for the amount of amps going through it. Note that there is also a motor, and probably a fan in parallel to this transformer, so the plate is spinning, and the fan is cooling the magnetron. Also keep the snubber circuit on the incoming AC line. Other than that, you got the basic idea of how to operate it correct.

Just hopping in here to point out that lots of newer microwaves do have multiple power levels for the magnetron. For older microwaves and some newer ones, the "on or off only" is still true, though. If the microwave in question is one of the new multiple power ones, there is no problem programming it as just on or off like an old fashioned one. And it's a lot safer than measuring and controlling the variable power settings.

If you want to learn more about AC power circuits start with relays (start with 5v or 12v dc as a lot safer , cheaper and easier) something like the spark fun power tail if you really do want to control 120V devices note its only on/off control, not different power levels. https://www.sparkfun.com/products/10747
You can generate AC from DC by using pwm at a lower voltage and driving a transformer
or a digital inverter. Can use an arduino to do it if you wanted to.
Use pwm function, then via optocouplers (to protect the arduino) to power mosfets or an h-bridge to drive a transformer. Can fairly easily produce 120V/240V output
Time to grab a good basic electronics book like Art of Electronics (should be able to find a pdf version)
3rd edition is finally getting published in 2015

Thanks for the tips. I've already messed around with AC voltage (luckily I'm still alive). I just used a relay module and hooked it up to my Arduino and the Wall outlet to control Christmas lights. But I haven't tried what you describe, generate AC to DC. Sounds pretty interesting.

other way around generate AC from DC. Thats how the static inverters for cars ,boats and aircraft can generate 120V/240V AC from 12 or 24V dc. First step is to get the arduino to output a sine wave (or close to a sine wave ). Learn more about pwm (also good for led brightness control)

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


text:
4 channel relay module reversed? Or is it my code?
So I am designing a simple project where my Arduino reads analog values from a potentiometer, or rotation sensor, as it is called on EBay, and uses that value to determine how many relays to close. I am connecting 4 digital pins to the relay module, and powering it with a constant digital signal from pin 2.
Here is my code:
//set up the pins for activating each relay on the module
#define in1 13
#define in2 11
#define in3 10
#define in4 9
#define power 2      //set up the power pin for the module

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
 pinMode(in2, OUTPUT);
 pinMode(in3, OUTPUT);
 pinMode(in4, OUTPUT);
 pinMode(power, OUTPUT);
 digitalWrite(power, HIGH);        //for power to the relay module
}

void loop(){
 float rotationValue = analogRead(A0);          //read raw value from potentiometer
 float percentValue = rotationValue / 10.23;       //convert the value to 0%-100%
 Serial.println(percentValue);                  //print it out on screen
 if(percentValue >= 0.00 && percentValue <= 1.00){         //all relays off
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 1.00 && percentValue <= 25.00){        //relay #1 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){           //relay #1, #2 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){     //relay #1, #2, #3 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 75.00){             //all relays on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, HIGH);
 }
}

Ok, here's the problematic part. After I upload the program onto the board, when I set the potentiometer to the 0 position, all relays are on. And when I twist it to the 100 position, which is maximum, all relays are off. Although it is usable, what's weird is that when I start from 100 and twist it back toward 0, the relays will activate, but in the opposite order. So relay #4 will activate, then #3, then #2, and then #1, and all four are on when I reach 0. Is it something wrong with my code? I've checked and rechecked, and even checked with a different project where I connect the pins to LED's. And they work normally. But when I connect up the relay module, it's reversed. Any ideas?
Here is the relay module: http://www.miniinthebox.com/4-channel-relay-module-with-optocoupler-5v_p903429.html?currency=USD&litb_from=paid_adwords_shopping&gclid=Cj0KEQiAts-kBRCbgrXc1rnXw7MBEiQAnFqTdph_qI5n7rrpW7gZaxafVVkeWitQlN8FUSUJzdsV2JwaAlBA8P8HAQ
And here is the potentiometer: http://www.ebay.com/itm/Potentiometer-Sensor-module-Rotation-Angle-Sensor-Arduino-competible-/251656942542
I mean, right now I'm even thinking that the relay module may be labeled incorrectly, that the numbers are printed the wrong way. But it could be my fault, most likely.
Thanks for any help.

All the relay boards I've come across are 'active low' i.e. as you've discovered bringing the control pin down to earth activates the relay. As an aside just be careful that the arduino has enough juice to power the relays, a separate supply is normally required if these are coil rather than ssr type relays

They are mechanical relays. By "active low," do you mean that the relays are closed when voltage is applied to their gates? Or what do you mean by "bringing the control pin down to earth?" Are you saying to ground the pin?

Oh, I did some more searching and came to this: http://electronics.stackexchange.com/questions/90777/4-channel-relay-module-set-to-low-activates-relay                                                      So when you pull the control pin to ground, the difference in voltage makes current flow through the relay to whatever you're connecting it to. Ha, I've been using them wrong the whole time.

Don't worry about, it does seem counter intuitive till you look at the circuit diagram, I've made exactly the same mistake in the past. N.B do check the point I made about the relay power supply I would expect your Arduino's voltage regulator to be getting very hot powering all those relays

So would it be better to power the relay module from something else? Like having the Arduino close a MOSFET and use a separate 5V power source going from the MOSFET to the relays?

Ok, so now I have it working. Kind of. As I turn the potentiometer passed 0, relay #1 turns on, and my DC motor spins. But as I continue to turn, although the LED's on the module board indicate, the remaining three relays aren't doing anything. The only thing I've changed in my code is replace all the digitalWrite(inX, HIGH) to LOW whenever I want to turn on the relay. But only the first one works. Is this because there isn't sufficient current from the Arduino connected to USB?

Just use a 5 volt wall wart or similar and leave them powered up, they'll only switch when the control pin is taken low, but remember to join the grounds together (Arduino and wall wart). There's unlikely to be enough power from the Arduino to operate multiple relays although I'd expect the voltage regulator to drop out and the Arduino to stop operating as well.

Finally got it working like it should. This webpage was really helpful, in case anyone else needs it: http://arduino-info.wikispaces.com/RelayIsolation


text:
Sensing concentration of methane with MQ-4 methane sensor?
I'm on a project to sense any amounts of methane in the home. I have bought the popular MQ-4 methane sensor from SparkFun: https://www.sparkfun.com/products/9404
I've looked online for any sample code, but I am confused as to whether the input from the sensor is already given in parts per million, or it is just a voltage. To be specific, here is the sample code the data sheet for the sensor gives:
int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println(sensorValue, DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

I have also used a breakout board for these sensors: https://www.pololu.com/product/1479
The sensor is soldered on it, along with a 20K ohm load resistor, like how the spec. sheet specifies.
However, I am confused on the readings I am getting. It's always something that ranges between 259 and 261. Is this ppm of methane in my home? If it is, shouldn't the normal level be 0? I currently have no methane based heating. Or is the 259 - 261 voltage?
Thanks for any help.

The values you're reading relate to the voltage measured by the AD converter, that is, the voltage over the load resistor. Arduino's AD converters have 10 bit resolution and measure against a 5V reference, so you can use the following line to convert it to millivolts:
VRL = map(sensorValue, 0, 1023, 0, 5000);
Once you have the voltage, you can compute the resistance of the sensor using the formula
Rs=(Vc/VRL-1)×RL
with Vc the circuit voltage (5V), VRL the voltage over the load resistor, and RL the resistance of the load resistor in Ohms.
The tricky part is to convert this to a concentration in ppm CH4. The curve in the datasheet gives you a starting point, but the values it gives are not absolute, but relative to the reference of 1000 ppm. The value of that reference depends on various factors, like temperature, humidity, other gases in the environment and how long the sensor has been running (the longer, the more reliable are the results).
If you really need exact ppm values, you'll need to calibrate your setup in an environment where you can exactly control the CH4 concentration. You'll also have to measure temperature and humidity along with the sensor readings.
Otherwise you'll get only a qualitative estimate of CH4 concentration, which is actually sufficient for many use cases.

Actually, you are getting raw data from the sensor. A little bit of math should be done in order to calibrate it and based on the chart in datasheet, measure the real value in PPM.
The calibration basically helps you find R0, which is an internal resistance (along with RS form a voltage divider) that could be derived by doing calibration in a clean environment. After that, you use R0 to calculate a ratio and then look at the datasheet's chart to measure whatever gas you want since there is a curve describing it.
Please refer to this tutorial for more information. I have developed a similar application using MQ-4 before.
It is related to MQ-2, you may have noticed that all theses sensors have similar features and principle applications.


text:
Cannot print the first number of the date with RTC module
I am using this real-time-clock module to keep track of the time for a project:
http://www.dfrobot.com/wiki/index.php/Real_Time_Clock_Module_(DS1307)V1.1(SKU:DFR0151)
I have hooked up the respective pins correctly to the Arduino.
Below is the code I'm using. This first one is the code used to set the time on the module. It writes the initial time you specify to the RTC module.
#include "Wire.h"
#define DS1307_ADDRESS 0x68
byte zero = 0x00;         //workaround for issue #527

void setup(){
  Wire.begin();
  Serial.begin(9600);
  setDateTime();         //MUST CONFIGURE IN FUNCTION
}

void loop(){
  printDate();
  delay(1000);
}

void setDateTime(){          //Set the time to a minute or two ahead. After upload has completed, simply press the reset button to start the time while watching another clock.
  byte second = 0;     //0-59
  byte minute = 56;     //0-59
  byte hour = 13;     //0-23
  byte monthDay = 26;     //1-31
  byte month = 5;     //1-12
  byte year = 15;     //0-99
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(zero);     //stop Oscillator
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(monthDay));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.write(zero);       //start
  Wire.endTransmission();
}

byte decToBcd(byte val){
return ((val/10*16)+(val%10));        //Convert normal decimal numbers to binary coded decimal
}

byte bcdToDec(byte val)  {
  return ((val/16*10)+(val%16));        //Convert binary coded decimal to normal decimal numbers
}

void printDate(){
  Wire.beginTransmission(DS1307_ADDRESS);        // Reset the register pointer
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  Serial.print(month);        //print the date, EG: 3/1/11 23:59:59
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

//http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

And this next block reads the time from the RTC module. It has an onboard battery, so it keeps time even when disconnected from the Arduino.
#include "Wire.h"
#define DS1307_ADDRESS 0x68

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

void loop(){
  printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10)+(val%16));          //Convert binary coded decimal to normal decimal numbers
}

void printDate(){
  Wire.beginTransmission(DS1307_ADDRESS);          // Reset the register pointer
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  Serial.print(month);          //print the date, EG: 3/1/11 23:59:59
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print("20");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

//http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

The weird thing is, when I open the serial monitor after I upload the getTime sketch (the second one), every thing works except that the dayOfMonth only shows the last digit. For example, if the day was the 23rd, it would only print 3. Or if it was 31, it prints 1. I've gone through the code, but can't find anything that I think would cause this. Any tips?
To get started, I followed this tutorial: http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

You forgot
int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday

just before reading monthDay. Even though you may not be interested in
this piece of data, the RTC chip has no way of knowing that, and it will
always send the date and time in the same format. You can replace that
line by
Wire.read(); // discard day of week

if you want to make clear that you are discarding this information.
Ah, BTW, decToBcd() and bcdToDec() are ill-named: they convert
between BCD and binary, not decimal.


text:
How do I use the prototyping area on a SparkFun MicroSD Card shield?
I'm having trouble figuring this out. I'm using this popular shield: https://www.sparkfun.com/products/12761
There is a breadboard area in the middle of the shield. But what confuses me is the lack of lines (order). On normal breadboards you can tell which row would be at the same voltage. If I wanted to put something on this prototyping area, how would I connect it? For example an LED, which would have a resistor attached to the positive side going to 5V and the negative side going to ground?

By soldering it.

This type of board, "pad per hole", has no pre-made interconnects. If you use thin enough wire sometimes you can push two pieces of wire into the same hole before you solder, say a resistor lead and another wire to connect to the next component. You can also solder an interconnect wire to the protruding leg of a DIP chip. You can make a buss for ground or 5v by assigning a whole row for that purpose, on the top side wire everything that needs to connect to that buss, and on the bottom side solder a straight piece of bare wire to all those wire ends in that row.


text:
How to find the difference between two timestamps
I'm using this time library to access the properties of unix timestamps like hours / minutes / etc. What I want to do is get the current time, and an estimated arrival time, and find the difference between them in minutes.
Here's my code: (My estimated time is coming from an API as an INT)
time_t timeEstimated = timeInt;
time_t timeNow = now();

But how do I find the difference between these two timestamps in minutes? I'd like to try and avoid all of the conditionals / math that would come with converting to hours / minutes / seconds / dates and subtracting each component if possible.

Unix timestamps are just a count of seconds since a standard
origin (1970.0 UTC), thus a simple subtraction, followed by a
conversion from seconds to minutes:
float minutes_remaining = (timeEstimated - timeNow) / 60.0;

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


text:
Determining contrast on LCD
So I am using this code here and I do get text written on my LCD screen. Problem is that text is almost invisible. I tried with background light on or off and it did not help. LCD is connected to 5v and backlight is connected to 3.3V. Backlight is connected through potentiometer.
How to control text contrast? To have more contrast?
#define PIN_SCE   7
#define PIN_RESET 6
#define PIN_DC    5
#define PIN_SDIN  4
#define PIN_SCLK  3

#define LCD_C     LOW
#define LCD_D     HIGH

#define LCD_X     84
#define LCD_Y     48

static const byte ASCII[][5] =
{
 {0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};

void LcdCharacter(char character)
{
  LcdWrite(LCD_D, 0x00);
  for (int index = 0; index < 5; index++)
  {
    LcdWrite(LCD_D, ASCII[character - 0x20][index]);
  }
  LcdWrite(LCD_D, 0x00);
}

void LcdClear(void)
{
  for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
  {
    LcdWrite(LCD_D, 0x00);
  }
}

void LcdInitialise(void)
{
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_SDIN, OUTPUT);
  pinMode(PIN_SCLK, OUTPUT);
  digitalWrite(PIN_RESET, LOW);
  digitalWrite(PIN_RESET, HIGH);
  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.
}

void LcdString(char *characters)
{
  while (*characters)
  {
    LcdCharacter(*characters++);
  }
}

void LcdWrite(byte dc, byte data)
{
  digitalWrite(PIN_DC, dc);
  digitalWrite(PIN_SCE, LOW);
  shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
  digitalWrite(PIN_SCE, HIGH);
}

void setup(void)
{
  LcdInitialise();
  LcdClear();
  LcdString("Hello World!");
}

void loop(void)
{
}

Welcome to Arduino SE. It would be helpful if you tell us the part number of the LCD screen, and also where you got the code for controlling it.

I second that. But be aware that some LCD boards, have a little plastic potentiometer on the back. If you turn the it, you can adjust the contrast.

First, thank you on greeting. I bought part here http://ebay.to/1ztRhd5 and (I did not know that fact) I checked and could not find any potentiometer on LCD screen. I am new to electronics, I did manage to do some things with LED diods, sound even some small theremin project, but LCD screen I just do not understand still. Code comes from this site http://playground.arduino.cc/Code/PCD8544

Have you even read your own code? Notably line 141; LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast)..
Try sending a different value. Note that the first bit should always be 1 so the value should be between 0x80 and 0xFF

Thank you. As I said I am new to electronics, and still figuring out this code. I did see this but did not know what to do with it. Can you help me with some thread or help where I can find out how to calculate these hex values?

You'll need a higher value I think. Just try a few different values. You can't calculate them, as the differ from display to display (and change due to temperature). In case you're not familiar with hex notation (0xB1), instead you can use a decimal number from 128 to 255. So e.g. LcdWrite(LCD_C, 190)

Actually if I am not mistaken that is contrast for background right? That will not make my letters more visible right?

No and no. here is a video showing different contrast values. It seems like you haven't even tried, so I'm out.

Same problem, I solved it following this:

The contrast can be adjusted by the potential-meter displayed in the following picture.

credit

Backlight is connected through potentiometer.
You should try to turn the potentiometer.
If that doesn't work, there might be something wrong with the connection from the potentiometer to the Backlight.

Check out this video: https://www.youtube.com/watch?v=XR8ede6V6eA&t=65
Where the led would be replaced with the BL (black-light) pin.

Backlight has nothing to do with contrast.

I assume you are using a 16 pin 16x2 display.  Try wiring a potentiometer like this with the pot wiper on pin 3. This is what adjusts text contrast:

By looking at the code OP is not using a character LCD


text:
Read all Digital input in arduino once time and sent theme to serial
i need to read all Read all Digital input in arduino once time; example:
Serial.write(digitalRead(0),digitalRead(1),...,digitalRead(13));

to receive state of all digital pin in one times from my app build with delphi

So what's your question?

Serial.write(digitalRead(0),digitalRead(1),...,digitalRead(13)); not working , i need to get function like that

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

void loop()
{
  Serial.print("<");
  for (int p = 0; p < 14; p++)
  {
    Serial.print(digitalRead(p));
  }
  Serial.println(">");
}

According to the pin mapping, D0-D13 and A0-A5 are mapped to ports B, C, and D. So simply read the raw ports as bytes, send the values, and decode them on the other side.
Serial.write(PINB);
Serial.write(PINC);
Serial.write(PIND);

Note that A6 and A7 (on boards that have them) are not mapped to digital pins and so cannot be read in this way.

iam tring this command but not working for me , any one can help me with example or demo ?


text:
IDE support for Arduino micro
I have an Arduino micro http://arduino.cc/en/Main/arduinoBoardMicro I was looking to know which is the lowest version of the IDE that support it. Actually on the IDE 0023 is not present in Tools > Board.

Why are you still using 0023?

Find some very old .pde that works and is compatible with 002x

I don't think you're gonna get an answer here, as it's generally accepted to use the latest version, and we're gonna need to know why you don't want to do that.

According to the Arduino Software Release Notes, support for the Arduino Micro was added in 1.0.2.


text:
Servo motor swinging back to 0°
I just got my arduino and servo. But my servo may be acting strangely.
Whenever I tell the servo to go somewhere it keeps going to 0 than to that position and stops after 10-15 seconds or more.
This is the code used in this video
#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);
      myservo.write(50);
    }

    void loop()
    {
    }

https://www.youtube.com/watch?v=rsikknT7z6g
It is connected like this:
Ground from Arduino to breadboard row 3
Ground from external power supply to breadboard row 3
Ground from SERVO to breadboard row 3
Power supply positive to servo VCC
Servo signal to pin 11

how is this being powered?

Try with something like:
#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);

    }

    void loop()
    {
        delay(2000);
        myservo.write(50);
        while(1);
    }

and let us know.
But more important: disconnect the servo +5V wire from Arduino and use another power supplier!!!


text:
too few arguments to function 'void setColor(int, int, int)'
When I put "c" inside setColor(c);
it tells me:
error: too few arguments to function 'void setColor(int, int, int)'.

I understand that I should put 3 arguments. What I don't understand is that the serial is correctly displaying the 3 arguments (255, 000, 000) so why it keeps telling me this error. What am I doing wrong ?
int rPin = 11;
int gPin = 9;
int bPin = 10;

void setup() {
    Serial.begin(9600);
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
}

void loop() {
    if (Serial.available() > 0) {
            delay(100);
            while (Serial.available() > 0) {
                char c = Serial.read(); // serial will display an rgb code, for exemple: 255, 000, 000 (red color)
                setColor(c);
            }
        }
}

void setColor(int red, int green, int blue) {
    analogWrite(rPin, red);
    analogWrite(gPin, green);
    analogWrite(bPin, blue);
}

You understand that c can only contain a single character, right?

c is what the serial is displaying, in this case an rgb code like 255, 000, 000 am I wrong ?

In the context of C/C++, the type char refers to a primitive type that can contain exactly one byte of information, or 8 bits if you like.

the serial is correctly displaying the 3 arguments (255, 000, 000)

In your question, you do not specify how you verify that this is indeed the information that returns from Serial.read. Serial.read returns one byte, which can be cast or parsed to an Integer but cannot be interpreted as the triplet (255,000,000) in no way. If you keep calling it repeatedly, however, as long as there is data (meaning that the result is greater than -1 or Serial.available returns a number greater than 0) - you can accumulate the characters to a meaningful string, which you can later split to three different int values. For example:
String incomingData = "";

void loop()
{
    if (Serial.available() > 0) {
         delay(100);
         while (Serial.available() > 0) {
             char c = Serial.read();
             incomingData.concat(c);
         }

         // now, the string incomingData will contain "255,000,000" which you can split into 3 different integers and send to setColor.
         // so, assuming the format "ddd,ddd,ddd":

         int color1 = incomingData.substring(0,3).toInt();
         int color2 = incomingData.substring(4,7).toInt();
         int color3 = incomingData.substring(8).toInt();
         setColor(color1, color2, color3);
    }
}

This result in error error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'

please see my edit.

now it tells me error: 'setColor' was not declared in this scope by the way I forgot to mention that I am totally beginner at C++ and i'm very grateful for your help. I'm actually studying you piece of code. Thank you

You're welcome. The code above is not complete; do not forget to include the 'setColor' function which I omitted.

Ok It works but I need to make some tweaking, I need to make some adjustments, including the fact that I can not change the color without reloading the script. Thank you Omer.


text:
How to move from arduino to physical prototype
I've been reading a bit about moving from Arduino to PCB and it seems a bit daunting. For now, all I really want to do is take something I've built, and make a few changes so that I can actually create a casing for it and make sure everything stays connected.
I've attached a photo of my project. What I am trying to do is create a box, where 4 pushbuttons sit in a box, with LEDs next to them. I will probably create foamboard cutouts for the spaces where the pushbuttons and leds sit. The wiring for the push buttons and the LEDs need to be hidden below the foam board, along with the arduino itself and the servo motor - which is where I get stuck.
What do I need to do to essentially "lengthen" the wires for the pushbuttons and LEDs, and make sure all the components stay secure in the breadboard (the push buttons in particular like to pop out)? Is there a way to do this without making a PCB? I understand the concept of soldering components into protoboard, but as far as cutting / printing the circuits or whatever, it is really confusing to me.
I'd appreciate any guidance. If you see anything wrong with my wiring setup too, I'd love a learning experience on that as well. Thanks!

How did you draw the bottom diagram?

The best thing to do is, of course, to use a PCB. But it doesn't need to be a custom PCB; there are plenty of pre-made PCBs that are usable for approximately 98% of designs. Here are just a few:

Adafruit Perma-Proto boards are connected just like breadboards, so direct transfer is possible.
BusBoard proto boards come in a ridiculous variety of configurations, including enclosure kits, and they even have SMD boards if you're up to it.

For switches just use a panel mount form. They come in everything from simple to robust to ridiculous.
LEDs can also be panel mount, or you can use a light pipe to make a LED on the PCB visible from the outside.
For power you can use a USB connection or a separate power jack with a voltage regulator. If you also need a serial connection then you should consider a pre-made serial module, and either use its built-in USB jack or a separate panel mount USB jack.
The servo can be mounted inside the case if appropriate, or can be connected to a PCB mount or panel mount connector instead.
Naturally the MCU itself should also be placed in a socket directly on the PCB. Don't forget the decoupling, the oscillator, and the ISP connector.
As for the circuit itself, you can get rid of the pullup resistors on the switches if you use internal pullups instead. And 100ohm is way too low a value for switch pullups regardless.

Thanks - this was super helpful! For the resistors - I'm using 1000 ohms - is that still too low? What do you recommend? As far as sort of extending all the wires and push buttons, would it be reasonable just to solder some wire to headers which I plug directly in to the arduino?

I'm fairly sure the third band is brown, but they're in front of you so you'd know better. But as I said, use the internal pullup. I strongly recommend not using the Arduino and instead using the bare AVR, but soldering or crimping pins onto a wire should work, at reduced reliability (excessive G-forces will pull them loose).

Thanks! If anyone stumbles across this - there's a good description of how to use internal pullups (and understand pullups) here: https://learn.sparkfun.com/tutorials/pull-up-resistors

Learning to design a PCB can be a challenge. First, there's software choices, there's file formats, and then actually laying out a good board. That's before production and assembly, each with its own struggles along the way. It's no different than the first time you open Xcode and learn about Storyboards and Frameworks and Simulators and all that, or for that matter, learning any new skill, which at first is a daunting experience but through both setbacks and success eventually becomes easy.
So, I agree with everyone that suggests perfboards and variants. But I also want to show, as perhaps motivation, where you could be in a few months. I tend to see Arduinos as the development tool, not the final product, but I understand others are content to just use a standalone Nano or Pro Mini and forever dedicate it to their project.
These are three variants of the same device, it combines an Arduino/ATMega, a GPS, a serial port, and an RGB LCD. I first created it in on a breadboard, then moved to a perfboard, thought "that is ugly" and made a simple PCB. Pleased with that experience, I kept refining the schematic and layout until I finally called the project "done."

You also might consider making tiny PCBs just for specific components, like these two boards I make for buttons and lights.

The very first PCB I ordered from OSHPark was an amazing experience, opening the envelope and holding it like some religious relic. But since then it's become routine. If you do later go the PCB route, you might appreciate my summary of low-volume shops I've ordered from.

Using a stripboard is perfectly convenient to create a circuit that:

will last longer than a breadboard prototype
will cost less than wasting a breadboard for a long time

Stripboards can be found in any good electronics retailer (I buy mines at Conrad).
You will need a soldering iron (and the skills that are needed for it, but that is not so difficult as some people think).
You could even go one step further and create an Arduino on the same stripboard (many components from the UNO are not required for a circuit you want to build and keep "forever").
Another option, just a little bit more expensive, would consist in affording a prototype shield for Arduino, solder you circuit onto it and directly plug it onto your Arduino. The principles are the same as for a stripboard, except the prototype are has typically no strip, only holes on which you can solder components and wires.

You can use Arduino proto shield. It's a prototyping board shaped the way it can be plugged into the Arduino. There are over 9000 of them from different manufacturers. Then just solder the stuff you need on the proto shield.


text:
estimating battery run time
I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.
Below is my code and attached is the wiring diagram for the project (minus the batteries).
    #include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

First don't use 9V batteries to power motors, they don't contain enough energy to last long. Then, consider using ATmega328 sleep modes (you can wake it on an input pin value, eg your button). Finally, consider ditching the UNO altogether and replace it with a minimal circuit (Arduino boards are not optimized for low consumption, but they are good forprototyping).

I agree. 9V batteries also don't have enough discharge capacity for driving things that need more than a few 100 mA. You can use high capacity AAs for that (NiMH cells for example - but beware of their high self-discharge rates, that may offset any economy you gain by configuring the MCU into low power mode). Also, the voltage regulator on the Uno will consume all of your battery, no matter how you configure the '328 for low power consumption. See this great answer by Anindo Ghosh for more details.

You would have to disengage the servo, when it's done moving. Otherwise it will continue to draw power. You also can't put the arduino in sleep mode, while the servo is attached, as it needs to be sent position data continuously. In case there is some pressure on the servo; if you connect the gnd and vcc of the servo, it will act like a break.

@jfpoilpret - I will look into the ATmega328 - as far as replacing it with a minimal circuit - I'm afraid my current circuitry knowledge is limited - I'm not even sure I would know where to get started with that. Can you explain or link me to anything that explains how to replace an arduino with a circuit?

ATmega328 is the central intelligence of Arduino UNO. UNO brings a lot of extra stuff that majes it cool for prototyping but not for definitive circuits: typically you won't need USB in the definitive circuit, you won't need voltage regulator if you provide voltage with bateries under 5V overall. For links, google is your firend :-)aybe start with "Arduino on breadboard" that will show you simple circuits to start with.

I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

As a side note, if anyone spots a way to improve battery life in my
  sketch / wiring, I'd love to know.

-Check out the ATTiny series (parametric); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.
-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.
Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.
-As others have pointed out, delay() is bad. delay() tells the MCU to do nothing (NO-OP) repeatedly, for a period of time. This is different from having nothing to do because it's asleep.

Jon - thanks - can you explain a little bit more about an interrupt or link to something where I can learn more about how to set this up?

Please visit this link from Arduino.cc; the "Using Interrupts" section says it perfectly: http://arduino.cc/en/Reference/AttachInterrupt

Additional: http://gammon.com.au/interrupts

added psuedocode-ish interrupt scenario

If you have issues with the interrupt going off multiple times when you press the button once, search for "how to debounce a button"

I can support what mheavers said in a comment above. Use a Bareduino or any kind of custom Board, use sleep-modes and avoid delay(). I wrote a blog-post about my experiences with this setup here, if you get it right the ATmel can go down below 1mA in sleep. In your case an extreme scenario (depending on your usage pattern) could be to wake-up the Arduino with an interrupt triggered through the sensor and otherwise sleep completely. You will find example on the net where people used a setup like this for remote controls for instance.


text:
attachInterrupt has no effect on Industruino SAMD21
I'm using Industruino D21G (SAMD21G version) with Visual Studio Code extension for Arduino. attachInterrupt seems to have no effect. I tried Industruino CH1, CH6 and CH7 with the same result. When I poll these channels in a loop, I detect signal level change as expected. Here is the code:
#include <Arduino.h>
#include <Indio.h>

constexpr int PROXIMITY_SENSOR_NC = 6;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Indio.digitalMode(PROXIMITY_SENSOR_NC, INPUT);
  attachInterrupt(digitalPinToInterrupt(PROXIMITY_SENSOR_NC), blink, FALLING);
  digitalWrite(LED_BUILTIN, HIGH);
}

void blink() {
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}

void loop() {
}

Any ideas what could be wrong?

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.

Industrial level I/O on Industruino, which includes CH1, CH6 and CH7 I tried, is not connected directly to the microcontroller. It uses a buffer and communicates through I2C in pull mode. That's why interrupt on I/O change has no effect.


text:
Looking for a library with basic EtherCAT master functionality
I have a P1AM-200 PLC with P1AM-ETH Arduino compatible Ethernet Shield based on the Wiznet W5500 Ethernet Controller. I'm looking for a library with basic EtherCAT master functionality, but there is nothing listed in Arduino IDE 2.3.1 Library Manager. I found Easy Master at https://www.bausano.net/en/hardware/easycat.html. Is there anything else known to work available?

You can consider SOEM instead. SOEM is a popular open-source EtherCAT master library written in C. While it is not specifically designed for Arduino, it is highly flexible and might be adapted for your hardware.


text:
Using MULTIPLE shields on Arduino Uno R3
I'm very new to using Arduino!  I'll be using Ocean Controls KTA 259 thermocouple multiplexing shield AND a Sparkfun microSD shield on my UNO--to log temperature data for a study I'm doing.  The KTA 259 has a library and the integral SD library should work for the SD shield.
Q1:  I believe they physically connect no problem, but how can I be sure there are no pin conflicts, disastrous or otherwise?  In other words--what conditions MUST I avoid using shields and multiple shields?
Q2:  Can (or must) a single data pin be used by both shields, eg from thermo as output to SD as input, or does Arduino juggle all that?
Q3:  Can (or must) a single function, eg CS, be mapped onto the same pin on BOTH shields, or do they have to be separate allowing Arduino to handle that?
Thank you; I appreciate the help!

You will have to consult a source like this one: http://shieldlist.org
There are no simple rules for which pin conflicts are OK and which ones are not, it all depends on the concrete protocol (i.e. I2C is designed for all bus participants to share lines, while in SPI, each participant needs their own select line, while the other lines are shared).
In your concrete case, both shields you want to use are addressed by SPI, which means D13 (SCK) and D12 (MISO) are shared between the shields by design, while they MUST have different slave select pins. In your case, the SS pin for the microSD shield is fixed as D8, while the one for the KTA shield seems to be selectable, so either D9 or D10 should be OK.
Peripherals generally don't have facilities to become an SPI master, so all data has to be transferred through the Arduino.

I have used these exact two shields myself and can confirm they definitely work together. I can find my datalogger code to confirm if desired.

Q1: If its a well established source of Arduino compatible boards you can be pretty confident (in my experience) that there are no design flaws regarding pin use.  A search on comments by other developers will also help confirm that for you further.
When you go to multiple shields you would need to look at fanout (driving more than one input from an output).  The reverse problem is even more of an issue: driving one input from several outputs.  In other words, an input on the Arduino would be connected to output pins on two shields providing different signals.
Q2: The answer relates to how I ended in Q1.  By avoiding the use of certain pins on a shield the conflicting inputs could be avoided.  The headers would simply pass through the signal.  I don't think there is any rule that a shield has to use or touch every pin.
Q3: I'm not quite sure what you are asking in this question.


text:
List of supported boards in Arduino IDE 2.0
Where can I find the list of supported boards in Arduino IDE 2.0 without installing the IDE? Googling it was not fruitful. Specifically, I'm looking for ESP32-S3 support.

The 2.X IDE makes use of arduino-cli:

The backend operations such as compilation and uploading are offloaded
to an arduino-cli instance running in daemon mode.

which has roughly the same internals as arduino-builder

The arduino-builder is now just a wrapper of arduino-cli

which is what the 1.X IDE uses to launch the build process. Roughly speaking, they support the same boards.
About the only difference I've noticed is that the 2.X IDE does not yet support disableRTS and disableRTS board properties, so some ESP32 board that require these settings will not (yet) work in with the 2.X IDE's serial monitor. The ESP32-CAM-MB together with ESP32CAM is one combination where the Serial Monitor won't work. You can still upload with it though.
So, the IDE should compile and upload for your ESP32-S3 just fine. If you want to know whether or not the Serial Monitor will work, it's down to looking at the specific board schematic to see whether or not the EN/RESET and GPIO0 signals are connected to the serial transceiver using only diodes. The official boards don't do this. So if you have one of the Expressif devkits (or a clone) the 2.0 IDE Serial Monitor will work fine with it.

Where can I find the list of supported boards in Arduino IDE 2.0
Specifically, I'm looking for ESP32-S3 support.

Without knowing what you want to do, the short answer is: check this JSON's "boards" properties: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json.
The Arduino IDE is just a user interface on top of the arduino-cli. It provides a way to change the board_manager#additional_urls property of the CLI configuration. Once a new 3rd party platform URL is specified in the IDE, the CLI will see the available boards of the platform. You'll need to install the platform to verify and upload your sketches. After installing the platform, the "boards.txt" will be available on your filesystem for the CLI. For this example, this is https://github.com/espressif/arduino-esp32/blob/master/boards.txt.


text:
What do these pins on the Uno do?
I've been wondering for a long time what these pins, labeled ICSP and blank, do.

I can't seem to find a diagram that explains them, so I've been wondering:

What are they for?
Are they GPIO, or do they do something special?
How can you use them?

Thanks for the help.

They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.

I'd like to add that the pins on the right header are VCC, GND, RESET, and Digital pins 11, 12, 13. So it's not like you can use them if you run out of digital pins.

There is a case where a "normal" user use the once at the back. That is when you use a shield that connects to those pins. An example of such a shield is the ethernetshield. The tag (that is what these 6 pins are called) at the end is actually added to fix a compatibility issue between the mega and uno.


text:
coding standards for bigger projects
I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.
I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide).
Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.
Any similar tools for C++ or more specifically arduino C++?

There is no such thing as "Arduino C++"; the magic is in the IDE, not the language. Also, you may want to try Programmers.SE for a style guide.

In my experience (15 years in industry, 30 total), this does not matter. What matters is having good developers who understand code written in ANY valid style. I currently work at a large bank, and there's 2 different bracket styles being used in our code, and nobody cares. Good developers don't care about this. We care a lot more about the code being valid, error-free, and efficient. If you do that, I don't care where your brackets are.
Yes, there are style guides for C++ but you don't need to use them. This is a good one though...
http://google-styleguide.googlecode.com/svn/trunk/cppguide.html
I am not aware of any style tools that integrate into Arduino IDE. There are some style tools that integrate into Eclipse though - and if this is important to you and your team, I strongly suggest using Eclipse for development. The Arduino IDE isn't really for large projects.
http://astyleclipse.sourceforge.net/ - but Eclipse doesn't really need this, it has a pretty good built-in formatter.

I don't intend to use the arduino IDE, it is pretty useless indeed beyond quickly testing some simple code. But I'm not a big fan of eclipse either, which I find clunky. The plugin you mention is built on top of http://astyle.sourceforge.net. There may be a way to use it as a validator rather than formatter.

Actually the Arduino IDE uses AStyle. In folder IDE/lib there's file formatter.conf file that you can edit if the default style doesn't suffice or fit

@Jasmine the google coding style is pretty much what I was looking for. http://google-styleguide.googlecode.com/svn/trunk/cpplint/ has the sort of tool I was looking for. Thanks for putting me on the right path!

Just as long as you remember that attempting to enforce a style will hurt you a lot more than it will help you. I hope I made that point clear. People with less experience will debate that, because they haven't witnessed the damage it can cause.


text:
Increasing payload size above 32 bytes using nRF24L01+
I tried to modify the example in the following page, by replacing the given string with a 56 bytes one after making all the suitable changes to read(), write() and max_payload_size(increased to 64 bytes), payload_size() parameters/methods in the RF24 library.
http://shanes.net/another-nrf24l01-sketch-string-sendreceive/
The problem is the receiver truncates the string to 32 characters. Is 32 bytes a hard limitation for payload with the nrf24l01+ radio? If so how to I modify the receiver in above example problem to receive the entire string?

If you look at the specification or datasheet for the nRF24l01+, you will see that the 32 byte payload is the maximum that the device can handle.
For example:

If you need to transmit anything larger than 32 bytes, you will need to develop a protocol that splits up your data into chunks of 32 bytes or less and sends the data in several packets.
The actual protocol you design is up to you, but a simple technique might be using the first packet to send a count of the number of data packets to expect and then simply send those packets, each with a part of your data and reassemble it at the receiving end.
You may need to design something more robust so you don't get confused by lost packets or bad data. The larger your payload, the more chance of transmission errors, so it might be an idea to experiemnt with the payload size to get the best throughput for your particular application.


text:
Throughput and BER test with nRF24L01+ radio and Teensy microcontroller
I am trying to modify the example given in the this page to a basic throughput and BER test with two nRF24L01+ and Teensy 3.0 modules.
I want to modify the nrf24l01_send_string example in a way that I can remove the powerUp powerDown and delay and transmit the next packet purely based on the ACK received from the receiver. The problem is RF24 class does not seem to have a method to transmit ACK (not ACK+Payload) and the datasheet does give any information on the structure of the ACK message. The example works when powerUp and powerDown are removed, but I need to modify it to measure throughput by removing the delay.

You can't send the ACK manually. The module itself sends the ACK automatically (if enabled that is), once it receives the package. This way the sending module only need to be listening for the ACK for the shortest amount of time, reducing power usage. To attach data to the ACK package you need the writeAckPayload function. But you have to prepare this before any package is received.

Thanks for the reply. The data string in the example in sent in a loop. I have to stop and listen to the ACK before resuming the loop. If I reduce the delay below 500 the arduino serial monitor hangs. Inorder to listen to the ACK using the read() function I need to know the structure of the ACK payload esp. the number of bytes in the ACK message. This information is not there in the documentation. Also, how do I find the CRC checksum after receiving the packet to calculate BER?

You can use getPayloadSize to get the size. No way to get to the CRC, as the module handles the CRC and rejects messages with incorrect CRC.

I'm sending 32 byte payload(in loop) with data rate set to 2MBPS and setRetries parameters of 0(250us) and 3(retries) respectively. The throughput I get is only 45 KBPS. The delay between consecutive 32 byte packets is 700us which works out to the above mentioned throughput. Is there any way to get closer to the set data rate of 2MBPS?

You could try filling the buffer, instead of sending 1 packet at a time to the module. Use startWrite, instead of write. I think however that then you won't be able to determine is a packet was ACKed.

Please stop asking to delete questions. The information in the comments might still be useful to someone else. Deleting the question will remove everything.


text:
Arduino RF24 library Delay after write function causes no byte availability
It's about the RF24 library you can find here. http://maniacbug.github.io/RF24/index.html
I transmit data from one Arduino to another using NRF24L01 radios.
When I use the write-function on the transmitter arduino (joystick is an array) and after that I put in a delay higher then 10, the available function returns false.
Transmitter
radio.write( joystick, sizeof(joystick) );
delay(20);

Receiver
if(!available())
  print('No data'); // delay > 10 --> No data will be printed

Why is it working with a delay of 10 but not above? Has it something to do with timeouts which is mentioned in the docs of the library?: http://maniacbug.github.io/RF24/classRF24.html#a4cd4c198a47704db20b6b5cf0731cd58
Thank you for your answers.

Don't you check repeatedly to see if data becomes available later?  Unless you use an interrupt from the radio to the processor, you will need to.

I check repeatedly in the sense of the standard loop. What I think is, that Arduino prints a huge amount of "No data" because of the delay. When delay is over, one single line is different, then again a huge amount of "No data" lines. I was scrolling the Serial Monitor, but this was not the case. Or maybe I scrolled not long enough? Would be interesting how many milliseconds a small loop needs to complete...But I think it's just better when I use: while(!radio.available()) {} so that only something happens when there is a payload. I will try this today.

Yes, it's not usually useful to repeatedly log that data is not available, thiugh if you are really curious you could count the number of loops until data is obtained and print that with the data.

Nice, that's a great idea. Yes, I'm very curious about this. I will share the result after I tried.

I consider that if statement without brackets kinda risky since it's harder to read than brackets. Apparently there's more code here; can you add that so we can see if there's another issue? I like that you tried to make it smaller, but can you please include an example with enough to compile? Thanks! (On a side note, what's this joystick variable? A class?)

Hey Penguin, thanks for your comment. joystick is an array and I copied the tutorial from here: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo      Just scroll down or search for "EXAMPLE ARDUINO SKETCHES" on the site. All I did was to hang on the delay after the radio.write in the YD_nRF24L01_Transmit_JoyStick example as you can see in my initial question. I am looking forward for your try :-)

This is a snippet, isn't it? print('No data'); would not print "No data" because you are using the wrong quotes. It is difficult to answer such questions without the actual code being posted.

I've got the same issue and placed this issue to the Github issue tracker. hope there comes an answer: https://github.com/maniacbug/RF24/issues/68

@Greccofly There will be no answer because that library has been abandoned. Please use the https://github.com/TMRh20/RF24 library. It should also be available in the builtin library manager so you don't have to worry about updating it.

In my situation the issue was with the Transmitter not continuing to transmit after a delay. I was able to resolve the issue using the powerDown (http://maniacbug.github.io/RF24/classRF24.html#aa0a51923a09ba4f3478aba9be0f8a6a1) and powerUp (http://maniacbug.github.io/RF24/classRF24.html#a5cdaf47aa0edd6dca1b9a8bb7972a1a3) functions. Here is a snipet of my code. "radioTx" is the name assigned to my transmitter.
//standard code setup for arduino uno board examples
radioTx.begin();
radioTx.setChannel(108);
radioTx.openWritingPipe(pipe);

}

void loop() {

  int dist_cm = sonar.ping_cm();

  Serial.println(dist_cm);
  radioTx.write(&dist_cm,sizeof(dist_cm));
  radioTx.powerDown();
  delay(5000);
  radioTx.powerUp();

  }

I had the same problem. My solution is:
First make .stopListening()
then .write(&data, sizeof(data))
and behind the write command an .startListening().
Now you can delay for longer times.

Welcome to Arduino SE! I'm having trouble understanding what you mean. The stopListening() command seems helpful, although can you explain how the .write(&data, sizeof(data)) would help? Thanks!

Try using
unsigned long t = millis();
while(millis() - t < DELAY);

instead of "delay(DELAY)"

Please read this: Arduino NRF24L01+ arduino to netmf transmit issue
Although you are not using NETMF, @PhilVallone uses the library and chip together successfully, points out the samples are not asynchronous, and addresses time-out. The OP for that question is using delay(1000) and no answer has been accepted.

I don't believe there is any use of interrupts or threading involved, making this mostly irrelevant.  Do you have evidence otherwise?

Answers should have some relevance to the problem - random unrelated suggestions do not.

And what bootloader bugs do you think might be relevant?  Do you realize how self contained the code in question is? This is not helpful, it's an uninformed grasping at straws.

Please take some time to actually read the code associated with the question...

With your feedback, I have backtracked and await the OP's reply.

Try updating your library to the new TMRh20 fork. That improves the old maniacbug's version a lot (possibly also fixing the bug). tmrh20.github.io/RF24
It's also worth noting that after you've read the message, it will print out "no data" until you receive new message.


text:
Doesn't Arduino reports DSR (Data Set Ready) correctly?
I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.
This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data
And computer should wait for it.
Does it happen so?

No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.
Generally host software / serial driver configuration ignores DSR.
On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.
None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.

No, this doesn't happen.
DTR is used purely for resetting the board.  Personally I would have chosen the RTS signal instead, but the wise guys at Arduino decided on DTR.
The Arduino has no knowledge of the DTR signal, it only knows that it has been rebooted.  Whether that reboot came from DTR, or from the reset button, or wherever, it has no knowledge.
So the DTR is being (in my opinion ab-) used to perform the resetting in order to make uploading a sketch easier and that is all.

If you have no control over the other device and don't want your arduino to reset you can check the 328P datasheet: "The External Reset can be disabled by the RSTDISBL fuse, see Table 28-7 on page 282."

Also, there is a possiblity to have knowledge of what has resetted your Arduino. It does go a bit further than Arduino only and involves reading the register: "11.9.1 MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU reset."

@FuaZe That will only tell you that something lowered the reset pin - it can't know what that something is, and there's more than one thing on an Arduino that can lower that reset pin.


text:
Can I reuse crystal frequency of Arduino?
If I use some IC which requires clock frequency like 16MHz, can I take one from Arduino?
Or this it too high frequency to travel to neighboring board?

Set the CKOUT fuse to 1, will give you the clock output. And you have to set PORTB0 to an output (pinMode(8,OUTPUT);). You probably don't want to use to long of a trace/wire.

The expense of properly sending a clock off-board will be greater than generating a new one over there, so only do it if your signals must be synchronized.

Possible duplicate of Arduino constant clock output

am dividing arduino clock frequency from 16Mhz to 8Mhz but am getting spike in clock signal how can i reduce that

The frequency is important. Make sure they are the same or it will probably not work.

Yes but you need to know what you are doing.  You will need a clock driver and possibly a clock receiver depending on the devices you select.  Then you need to modify both boards voiding any possible warranty.
The best answer is NO!

I don't agree with that. I don't see any problem with using the arduino clock to clock another chip. The whole point of buying an Arduino is experiment and learn! Screw the warranty. I personally have done it often. Its not that hard.

I disagree. Why is it necessary to change the board given Gerben's comment? And I dunno understand, why you are referencing to warranty. Nobody will reasonably try to claim a warranty for a 15€ device where a failure is almost always user generated. If someone over here ever has successfully claimed a warranty for an arduino, let him now speak...

Why not download this application from TI: http://www.ti.com/lit/an/scaa082a/scaa082a.pdf Then download: https://www.elprocus.com/crystal-oscillator-circuit-and-working/ after you read them and understand them you will know why I answered as I did. Note this is an open ended question without the necessary specifics to do a proper design. Your solution may work but what happens if yo build thousands of them?


text:
How to connect Arduino device to Linux?
I wrote Arduino sketch and it works. It waits for a command and answers text on response.

Simultaneously, I can't get any response with command line tools.
For example, I have the following code to get temperature:
#!/bin/bash
tty=/dev/ttyUSB0
exec 4<$tty 5>$tty
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
#stty -F $tty 9600 -echo
#printf "temp\n" >&5
echo temp >&5
read reply <&4
echo "$reply"
#tail -n 1 - <&4

It returns empty or hang under different circumstances.
Also, if I run built-in Serial Monitor, I can see responses on command lines like:
echo temp > /dev/ttyUSB0

But I see nothing with commands like tail -f /dev/ttyUSB0
What I am doing wrong?

I really want to say using Linux is where you going wrong, but that would be childish. :)  I'm not sure if I read it right, but are you trying to connect two apps to the same console port?  I wouldn't expect that to work, but I only use Windows, does that work on Linux?

Add the flag -hupcl to your stty command.  That will disable the assertion of DTR which is resetting the board.
 hupcl (-hupcl)
             Stop asserting modem control (do not stop asserting modem
             control) on last close.

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset.  So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.
You can do that with the sleep command: sleep 3
Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with
stty -F $tty hupcl

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board.  So in summary try this:
#!/bin/bash
tty=/dev/ttyUSB0
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
sleep 3
echo temp >$tty
read reply <$tty
echo "$reply"
stty -F $tty hupcl

I was wishing to use reset feature. Why doesn't it work with it?

In that case leave the stty as it is, but just add the three second delay so it can get past the bootloader before you send your request.

I was waiting long enough with tail -f, also I was observing directly, that Serial Monitor does see the output, while tail -f does not.

You can't read the data with two things at once - only one thing will get it.  Also you have to wait before sending "temp" otherwise it just won't ever get it.

By the way, what are exact conditions for resetting? I have 3 commands in the script, touching the port: stty, echo and read. Will it reset 3 times or only one, how to know?

One more thing: every operation you perform from your shell script will trigger a new reset.  You should disable reset at the beginning (which will make it reset once) then enable it again afterwards.

As it happens I was answering that at the same time as you asked it - the same thought occurred to me ;)

Why can I see the answers with Serial Monitor? Why doesn't it reset then?

While it is open it is open - it's only when the last file descriptor is closed that it resets the board. While the serial monitor is open there will always be an active file descriptor.

Isn't it possible with shell script to keep port opened?

Not really, no.  It executes a series of distinct commands with little to no state between them.  You want to use Perl or Python or something if you want to do that kind of thing.  I can recommend Device::SerialPort in perl, and people do keep trying to use PySerial

Okay, but why doesn't read command wait until it get something? Why should I make explicit delay? Why can't I initiate reset, then wait for ANYTHING with read, then read it, then exit?

You are sending first to initiate a read from what I understand. It's that initial write (echo) that must be delayed.

PySerial is not too bad to use if one wants to transfer text. What is somewhat more problematic, as it goes against the grain of Python, is to do byte-oriented data transfer, but it's not impossible, it requires a bit of juggling.

@IgorStoppa That's why I say "try and use it" ;)  Personally I do it all in pure C...

@Majenko: it depends on the overall language you want to use in a project ... using multiple languages is not necessarily the kindest act toward who will read it later on :-)   - anyway, it's not that long/complicated: https://github.com/01org-AutomatedFlasherTester/pem/blob/master/src/mappedbuffer.py

@IgorStoppa Urgh - I feel dirty now. I need to go and scrub my eyeballs.

@Majenko you mean, that no synchronization or buffering occur? Computer does not feel that Arduino is not on and just blindly send bits, which turn lost?

@Dims The computer has no concept of what an Arduino is.  When you send data the Arduino receives it.  If the Arduino is in the bootloader, which it is for 2 seconds after reboot, then the bootloader receives the text, not your sketch.  Only once the bootloader is finished with will any text sent to the Arduino make it to your sketch.

@Majenko see my separate question on it: http://arduino.stackexchange.com/questions/16781/doesnt-arduino-reports-dsr-data-set-ready-correctly
I agree, that computer has no concept of Arduino. But computer should has concept of obeying the protocol.

@Majenko: it's portable (as in: works without recompiling) and doesn't require using also perl (no, writing everything in perl was not an option and anyway I would have not liked it)

@Dims The Arduino is ready to receive the moment the reset is performed. It's just your sketch that isn't ready to receive because the Arduino is busy doing other things first for 2 seconds before your sketch is run


text:
Arduino-like ethernet only board?
I don't think USB chip is more expensive than Ethernet chip. So, I expect there should exist a board like Arduino, but where USB is removed in favour of Ethernet.
Are there such boards?

Yes, there's the Arduino Ethernet. Available from Sparkfun for example

Important to note: you need to use an FTDI serial to upload sketches. You cannot upload sketches through the Ethernet chip.

@Len Correct, this would require a bootloader with Ethernet support as mentioned by Majenko. In this context it is also worth to note that the original Arduino Ethernet is retired.

It is highly unlikely you will ever find an "Ethernet only" board. There are plenty of boards that have both Ethernet and USB, but one without USB? I doubt it.
To make an Ethernet only board you would first need to create a bootloader with built-in support for the Ethernet port as well as a way of configuring that port to suit your network. Than kind of program would be rather large and take up a fair proportion of the flash memory, leaving you with much less room for your own program.
And as you have rightly noticed, USB chips (especially the dreaded CH340G, the bane of my life) are so cheap now, so why wouldn't you include one on your board?
So you get boards with both USB and Ethernet, and you install the software (generally) through USB which doesn't need any special configuration or complex software to get it to work.
Some boards provide "OTA" (Over The Air) updates, such as the ESP8266, but these generally require the OTA software first installing via the USB (or UART) connection to allow it to communicate on your network and accept OTA firmware. Others, such as the Arduino Yun, use multiple MCUs to provide remote programming. In the case of the Yun you get a "host" microcontroller which is considerably more powerful than the AVR microcontroller that it is programming, which always strikes me as a little pointless.
So no, I doubt that anyone would ever want to make an Ethernet only board.

I don't understand, why would I need to create "bootloader" with Ethernet while I don't need with USB? What is magic difference between two jacks?

You need a bootloader whichever you use. The "magic" difference is that the USB bootloader has already been written. Also USB is much much much simpler than Ethernet. A full IP stack is large. Very large. And complex. Very complex.

What about just Ethernet, w/o IP stack?

And how is that supposed to work?

You are showing a fundamental lack of understanding of technologies and terminologies. Go look at just what Ethernet is.


text:
How to encode resistance change (reed) for Arduino?
I have a water counter which switches reed on each 10 liters of water. I would like to count these values with Arduino.
I wrote a program which counts changes from analog input and connected counter between +5V and analog input. It counts well but I am doubt I connected correctly. Because when reed is opened, then analog input is connected to nothing, while it should be connected to GND.
How to implement correct conversion from reed to analog or digital input?

You could add a large value resistor as a pull-down.

A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.