Using Arduino to control a 12v car light system? I am new, but I am wondering what options I may have to control a 12v line that connects to a light with Arduino i/o.

Given the voltage limitations of an arduino, I am thinking using some kind of 5v relay to switch a 12v line on/off ( if it exists )

Though I was also hoping to be able to utilize the PWM pins in conjunction with a 12v line to 'reduce' it to 6v without using a resistor.  (though I would have no idea how to go about this, or if it is even possible).

Any help appreciated.

Yes, you can use a relay. However, you'll almost certainly need to drive the relay with a transistor because the current requirements of the relay will be too high for an Arduino pin.

Better to use a logic MOSFET N-channel transistor as an electronic switch. You connect the Arduino's output pin to the gate of the transistor. You connect the + terminal of your 12 volt source to one end of the light, and connect the other wire from the light to the drain on the MOSFET. You then connect the source pin on the MOSFET to ground, and tie the ground of your Arduino to the 12 volt negative terminal.

In this setup, the MOSFET acts as a switch. When you switch the output pin of your Arduino to HIGH, the MOSFET turns on, providing a very low resistance path to ground. Current flows from the +12 volt supply, through the light, through the MOSFET, and to ground.

When the Arduino's output pin is low, the MOSFET acts as an open switch. There's no path to ground so the light is not lit.

You can't use PWM to lower 12 volts to 6 volts without some additional circuitry. PWM rapidly pulses the output from all the way on to all the way off. If you feed a PWM pin into a transistor, it can be used to create a higher voltage and/or current pulsed signal. However, pulsed DC is not the same thing as a lower DC voltage. You'd need to feed the pulsed 12 volts through a reservoir capacitor, perhaps 2 capacitors (and possibly a choke)  in order to average out the pulses into a lower DC voltage. That simple approach would work ok for powering a 6 volt incandescent light, but would not be good enough to power a solid state component because the output would not be even enough. It would have a fair amount of ripple and high frequency noise in it.


Arduino recieving binary I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is 01 it would turn a red led on, if it was 11 it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?

Pretty much anything is possible.

There is a method known as bit banging which toggles a generic IO pin to create a protocol, and read changes on another generic IO pin to read in the data of a protocol.

The trick is in creating a protocol.

Fortunately that has all been done for you - the SoftwareSerial library. It will create a bit banged version of the RS232 serial protocol using any combination of IO pins to transfer data between devices.


How do I proceed with a fall detection sensor? I am working on a human fall detection system using accelerometer and gyroscope which raises alarm in case of a fall. In all the papers I have read people have used net acceleration magnitude and compared it with a threshold and coupled it with change in orientation to detect fall. My question is would it be better to use acceleration in z-axis(normal to earth's surface) and compare it to threshold as compared to net acceleration as it might reduce false positives as net acceleration can exceed threshold in case of running but that won't happen if i take only acceleration in z-axis. Is my approach right?

How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

Find the derivative of acceleration over time, also known as jerk. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.


Arduino ESP8266 communication I saw two peculiar things while googling this subjects.

Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?
Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?

There is some uncertainty as to whether the ESP8266 has 5V tolerant inputs or not.  This uncertainty stems from differences in an early Chinese datasheet translated by the community, and the current English datasheet.  It's better to err on the side of caution though and translate your 5V signal from the Arduino to a 3.3V one with either a proper logic level translator or a resistive divider (note that the latter can limit the maximum baud rate you can use).

You can read more here:

https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

  Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Bad information begets bad information. People copy poor quality examples and tutorials and pass that bad knowledge on to others1.

Many Arduino boards only have one hardware UART port, and that is shared with the USB connection to the PC.  It is hard to reliably use that UART for other serial communication, since doing so will break your ability to upload code while your hardware is connected.  So it's simpler in that case to use SoftwareSerial (or one of the better implementations).

However, I would never advocate using SoftwareSerial unless you absolutely have to.  It barely functions at 115200 baud (one of the common default ESP8266 baud rates).  If you have a convenient hardware UART then really you must use it, for the sake of your sanity if nothing else.

1: Even worse though are the examples where people use SoftwareSerial to communicate over the pins of a hardware UART... that's just plain stupid...


Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom? Hi I'm a newbie and working on a project with Arduino Due(Atmel3X8E).I want to try and save the important variables to the eeprom during a power outage,using the brown out detector.Is it possible to do this?
Thank you.

Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.

The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

When external power goes off, you well get enough time and power to store your bytes safely.

How it works

When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER_GOOD signal is LOW.

When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER_GOOD signal goes to HIGH level and your program may start save data to EEPROM.

Why the optocoupler?

We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.


Relay starts trigger about 6 times when connecting arduino to laptop I have a fairly simple code to turn a relay on-off every 2 seconds
When i attach the USB of the arduino Uno to the laptop, it goes into a frenzy and the relay triggers on off for 6 times within 3-4 seconds and then it settles down.
This however doesnt happen when connecting directly to the power output.
Is there something that needs to be wired to stop this happening ?
I am using an arduino Uno with a relay JQC-3FF-S-Z connected directly to the arduino pins.
const int ONOFF_TRIGGER_PIN = 2;

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

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(ONOFF_TRIGGER_PIN, LOW);
  delay(2000);
  digitalWrite(ONOFF_TRIGGER_PIN, HIGH);
  delay(2000);
}

The markings on your relay suggest the coil is for 5VDC. But you have the coil supply wired to 3V3. Move the coil supply to 5V, and try again.


Pro Micro - Measuring voltage between two pins, without using GND Quite new to this but making pretty good ground. I have an issue I'm not sure how to solve. I want to add a Pro Micro to an RC Toy, I can easily power it from the toys GND and 5V power. But then I want to use the voltage going to an LED on the toy (uses a different ground) to trigger an event within the Pro Micro.

I can power the Pro Micro from USB and and accomplish what I need with AnalogRead(). But if I connect the GND from the toys main power input to the GND from the LED it no longer acts as it should. I'm thinking these GNDs are not common, or are a separate circuit.

What I'm wanting to know is.. I'm using PIN10 on the ProMicro for the AnalogRead(), can I make it so that maybe PIN11 is the GND for that reading?

Thanks.

No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.

You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.

It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching".  There will probably be a resistor on one side or the other of the LED.

With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.


Use a button on LCD shield to pause the code I'm creating a Temperature logging device with thermocouple K and SD card breakout and a RGB LCD Shield Kit w/ 16x2 Character Display (with buttons).

Everything runs ok: temperature displaying on the LCD and logging on txt file on the micro SD card work well

Now I try to configure button on the shield

button UP to reset measurements and timer , it works
button Down to pause measurements, then when pushed again, continue measurements. I don't know how to do that (how to go out the while condition).

 if (buttons) {

if (buttons & BUTTON_UP) {

  lcd.clear();
  lcd.print("RESET ");
  if (SD.exists("datalog.txt")) {

    SD.remove("datalog.txt");
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
  }

  else {

    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // if the file is available, write to it:

  }
 StartTime = millis();

  delay(500);

}
if (buttons & BUTTON_DOWN) {
  lcd.clear();
  lcd.print("STOP");
  while (buttons & BUTTON_DOWN){

      ;
  }

}

I already thank you for your help,

Vincent

You are not saying much about how buttons is valorized or its data type, but assuming it is a numeric variable which gets somehow set by, let's say a readButtons() function, then consider the following snippet replacing your while-loop:

do {
  delay(10);
  // re-evaluate whatever sets the buttons variable
  buttons = readButtons();
while(!(buttons & BUTTON_DOWN));

The loop above will continue until the button down is pressed and it's a little resilient regarding contact bouncing, but not 100% reliable, so I assume the readButtons() performs also some debouncing.


Visibility of #define between sketch and library I want to have a define from my sketch be picked up by a library.
Here is a similar question for references: Using #define and multiple classes

I have a CI server that compiles my arduino sketchs on commmit. It pulls all my personal libs from an other repository and compiles the sketch using arduino-builder.

Now i want it to also make a debug build. (Some of my library's have debugstatments in them i enable using a #define debugsomething.

Is there any way i can get the compiler to pickup the #define in the sketch or am i better off making a very complex build script that modifies the headers between builds?

You need a common place that the building of all the places can get the definition from.

That isn't the sketch. The sketch is one of the things that would have to look at that common place.

That can either be a single shared header that everything else (that needs it) includes, or it can be a -D flag added to the compilation command.

For instance, adding:

-DDEBUG=1

to your compilation command is the same as adding

#define DEBUG 1

to every single file you compile.


How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go. For my next project I'd like to use a battery pack to power my Arduino.
I would also like to get a small solar panel and charging module to charge these batteries when possible (during the day).

What is the right type of battery for this kind of application?
What are the differences given this context?
What are the factors I need to consider when choosing a rechargeable battery for this application?

Look at Battery University for many good ideas.

Both NimH and LiIon are viable for your application.

LiIon are easier to manage well if managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.

NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.

As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.

Nimh give 1.0 - 1.2 V/cell so eg

6 cells give 6 - 7.2V for a 5V system,
5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and
4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.

LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.


perform an action maximum x times per hour is it possible to perform an action maximum x times per hour on the arduino?

I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again

sorry for bad english, this is not the language I speak (and type) mutch

Sure it's possible. It would be better if you had a real time clock module. Then you could use time-of-day.

You need to define your problem a little better. Would it be ok to run the sprinkler every 5 minutes, then not again for 40 minutes, for a total of 4 sprays in an hour, but clustered together? Do you want to prevent 4 sprays in a clock hour, or not go over an average of 4 sprays per hour?

Without a realtime clock module, I guess here's what I would do:

After a spray, record the time (in millis). Then in your loop, don't spray again for 15 minutes (15*1000*3600 milliseconds.)

The code would look something like this: (not real code, more like pseudocode)

const unsigned long fifteenMinutes = 15*1000*3600;
unsigned long nextSprayTime = 0;

loop()
{
  if (millis() >= nextSprayTime)
  {
    if (humidity < 50)
    {
      spray();
      nextSprayTime = millis() + fifteenMinutes;
    }
  }
}

Edit: You said, in comments:

  i want it not to go over 4 sprays an hour,i have the ds1307 rtc
  module. situation: ist an automatic egg incubator and the humidity
  must be between 50% and 60%.i control the sprayer whit a dht11 sensor
  an a servo connected to an spray bottle. if the humidity is below 50 %
  the servo starts whit spraying.the servo keeps on spraying every
  second until that 60% mark is reached and then shuts of.so the amount
  of water in the box is way to much and so the humidity keeps on
  climbing until the 100% mark whit is deadly for the eggs

Ok, that gives your readers a clearer picture.

You're dealing with a process control problem, not just a hardware or software problem.

When you spray water, it will likely take several minutes for the change in humidity to stabilize and be detected by your sensor.

Your current approach sounds wrong because you dump far too much water into the system, and don't give it time to reach a new equilibrium before adding more water.

You need to collect some data.

There is going to be a significant lag between putting a spray into the incubator and sensing the increase in humidity, and when the increase reaches it's max.

You need to measure that lag.

You also need to know how much a single spray increases the humidity.

You should probably **ALSO* figure out how many sprays at a time you can spray before water droplets form on the walls of your incubator and on your eggs, since I assume that is very bad and to be avoided at all costs. Thus I would add a moisture detector to your system (A small piece of cloth with electrodes on it at 2 locations a couple of CM apart, and a sensitive conductivity sensor that detects the change from insulator to weak conductor that takes place when the cloth becomes saturated with water.)

You should also figure out how fast the humidity in your incubator drops if you don't add any water, for a variety of different conditions. (Likely affected by current humidity, outside temp and outside relative humidity, so you probably want 2 humidity sensors, one inside and one outside the incubator, and to record all the variables and graph them.)

I would suggest writing a data collection program. You might want to run it with the serial cable connected to a PC constantly, or install an SD card and save your data there.

In all your tests, you probably want to wait a significant time (15 minutes? 1/2 hour? 1 hour?) for the incubator to reach equilibrium before beginning your test.

You want the conditions of your incubator to be as close to your real-world conditions as possible. You might want to put eggs (dummy eggs, grocery store eggs at room temp, or something like that) in the incubator during the test to allow for the amount of water they absorb. You want the outside temp to be as close to your real-world temp as possible. If the incubator will be exposed to direct sunlight, air vents, wind, etc, then you want those same conditions.

At each step in every test you should record the current time, the current outside temp and humidity, and the current incubator temp and humidity, and the time of each spray you trigger.

Add your condensation detector at the beginning, and any time it detects condensation you should sound an alarm, record the time that it trips, and abort the current test. If you get liquid condensation you've done something wrong and need to adjust.

Write a program for your computer that graphs all your data points over time. Every time you run a test (other than the very first test) graph all the data and look at it. Patterns will probably jump out at you.

Test 1:

Record the time and the current humidity. Add one spray of water, and then record the humidity for 15 minutes. Look for an increase in humidity and when it peaks. The time from adding a spray to the peak increase in humidity is what you want.

Test 2:

Then modify your program to log the spray-to-peak-humidity-increase time, and each time it detects the humidity starting to drop again, spray once more, log the current outside temp and humidity, the inside humidity and outside time of the spray, and repeat.

This will give you spray-to-peak-humitity lag times over a range of humidity values. Graph that data with starting relative humidity on the x axis and the lag time on the y axis and look at it. Is it a constant value? A straight line? Is it a geometric curve? Exponential? Come up with a curve that fits the data fairly well.

Test 3:

A test that uses an increasing number of sprays, looking for how many sprays you can do at once before you cause condensation.

Start with 2 sprays.

Look for the peak increase in humidity, and once the humidity starts to drop, increment your spray counter to 3, spray that many times, and repeat. When the condensation alarm trips, stop the test.

Note that the number of consecutive sprays you can do before the moisture alarm trips will probably change for different starting humidity levels. My guess is that the max number of sprays you can add without triggering condensation will be highest at your lowest humidity level, and as the humidity increases, you'll get condensation with less and less sprays.

Test 4:

Figure out how to measure the max number of sprays that trigger condensation when you start at less than your minimum humidity, at your minimum humidity, at halfway between min and max, and at max. (This experiment will take some thought since it's not easy to get to a given humidity level, and once you trigger condensation you'll have to stop, dry everything out, and start again.)

Test 5:

Get your incubator as close to the maximum acceptable humidity (60%) as you can at the beginning of the test, or even a little above. Simply record the humidity every minute until it drops to the lowest acceptable level (50%). Graph the data. That will show you how fast the humidity drops if you do nothing.

Test 6:

Repeat test 5 for the range of outside conditions you might find in your production environment. (If you're in a climate-controlled space, do you have summer and winter thermostat settings? Test for those upper and lower ranges. How much does your indoor humidity level vary?)

Now what?

Now you have lots and lots of data.

More than likely you have an idea of how many sprays you can add at a time without triggering condensation over your humidity range. This should be fairly simple: (for example, at humidity < 50% to 52%, you can use 3 sprays.  AT 53-55%, 2 sprays. Above 55%, 1 spray.) You should also have a rough idea how much increase you'll get in humidity for a given number of sprays.

You have an idea of how fast the humidity drops if you don't add water.

You have an idea how long it takes for a spray set of sprays to cause a peak in the humidity level.

Write a program that strives to keep the incubator in the middle of your desired range. If 50% is your absolute minimum humidity level and 60% is your max, then trigger sprays at 52%, not 50%. Spray as many sprays as you can without causing condensation (or overshooting your max humidity), then lock out sprays for the time period you calculated as the time it takes for your sprays to cause the maximum increase in humidity.

If you've found that the max number of sprays you can do at a time is different for different humidity levels, use code that comes up with a number of sprays that stays below that limit. Also try to estimate how much increase in humidity you get per spray, and each time you trigger a series of sprays, stay below the number of sprays that reaches your max humidity.

If you've found that the conditions outside the incubator have a big effect on your system, adjust your code to compensate for those changing conditions.

You want a system that uses small adjustments over time to keep a system at near equilibrium. Big adjustments will likely cause wild variations in conditions that go outside of the acceptable range.

Other considerations:

Do you need to open the incubator at regular intervals to check on the eggs or turn them, or do you have an egg turner? If you do need to open the incubator, you will need to figure out the effect this has on your temp and humidity levels for the range of outside conditions you face. You can probably build your system with a door sensor that detects you opening the door, the outside temp and humidity, and how long the door is open. Once you close the door, it would note the new inside temp and humidity and make an educated guess as to how much the humidity will drop after being open, and add water accordingly.


What are the correct pins for TWAI (CAN) on ESP32? compared to the microchip's PICs:
pic16f's does not have an onboard CAN peripheral. so you need an SPI - CAN controller (like MCP2515).
some PIC18f's have an onboard CAN controller, and only need a CAN transceiver. In these cases there are exclusive TX and RX pins to be used.
Are there specific pins to be used as a CAN bus on esp32?
peripherals like adc, i2c and others need to use specific pins. Does this happen with CAN too?
I'm using the following configuration:
2 ESP32 devboard boards - arduino on PlatformIO
Pin 5 as TX and pin 4 as RX (already in the CAN library),
2 Sn65hvd230 transceiver modules
I looked for information about it in the documentation, but I couldn't find it.
I appreciate any help.

I looked for information about it in the documentation, but I couldn't
find it.

Well, some of their documentation says:

The TWAI controller’s interface consists of 4 signal lines known as
TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed
through the GPIO Matrix to the ESP32’s GPIO pads.

And that sort of seems to be backed up by their examples that make use of TWAI_GENERAL_CONFIG_DEFAULT to generate a structure with the arguments filling fields that use gpoi_num_t.
There is documentation to the GPIO Matrix generally in the ESP32 technical reference.  It is described there as follows:

The ESP32 chip features 34 physical GPIO pads. Each pad can be used as
a general-purpose I/O, or be connected to an internal peripheral
signal. The IO_MUX, RTC IO_MUX and the GPIO matrix are responsible for
routing signals from the peripherals to GPIO pads. Together these
systems provide highly configurable I/O.

(My emphasis in the above).
And also there is a table (Table 25) in Appendix 2 of the ESP32 datasheet for the GPIO matrix.
Many of the small chips, like the PIC16F series ones, have no internal routing for peripherals, except for deciding which of one or two special functions to use rather than GPIO and ADC channels.  Most of the of the ATTiny and ATMega series AVR chips that are not in the 0- and 1- series don't.  The 1- and 0- series an a few of the older series parts (e.g. ATTiny841) give you a fixed number (usually two) pre-determined destinations to chose from for some peripherals.
This sort of thing gets more flexible as you get into larger chips, but the having that "matrix" feature that lets choose more freely is comparatively rare.  Some of the Cypress "PSoC" labeled chips have this sort of feature.


pulseIn() function not working I want to find the length of upper one signal (purple one). So for that, i used pulseIn() function for that. But i just get 0 as a result in serial monitor.

int pulsepin = 8;
int value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Here, above is my arduino code which i used. I don't know why I don't get any reading except 0.

pulseIn() returns an unsigned long (32 bits) not an int (16 bits), so you may have some truncation occurring in your program leading to a 0 value.

Hence you should modify your program as follows:

int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Also beware that pulseIn() has a timeout (it will not wait forever).
This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get HIGH, then waiting for it to get back LOW. If no pulse is detected and complete (LOW -> HIGH -> LOW) within this time, then pulseIn() will return 0.

Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an unsigned long:

e.g. if you need 10 seconds, then:

  value = pulseIn(pulsepin, HIGH, 10000000UL);

I am not sure why you use delay(1000) in your loop(), I would remove it as a pulse may occur during that time and it would not be seen by your program.

Here is a suggested update (I also used const where it made sense but that won't change program behavior):

const unsigned long PULSEIN_TIMEOUT = 10000000UL;
const int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  Serial.println(value);
}

You may also want to avoid printing 0 values since they mean no pulse was detected:

void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  if (value > 0)
    Serial.println(value);
}


Controlling 12v DC LED strips using Arduino UNO I have 2 LED strips with 6 LEDs on each. They use a 12V power supply.

My question, how can I use them like regular LEDs using Arduino UNO? Without any MOSFETS or transistors if possible.

And can I use PWM?

It's not safe for the MCU without transistors or so.

You can use some kind of LED driver (for example TLC5940 with on chip PWM) or ULN2003 as 8 channel low side switch (instead of 8 transistors, PWM is possible if you do it programmatically) or many others.

With single transistor it looks like:

Where R_1 can be about 1K and transistor can be any NPN that could handle led current.


Chips & High voltage: Connected in Series? I have 3 micro-controllers that will be connected to a battery, and I need to provide each of them between 3 and 5 volts maximum.
I have 3V batteries but they do not seem to provide enough power, while putting to of them in series would fry the chips as it busts the 6 volts max.
My question is, if I provide 9 volts to 3 chips connected in series, would current drop be distributed evenly to 3V across all chips, or would for example fry the first one?

simulate this circuit – Schematic created using CircuitLab

If  you put three resistors of the same value in series, then you would get equal voltage division between them.
But chips are not like resistors. Their current usage is not constant and typically vary by orders of magnitude even within each clock cycle. See why this would be a problem?
If you have good 3V batteries that supply 3V up to the maximum current that the chips can draw, and the chips are rated to run reliably at 3V then there is another problem. Maybe you need decoupling capacitors across the chips?


Stuck in a small confusion about Infrared leds and receivers? I have a very simple idea I want to implement. I am making a home automation using an Arduino Uno. I am familiar with Arduino programming but the problem is what kind of IR receiver I need to buy if i want my TV remote (or similar) to communicate with my Arduino.

Can you suggest me any example (low cost, and available in India)?

Element14 has an India based store, and they carry these IR devices.
Here is one for 66 rupees:
http://in.element14.com/vishay-semiconductor/tsop38238/ir-receiver-45m-38khz-th/dp/2395954?MER=MER-BPR-4PPM-SP-VSHY-OD&

You may want to do research into what the carrier frequency of your remote is also. Most are generally around 35 - 40khz, and the receiver I provided a link to is 38khz. It should work, but if you want to be safe I suggest you look it up. Or, if you have an old TV lying around, you can pull one out of that.

Hope this helps.


Arduino restarts problem I want to assign -1 to count variable again when count == 16 but when I have assigned -1 inside the if condition I have marked below in the code, the Arduino restarts.

Can anyone guess what is wrong here?

#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
#define DISPLAY_WIDTH 16

// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

int count = -1;
char drawNo[4];
int m = 0;
int turn;
class KbdRptParser : public KeyboardReportParser {
    void PrintKey(uint8_t mod, uint8_t key);
protected:
    virtual void OnKeyDown(uint8_t mod, uint8_t key);
    virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
    uint8_t c = OemToAscii(mod, key);
    count++;

    if (c)
    { OnKeyPressed(c); }
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key) {
    static uint32_t next_time = 0;      //watchdog
    static uint8_t current_cursor = 0;  //tracks current cursor position

    if (millis() > next_time) {
        lcd.clear();
        current_cursor = 0;
        delay(5);    //LCD-specific
        lcd.setCursor(0, 0);
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if (current_cursor++ == (DISPLAY_WIDTH + 1)) {    //switch to second line if cursor outside the screen
        lcd.setCursor(0, 1);
    }

    int keys = (int) key;

    if (count == 4 | count == 5 | count == 6 | count == 7) {
        turn++;
        drawNo[m] = (char)keys;
        //lcd.print(drawNo[m]);
        Serial.print(drawNo[m]);
        Serial.print(m);
        ++m;
    }

    if (count == 16) {
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }
    }
}
void printScreen() {
    int j;
    lcd.print(" DRAW NO : ");

    for (j = 0; j < 4; j++) {
        lcd.print(drawNo[j]);
    }
}
KbdRptParser Prs;

void setup() {
    Serial.begin(115200);
    Serial.println("Start");

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay(200);
    Hid.SetReportParser(0, (HIDReportParser *)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay(200);
}

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

int m = 0;
...
    drawNo[m] = (char)keys;
...
    ++m;

No other references to m in your code. Therefore m keeps increasing and you are writing outside the bounds of the array drawNo, corrupting memory.


Playing audio files with sine wave from arduino So, when searching for a way to play audio files through the Arduino, I came across this site: How to play WAV audio files with Arduino Uno and MicroSD card

This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?

I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.
It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)
From GitHub's wiki:

All 328 based boards: Arduino Uno, Nano, Duemilanove, etc
Mega Types: 1280, 2560, etc
No Due support currently.

You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).
Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.
Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.

Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.

If you want to take a look, go to this page for more informations on the advanced features
A last thing that I have to say is that the functions are really straightforward:
TMRpcm audio;
audio.play("filename");    plays a file
audio.play("filename",30); plays a file starting at 30 seconds into the track
audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.
audio.disable();           disables the timer on output pin and stops the music
audio.stopPlayback();      stops the music, but leaves the timer running
audio.isPlaying();         returns 1 if music playing, 0 if not
audio.pause();             pauses/unpauses playback
audio.quality(1);          Set 1 for 2x oversampling
audio.volume(0);           1(up) or 0(down) to control volume
audio.setVolume(0);        0 to 7. Set volume level
audio.loop(1);             0 or 1. Can be changed during playback for full control of looping.


Prioritizing one sensor I want to ask is there a possible code to prioritize a specific part of a code? So I'm doing this project where I want to utilize muscle sensor, servo, and a button on an app over Bluetooth. The problem is since all is running in void() loop, even though I am not using the muscle sensor I can't move the servo with the app, since it reads the muscle sensor first. So is there a possible code to make the muscle sensor stop for a period of time after the button is pressed on the app and the servo is moved?

Here is the code:

void loop()
 {
  if(Serial.available()>0)
   {
    char data = Serial.read();

      if (data == 'a')
       {
        myservo.write(15);
       }
  }

int value = analogRead(EMG_PIN);

 if(value > THRESHOLD)
  {
   myservo.write(15);
  }

  else{
       myservo.write(140);
      }

So the first code is a bluetooth code where the servo is controlled through a button on an app. The second one is a muscle sensor. As stated above the problem is it will always read the muscle sensor even though the button is pressed from the app.

#include <Servo.h>

 int increment = 0;

 Servo myservo;

 void setup() {

   myservo.attach(1);

 }

 void loop()
 {

   Serial.println(increment++);

   if (increment > 9);
    {

     if(Serial.available()>0)
      {
       char data = Serial.read();

       if (data == 'a')
       {
        myservo.write(15);
       }
 }

      else if (increment = 0);

      int value = analogRead(EMG_PIN);

      if(value > THRESHOLD)
       {
        myservo.write(15);
       }

     else{
       myservo.write(140);
      }
  }

You have to think of your program as having two distinc modes of
operation:

The "fixed servo" mode is entered when you press the button on the
app. In this mode the servo is kept at a fixed position. The mode
lasts for a predefined delay.
The normal (not fixed servo) mode is the default mode. In this mode
the servo is positioned according to the reading of the sensor.

So you need a boolean variable to remember whether the "fixed servo"
mode is active or not, and the code in loop() should take care of
providing the correct behavior depending on the mode, and updating that
variable when needed. For example:

void loop()
{
    static bool fixed = false;  // whether we are in "fixed servo" mode
    static uint32_t fixed_started;  // when the mode started
    uint32_t now = millis();

    // On button press, start "fixed servo" mode.
    if (Serial.available() && Serial.read() == 'a') {
        servo.write(SERVO_LEFT);
        fixed = true;
        fixed_started = now;
    }

    // Get out of "fixed" mode after some delay.
    if (fixed && now - fixed_started >= FIXED_DELAY) {
        fixed = false;
    }

    // If not in "fixed" mode, react to the sensor.
    if (!fixed) {
        if (analogRead(EMG_PIN) >= THRESHOLD) {
            servo.write(SERVO_LEFT);
        } else {
            servo.write(SERVO_RIGHT);
        }
    }
}


Can I run 3 motion sensors with a voltage regulator? I want to power 3 hc-sr501 PIR motion sensors with a voltage regulator that can output 5v-1A.
If I make such a system, will there be a noise?

Many internet sources like this one claim the HC-SR501 requires less than 50uA (or 0.00005 Amps).  Likely this is only in a quiet or quiescent state and current demand may increase initially when power is applied and when motion is detected.  Regardless, this is an insignificant fraction of a 2 Amp power supply.
Likely the Atmel 328p will require several times the total current of the 3 PIR sensors added together.  Still, the over all current of the described project (1 processor and 3 PIRs) is expected to be far less than half the capacity of a 2 Amp power supply.
It is suggested to keep the PIR to Arduino wires as short as possible to avoid noise.  It would be preferable they only be several inches (10s of centimeters).  And certainly not as long as several feet (a meter).


Do (cheap) SD modules support file I/O? I noticed there are cheap SD modules and complete SD shields.
I assume the last are used for a 'final' product and not for bread-boarding (?)

However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition  to SPI interface)?

E.g. can I use the file I/O and the SD library with the This SD module?

There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.

The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.

What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).

The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.

So to answer your question

If you use a module and shield that use the same IC (chip) to access
the SD card and the same library then they will almost always behave
the same.
If you use two different shield (different ICs) which
need different libraries then they MIGHT have different
functionality.
If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)

If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.

==== Edit ===

When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.

When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.

Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.

There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.

So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call WriteFile().  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that WriteFile() is actually storing it on the hard disk of a PC somewhere in the world?

Your call to WriteFile() is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling read() and write() but it isn't.


How far can a HC-SR04 can stand from the microcontroller? I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

I have a couple measuring the liquid level of two tanks.

The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.

Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.

That's the longest I needed, so I haven't tested beyond that.


Communication between Arduino and XBee I have two XBee Pro S2Bs: one is plugged in to a USB explorer, and; the other is plugged into an Arduino Wireless Protoshield, which is connected to an Arduino Uno.

My XBee connected to the explorer is configured as the coordinator in AT mode, and the XBee connected to the Arduino is configured as a router in AT mode. As a side note, I tested the network with a second USB explorer, and I was able to communicate between both XBees.

I uploaded the following code to the Arduino (which is just a sample I pulled off the internet somewhere):

char rx_byte;

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

void loop()
{
    if (Serial.available() > 0)
    {
        rx_byte = Serial.read();
        Serial.print("You Typed: ");
        Serial.println(rx_byte);
    }
}

Once I upload the code and turn on the serial monitor for the Arduino (using either the Arduino IDE or Visual Micro, with the Arduino plugged in via USB), and turn on the serial monitor on for the XBee connected to the USB explorer (using the serial monitor in XCTU), I get the following results:

If the wireless proto shield has its switch set to USB mode, then I can send data from the Arduino serial monitor to the serial monitor in XCTU, but the Arduino serial monitor doesn't receive data that is typed into the XCTU serial monitor.
If the wireless proto shield has its switch set to Micro mode, then I get mostly the opposite result.  I can send data from XCTU serial monitor to the Arduino serial monitor, which the result is returned to the XCTU serial monitor, e.g., if I type "X" in XCTU serial monitor, both serial monitors say "You Typed: X".  However, if I try to send data through the Arduino's serial monitor, neither serial monitor displays anything.

What I would like to do is be able to type in either serial monitor and have the data displayed in both serial monitors, like you would expect in a simple chat program.

Can someone see where I have gone wrong and/or how to get to the correct result?

Check out https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test
Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time.


Converting each digit in an integer to its respective ASCII characters For example what would be the process of converting the integer 1023 into ascii characters of

0x31 (1)
0x30 (0)
0x32 (2)
0x33 (3)

Not looking for any library functions (I know of Serial.print() and what not). I am trying to serially communicate an integer to the serial monitor, and I'd like to know what the process would be for an algorithm to take an integer and make each digit its corresponding ascii character

To convert a whole number to a char array in one go use the itoa function. That sounds like what you actually need.

To convert one digit from decimal to ascii just add '0', the ascii value for a 0. If you just want to try to understand what's going on, it's something like this.

char result[4] = {0};
int num = 345;

int digit = num % 10;  // get the 5 off the end
result[2] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 5
digit = num % 10;   // get the 4 off the end
result[1] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 4
digit = num % 10;   // get the 3 off the end
result[0] = digit + '0';  // convert to ascii and store

Serial.print(result);  // prints "345"


Which arduino should i use for a very simple one pin "blinking led" type project? I want to simply switch a relay like Majenko describes it for my last question. (time based switching of a relay)

That's the code I came up with based on the documentation:

int relayPin = 2; // pin where relay is attached
long mins = 5L;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    digitalWrite(relayPin, HIGH);
    delay(mins * 60L * 1000L);
    digitalWrite(relayPin, LOW);
    delay(mins * 60L * 1000L);
}

Now I want to use a real device and have been looking around, but there are tons of different boards, so some shopping advice would be really great. What I would like if possible:

Closed casing to reduce risk of people touching stuff. (also for a "professional" look)
Built in power supply from 220V AC.
Outputs strong enough to work without external logic, just connect the relay and go.
Small size and low cost, in case I start using these everywhere in the house i don't need to reevaluate. :)

For beginners, use an Arduino Uno. It is ready to use and quite expendable with shields. They have the USB to SERIAL chip on the board. Only week point is that it is sometimes large from space sensitive projects.

For more advanced users, I would suggest the Pro Mini (my personnal favorite). It is small, powerful and even has more pins then the UNO. The main disadvantage is that it requires an FTDI connector for the USB to SERIAL. Note that this NOT recommended if you use a lot of I2C.

Finaly, there is the overkill option. Only use this if you are considering to get one Arduino to rule them all!. It's the Arduino Mega 2560. It is the overkill of the overkill. So many GPIOs and ANALOG inputs. It is also unique for its core which is different the then normal ATmega328.

Then finaly there is the most easy to use one, the Red Board by Sparkfun. It combines the best of each Arduino in one. Note that this one is not manifactured and backed by Arduino.

That is pretty much a summary of all of the most popular types of Arduino that there is.

[EDIT]

Note that none of them has an included case and a circuit that can reduce 220V to 5V. If you really want a case, get an UNO. There are many cases for it. For transforming 220V to 5V, use an 5V wallplug. If you have something like a 12V wallplug, you can also connect it to the Arduino but you have to make sure you connect it to the Vin port.


Interrupt not firing on motion I'm trying to get MMA8452Q to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.

So I setup CTRL_REG4 to 0x0B with

void MMA8452Q::setupISR()
{
    writeRegister(CTRL_REG4, 0x0B);
}

then I setup FF_MT with

void MMA8452Q::setupFF_MT()
{
    writeRegister(FF_MT_CFG, 0xF8);
    writeRegister(FF_MT_THS, 0x0F);
    writeRegister(FF_MT_COUNT, 0x00);
}

and I read ISR with

#define SRC_PULSE 2
#define SRC_FF_MT 1

byte MMA8452Q::readISR()
{
    byte intStat = readRegister(INT_SOURCE);

    if (intStat & 0x0B)
    {
        readRegister(FF_MT_SRC);
        return intStat & 0x0B;
    }
    else
        return 0;
}

void printISR()
{
  byte isr = (accel.readISR() >> 2);
  if (isr & SRC_PULSE)
    Serial.print("(ISR) Tap");
  else
    Serial.print("(ISR) No Tap");

  Serial.print("\t");

  if (isr & SRC_FF_MT)
    Serial.print("(ISR) Motion");
  else
    Serial.print("(ISR) No Motion");

  Serial.print("\t");
}

AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in FF_MT_SRC, I'm not picking up an interrupt in INT_SOURCE.

Interrupts are fired on (most) taps, but not on motion at all.

Am I missing something here?

Thanks

Here's an extract from page 39 of MMA8452Q-rev8.1.pdf, the MMA8452 spec sheet:

Rather than saying writeRegister(CTRL_REG4, 0x0B); in MMA8452Q::setupISR(), try writeRegister(CTRL_REG4, 0xD);.

0xB is 1011 in binary, while 0xD is 1101, which turns on INT_EN_FF_MT to enable freefall/motion interrupts.

The above should answer your question as asked.  The following expands on my earlier comment which said

  Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.

"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.

"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.

If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the AttachInterrupt page at arduino.cc.  Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.


Send data string from Arduino UNO to ESP8266-01 Is there anyway to send a string from an Arduino UNO to a ESP8266-01 (one with only 8 pins RX, TX, CH-PD, vcc, ground, reset, GPIO0, GPIO2) without using without using AT commands.  I've looked everywhere and from what I can see UART doesn't work and SoftwareSerial uses only AT commands.  I am at my wits end.  Can anyone help here? please.
I have tried Serial.write but only writes String and Esp8266 only receives ints.

I found some code I thought might work but so far I can see that the arduino is sending <100.00:200:00>, but on the esp8266 all I get is four backwards question marks

this is the code on the Arduino UNO

#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // TX | RX
 float water = 100.00;
 float battery = 200.00;
void setup()
{
    Serial.begin(9600);     // communication with the host computer
    //while (!Serial)   { ; }

    // Start the software serial for communication with the ESP8266
    ESPserial.begin(57600);

}

void loop()
{
   ESPserial.print("<");
          ESPserial.print(water,2);
          ESPserial.print(":");
          ESPserial.print(battery,2);
      ESPserial.print(">");
      Serial.print("<");
          Serial.print(water,2);
         Serial.print(":");
          Serial.print(battery,2);
      Serial.print(">");
     delay(10000);
}

and here is the code on the ESP8266

#include <SoftwareSerial.h>
#include <string.h>

SoftwareSerial ESPSerial(2,0);

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

String water;
String battery;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  ESPSerial.begin(57600);
  delay(10);

}

void loop() {
  // put your main code here, to run repeatedly:
  recvWithStartEndMarkers();
  showNewData();

 water= getValue(receivedChars, ':', 0);
  battery = getValue(receivedChars, ':', 1);
Serial.println(water);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (ESPSerial.available() > 0 && newData == false) {
        rc = ESPSerial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }

The Arduino sends writes every 10 seconds and the esp prints the ???? every 10 seconds but with a lag.

I am not sure what the pin out to pin in should be.  Right now I have the Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2.

Can someone look at my code and see what I am doing wrong.  I thought I would send over two values because eventually I want to show water level and battery level.

Sending data between Arduino and NodeMcu (Serial Communication)
youtube link  (in French):
https://youtu.be/0TXmi9EgaCs


Connecting an Arduino to a servo with an external power supply I have purchased an MG995 servo (4.8-7.2V operating voltage, 170MA no load operating current draw) and will power this using a 5V, 2A mains plug pack. Do I need a breadboard to connect this with my Arduino (which will itself be powered through its usb port)? Or is it possible to connect the servo with the Arduino directly?

If it's possible to connect it directly, which pins should I be using on the Arduino? Will it look something like this:

except the red wire (and black wire?) connects to the external power supply?

Any answers (or links to relevant tutorials which have all three of these components) would be welcome. Thanks!

Your question is not very concise, but I'll try to hit the main points.

I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of <800mA (heat management on the Redboard probably lowers this number even more), as per the LM1117 voltage regulator listed in the provided RedBoard schematic, and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.

Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.

To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out Adafruit's servo tutorial. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs >= 7v.


Running light, without delay, and a potentiometer I am just getting hands on to my Arduino Uno.

I am have finished the blinking light tutorial, managed to read a potentiometer, build a running light with delays and as well a binary counter.

Now I build a small project with 5 LEDs and a potentiometer to configure a running light and change the speed of the running light with the potentiometer.

The LEDs are connected to the pins 13 to 9 and the potentiometer is connected A0 and 5V.

I also managed to program it without a delay function, but I think it is rather ugly.

Is there a better way of doing this like I did it?

int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
//the delay
int pause = 1500;
//count to decide which LEDs are HIGH and which are LOW
int count = 0;
// will store last time LED was updated
unsigned long previousMillis = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

  unsigned long currentMillis = millis();

  // read the input on analog pin 0:
  pause = analogRead(A0);
  float voltage = pause * (5.0 / 1023.0);

  // print out the value and teh corresponding voltage you read:
  //Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(pause);
  Serial.print("Volts: ");
  Serial.println(voltage);

  if (currentMillis - previousMillis >= pause) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    if (count == 0) {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
    }
    else if (count == 1){
      digitalWrite(led2, HIGH);
    }
    else if (count == 2) {
      digitalWrite(led1, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 3) {
      digitalWrite(led2, LOW);
      digitalWrite(led4, HIGH);
    }
    else if (count == 4) {
      digitalWrite(led3, LOW);
      digitalWrite(led5, HIGH);
    }
    else if (count == 5) {
      digitalWrite(led4, LOW);
    }
    else if (count == 6) {
      digitalWrite(led4, HIGH);
    }
    else if (count == 7) {
      digitalWrite(led5, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 8) {
      digitalWrite(led4, LOW);
      digitalWrite(led2, HIGH);
    }
    else if (count == 9) {
      digitalWrite(led3, LOW);
      digitalWrite(led1, HIGH);
    }
    else if (count == 10) {
      digitalWrite(led2, LOW);
      digitalWrite(led1, HIGH);
      count = -1;
    }
    count++;
  }
}

Your Serial.print()s will print on every iteration of loop() even if that iteration doesn't operate on the LEDs. You'll be swamped with output on the terminal.

One improvement I'd make would be to get rid of the counter and the if/else if/.../else if segment. Rotate a bit through a byte variable for as many bit-positions as you have LEDs. Then call a function with that byte, that will set each LED on or off according to the state of its respective bit.

One more improvement can be had if you rotate the bits through bit positions 1 to 5 (in this case) of your byte variable, because you made the fortunate or perhaps intentional assignment of LED's to digital I/Os that are adjacent bits in PORT-B! One single PORTB = [your byte]; statement could set all 5 LEDS simultaneously.

Update:
PORTB is a register in the UNO's Atmega328p MCU, one of three (PORTB, PORTC, and PORTD) that connect to all of the I/Os on the UNO (or any other '328 based MCU board). By setting the (up to) 8 bits in one port, a single assembly-language instruction can set that many I/Os simultaneously. It is incredibly efficient. The downside of doing that instead of calling digitalWrite() is that the sketch is then tailored to that particular processor. digitalWrite() uses more program memory and execution time (by a lot, especially when setting multiple I/Os), but keeps your sketch processor independent; digitalWrite() knows which processor it was compiled for and how to translate a Digital I/O number to a physical external pin on that processor, so you don't have to.

For those interested in the low level details of the hardware, they are in the processor's datasheet.


Sending and receiving different types of data via I2C in Arduino I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

#include <Wire.h>

const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600);  // start serial for output
}  // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
 Serial.print('\n');
   Serial.print(table[0]);
    Serial.print('\t');
   Serial.print(table[1]);
    Serial.print('\t');
   Serial.print(table[2]);
   Serial.print('\n');

delay (500);

// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}

here is the code for the slave

#include <Wire.h>
int table[]={0,0,0};
int Work=0;

void setup() {
Wire.begin(8);                // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}

void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
  table[0]=x;
  table[1]=y;
  table[2]=z;
}

void requestEvent()
{
  uint8_t Buffer[3];
  Buffer[0]=table[0];
  Buffer[1]=table[1];
  Buffer[2]=table[2];
  Wire.write(Buffer,3);
}

void receiveEvent(int howMany)
{Work = Wire.read();}

I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.

After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0

The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.

Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.

//master
#include <Wire.h>

char t[10]={};//empty array where to put the numbers comming from the slave
volatile int Val; // varaible used by the master to sent data to the slave

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

//gathers data comming from slave
int i=0; //counter for each bite as it arrives
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i=i+1;
  }

Serial.println(t);   //shows the data in the array t
delay(500); //give some time to relax

// send data to slave. here I am just sending the number 2
  Val=2;
  Wire.beginTransmission (8);
  Wire.write (Val);
  Wire.endTransmission ();
}

here the other part
    //slave

#include <Wire.h>

char t[10]; //empty array where to put the numbers going to the master
volatile int Val; // variable used by the master to sent data to the slave

void setup() {
  Wire.begin(8);                // Slave id #8
  Wire.onRequest(requestEvent); // fucntion to run when asking for data
  Wire.onReceive(receiveEvent); // what to do when receiving data
  Serial.begin(9600);  // serial for displaying data on your screen
}

void loop() {
  int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
  float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

  dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  Serial.println(Val);         // print the character
 delay(500);
}

// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}


Expected Unqualified-ID Before 'do'(and 'while') I am getting the error "error: expected unqualified-id before 'do'" multiple times for every do{
}while(); loop I have... Any help?

Pastebin:http://pastebin.com/DubuAEUs

The do whiles are outside of the setup() or loop(), so they won't work.

I would suggest doing a simple C/C++ tutorial like this one to get up to speed with how things work.


DC Motor Car Steering I am working on a project with a 3-Wheel Car: 1 Custer Wheel, and 2 DC Motors. I need to steer the car playing with the speeds of these two dc motors. If I would supply a constant voltage and current to the DC motors, is there an equation or maybe a source to know the exact degree of turning by assigning PWM to a certain value? Let's say I want to turn the car 30 Degrees to the left from the straight direction. Can I do calculations to find all of the PWM values or it can only be got through experiments?
Thanks in Advance!

Basically you can't. PWM value required to turn to a specific degree will depend on motors, on voltage, on hardware, in the current velocity of the car and probably on the surface under the wheel. Also keep in mind that real cars don't turn like that (at a fixed angle). Instead, driver constantly adjusts the position of the steering wheel, while looking at the road (i.e.a feedback system). Same is for RC cars, operator smoothly deflects the joystick looking at the vehicle.


Function to control servos I'm trying to control 6 servos while writing a lean code. I think the function call isn't correctly yet and I think that the variables (pos_n, open_n, servo_1) in the for loop do not get inserted, but instead the string just gets inserted.

I think I have come a long way to not make this a bulky code.

What changes makes this function working, so that the call openValve(1) and openValve(2); work for both servos?

#include <Servo.h>
const int buttonPin = 2;
int buttonState = 0;

Servo servo_1;
const int pos_1 = 0;
const int open_1 = 105;
const int clos_1 = 10;
//Servo servo_2;
//const int pos_2 = 0;
//const int open_2 = 104;
//const int clos_2 = 9;

String servo_n, pos, pos_n, servo, openServo, open_n;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  servo_1.attach(11);
}

void loop() {
  openValve(1); // call the function
  while (true);
}

void openValve(n) {
  int n = 3;
  pos = "pos_";
  pos_n = (pos + n);
  Serial.println(pos_n);

  servo = "servo_";
  servo_n = servo + n;
  Serial.println(servo_n);

  openServo = "open_";
  open_n = openServo + n;
  Serial.println(open_n);

  // DONT USE STRING BUT THE VARIABLE CONTENTS ??
  for (pos_n = pos_n; pos_n <= open_n; pos_n += 1) {
    servo_n.write(open_n);
    delay(10);
  }
}

I think you are totally misunderstanding, about variables and types and how using multiple servos with 1 function can work, and that this is your real question and not the thing with inserting variables (whatever you mean by that).

You are trying to put together a string and use it as variable name. That does not work. A string is only a variable/instance of type/class String. It cannot have methods of the Servo class. Also function parameters each have their own type. You cannot provide a value of a different type to this parameter. Servo.write() takes an integer value. It cannot use a String value. Thus the code inside the for loop is nonsense and won't compile. I would suggest doing some C++ tutorials from the web, that explain, how variables work in C++.

Instead you have to use multiple variables of the type Servo, one for each servo motor, that you are using. These variables are instances of the Servo class, which implements all the servo related functions (like write) Each motor gets it's own pin on the Arduino. You can put these Servo objects into an array, so that they can be indexed by an integer number. For example you can define the following variable in the global scope:

#define N_SERVOS 6
Servo servos[N_SERVOS];

This creates an array of type Servo with 6 elements. Each element is one independent servo object. (Note, that I used a define to easily change the number of attached servos when changing the code). You can reach an individual servo object by indexing it:

servos[3].write(pos);

This would write a new position to servo 4 (4 because array indices are starting from 0). Now we need to attach each Servo object to one pin of the Arduino. I would create an extra array, which contains the corresponding pin numbers - also at global scope:

int servo_pin[N_SERVOS] = {6, 7, 8, 9, 10, 11};

Here I used pins 6 to 11, but you can change them, as you like. Then in the setup() function we loop over our servo elements and corresponding pin numbers and attach the servo objects to the pins:

for(int i=0;i<N_SERVOS;i++){
    servo[i].attach(servo_pin[i]);
}

And now you can rewrite your openValve() function corresponding to that. I don't understand, what you wanted the servo to do in the for loop, so I will leave this to you. First you need to correct the syntax at the function declaration. You didn't specify the type of the parameter n. It has to look like:

void openValve(int n){

And then you shouldn't declare a new variable with the same name, so delete the line int n=3;. Then you can delete all the weird string concatiation. Then you need to fix the for loop (as I wrote I will leave that to you, since you didn't explain, what the servo should actually do there). And finally you need to rewrite the servo write line like described above:

servo[n].write(new_pos);

Note, that new_pos is just a placeholder here, for whatever values you need to write to the servo (as already said, I don't understand, what exactly you want the servo to do).

  what I then should use instead of the String object?

The String class from the Arduino framework can get you into memory trouble (to be exactly memory fragmentation). You can read Majenko's blog post about Arduino Strings for further explanations.

Instead you should use char arrays aka C-Strings. You create a buffer with a fixed length, that is big enough to hold the biggest chunk of data, that you need to process. Let's say you need at max 30 characters. Every C-String is terminated by a zero ('\0'). This zero also needs space in the buffer. So the actual buffer size is 31.

char string_buffer[31];

You can even directly initialize it with a string value:

char string_buffer[31]="Teststring";

You can use sprintf() to put a formatted string into the buffer. For example a string with a number:

sprintf(string_buffer, "Number: %d", 50);

will put the string "Number: 50" to the buffer and will terminate it with a zero.


Analog inputs showing value even there is nothing connected to it After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.

the code is

float ana [] = {A0,A1,A2,A3,A4,A5};
float dec [6];

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

void loop()
{
  for(int i = 0; i<6 ; i++)
  {
    dec[i] = analogRead(ana[i]);
    Serial.println(dec[i]);
    delay(1000);
  }
}

How is this even possible?

this is the output result

Your input is floating if nothing is connected.  It is reading whatever random noise it happens to pick up.  That's what it is supposed to do.  For it to read 0 it would need to be connected to ground.  Google "floating input" for more info.


The right way to find and understand the libraries I am working on a project to send sensor values from esp8266's Wemos D1 mini to MySQL.
I tried using the library MySQLconnection.h but I couldn't make it to connect to wifi. So I uploaded a simple program to connect the board to WiFi using ESP8266.h but I got the error that Unable to compile for Wemos D1 board.

Please tell me the right procedure to select the right library for the problem defined.

You should break your problem down into simple parts, which it seems you are on-track to do. Your ultimate goal appears to break down into the following sub-tasks (not in order):

Read sensor value
Connect to a WiFi network
Connect to a MySQL server
Send sensor data to MySQL database

You are unlikely to find a single library to do all of these tasks, but as progress in solving each step, any library that works is the "Right" one, in general. Choose a library that solves an individual task.

You say you tried to upload a simple program to only connect to WiFi, but that it did not compile. The clue to why it did not compile will be found in the actual compile error message. If you can update your question with the error message and the code to the simple program, you can get some guidance from the users of this site to solve that problem.


How do I write the codes in #define in an IR Receiver circuit? So I'm trying to turn an ON LED OFF or an OFF LED ON using a TV Remote. In the #define line, I write the hex code received from pressing the designated button on the TV remote. However, during compilation, an error saying unable to find numeric literal operator 'operator""DE74847' appears. I've scoured the web and can't come up with a solution.

#include <IRremote.h>
#include <IRremoteInt.h>
int ledPin = 13;
int IRPin = 3;

#define code1 0575

IRrecv irrecv(IRPin);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(ledPin, OUTPUT);
}
void loop()
{
  if (irrecv.decode(&results))
  {
  unsigned int value = results.value;
  int ledState  = digitalRead(ledPin);
  switch(value)
  {
    case code1:
    if (ledState = HIGH)
    {
      digitalWrite(ledPin, LOW);
    }
    else
    {
      digitalWrite(ledPin, HIGH);
    }
    break;
  }
  }
  else
  {
    digitalWrite (ledPin, LOW);
  }
   unsigned int value = results.value;
  Serial.println(value);
    irrecv.resume();
}

Here's the code. Please help.

Your problem is that you don't know how to form hexadecimal numbers.

In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:

#define code1 DE74847

So in your switch construct, when code1 gets replaced with the content of the macro, you end up with:

switch (value) {
    case DE74847:
        ....

The compiler has no idea what a DE74847 is.

Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

0b... is binary
0 is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
0x is hexadecimal.

So adding 0x to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:

#define code1 0xDE74847


Need help rewriting a program I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.

int motorPin = A0;
int blinkPin = 13;

int watertime = 300000; // how long to water in miliseconds
int waittime = 3600000; // how long to wait between watering

void setup() {
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    delay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    delay(waittime);
}

Changed int to:

#define watertime 300000
#define waittime 3600000

But it does not work.

Use the long type instead

long watertime = 300000; // how long to water in miliseconds
long waittime = 3600000; // how long to wait between watering


Arduino Robot Chasis I am looking into building a robot with my Arduino Nano but I don't want to shell out more then 50 bucks. Does anyone have any suggestions for a four wheel robot chassis at this price that I could use to make my robot mobile?

There's plenty of options on ebay, you will have to add a DC motor driver and optionally, sensors, but these are a good starting point.


NRF24L01 Direct Communication Library Logics Actually I'm using the RF24 Library mantained by TMRh20 (https://github.com/TMRh20/RF24).
I'm trying to get some type of direct communication between multiple modules working, but I don't want to use the RF24Network Library (https://github.com/TMRh20/RF24Network) which creates a mesh of connections.

I currently have several arduinos that have to communicate between them. Every arduino has its own address starting from 0x0001 (0x0000 is for a main module that manages everything) and finishing to 0xFFFF.
I want to directly communicate between the two NRF24L01+ modules without any intermediator, because I don't have problems of distance.

The main thing that I want to be able to do is communicate directly not with just one module, but choose if I want to broadcast to all the modules in an area (I know that it can be done with range power modifications in the code) or talk with just one module.

What is the best way to do this type of communication?

Both of the Libraries you mentioned are well written. I've used both, but decided to write my own based those libraries. For me, the network libraries were written for their project and didn't really fit my needs. So I decided to write my own. I combed the internet for a bare bones NRF24 Library and found this one. This was my starting point. It didn't need the Arduino Core Library and handled all the SPI functions. Then I read the NRF24L01 datasheet several times, then read it again.

With that said, you can broadcast up to 6 radios at a time. Per the datasheet, the receiver knows which radio sent the packet. The STATUS register (0x07), should tell you who sent the packet:

I was unable to get this working (I am still working on it), so for now, I send my packet as a struct:

typedef struct  {

uint8_t id;
uint32_t data;

}
Packet;

Packet pck;
pck.id = 2; // id of my second radio

Keep in mind when you program your Arduino as the receiver, you have to tell it who it will be receiving from. The transmitter and receiver have to be on the same RF channel, speed and same pipe. To choose who receives the packet may not work the way you think, but as I mentioned you can program the receiver to know who the transmitter was and code around it.

I would suggest you dig into the datasheet.


What do symbols like UCSR0C, UMSEL01, etc. means? I have a code with a connection to serial port:

// Set baud rate
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?

Take a look in the datasheet under the "20. USART0" section:

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

I will list the names of the registers, what they are called, and then what your code is doing specifically:

UBRR0H and UBRR0L together form the baud rate divider.  Your program probably uses F_CPU and <util/setbaud.h> to calculate a divider and set the baud rate.  For more information see Table 20-12.
UCSR0A  "USART Control and Status Register n A"  --  This line is enabling the U2X0 which doubles the transmission speed
UCSR0C  "USART Control and Status Register n C" --  This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity".  See Table 20-9.  This line has extra information, all the statements with 0<< actually do nothing.
USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in
a frame the Receiver and Transmitter use. "  This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
The final USCR0B line enables tx and rx


Use UTP Cable to transmit/receive data? I was wondering if it was possible to use the utp port of a computer/laptop to transmit and receive data to an external device?

If you take a cat5 cable there are 8 wires, so lets say you have an Arduino would it be possible to use those wires for serial communication? If so how can I program the utp port? And is there a specification for this (for example use wire x for output and wire y for input..)

Thanks in advance,
Regards

Ps: I had no idea on which sub.stackexchange to ask it hopefully it suits here.

By "UTP", I'm assuming you're referring to Unshielded Twisted Pair. The shielding and twisting aren't really relevant, because they're just physical characteristics of the cable itself. They don't have any bearing on the sender or receiver.

The salient point about UTP is that it uses differential transmission. That is, the data is sent down two wires at the same time, but one is inverted. The receiver uses the difference between the two signals to reconstruct the original data, eliminating any interference which may have been introduced en route.

Assuming the voltage level is safe (0-5v for most boards), you could connect each wire directly to an analog pin on the Arduino. If you read both continuously, and apply suitable thresholds/triggers in software to identify level changes, you could probably reconstruct the original signal.

It's definitely not ideal though, as ADCs are comparatively slow, and you would never be able to read both at exactly the same time. That means the transmission would have to be quite slow in order to work. The exact speed would depend on how quickly your program could poll the ADCs and process the result.

It would be much better to use some external circuitry to handle the differential signal. It could then produce a nice clean digital output which you could feed directly to any input on the Arduino. It should be able to run a lot faster, and leave your program free to do other things. Any good electronics vendor will stock a variety of ICs which would do the job, depending on your exact requirements.

Setting up your computer/laptop as a sender is a totally separate issue though. Many different ports use differential signals in some form, including ethernet, USB, and RS-232 (old DE-9 serial ports). Unfortunately, it would be very difficult to get direct control of their signal lines. You would almost certainly have to write your own device drivers, which is a pretty huge undertaking.

If you want to send serial data from your computer to an Arduino, the easiest way is just USB-to-TTL conversion. Most Arduino boards have this built-in, connected directly to the hardware serial lines on the microcontroller (which is how you upload programs/sketches). Alternatively, you can get external cables which do the conversion, and you can connect it manually to other pins, processing it using software serial.


Efficiency of a cast vs a shift I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:

 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 3)>>1);
 digitalWrite(_S2, (chan & 7)>>2);
 digitalWrite(_S3, (chan & 15)>>3);

Those masks seem a little odd, but it would work. More natural to me would be:

 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 2)>>1);
 digitalWrite(_S2, (chan & 4)>>2);
 digitalWrite(_S3, (chan & 8)>>3);

But overall, would it be more efficient to do this?

 digitalWrite(_S0,       (chan & 1));
 digitalWrite(_S1, (bool)(chan & 2));
 digitalWrite(_S2, (bool)(chan & 4));
 digitalWrite(_S3, (bool)(chan & 8));

...or is shifting already pretty efficient?

I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.

I tried compiling your three snippets with avr-gcc 4.9.2 at the -Os
optimization level (standard with Arduino) but without -flto. The
results were:

The first snippet generated inefficient code: the ands and shifts were
translated in assembly quite literally, the shifts were done on
16 bits even though chan was declared uint8_t, and the last
shift was even implemented as a loop roughly equivalent to
uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;
The second and third snippets were translated identically and
efficiently, using the bst (bit store) and bld (bit load)
instructions to copy the relevant bit of chan into the second
argument of the digitalWrite() call.

Personally I would just write

digitalWrite(_S0, chan & 1);
digitalWrite(_S1, chan & 2);
digitalWrite(_S2, chan & 4);
digitalWrite(_S3, chan & 8);

as digitalWrite() expects an integer as its second argument, and it
interprets it just like the (bool) cast does. If you want to be sure
to always call digitalWrite() with either 0 (LOW) or 1 (HIGH),
then use either your second of third form. The first form seems formally
equivalent to the second, but since it is not an usual C idiom, the
compiler could not catch the optimization opportunity.


Multiple if statement conditions I would like to make this code using the Arduino Uno. I am using three on/off switches and based on the truth table would like to turn on one of 8 LEDs. When I use digitalWrite(), I get an error code saying that there are too few arguments.

Here is the code

int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
}

void loop() {

  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
    digitalWrite (ledPin1 = HIGH);
    digitalWrite (ledPin2 = LOW);
    digitalWrite (ledPin3 = LOW);
    digitalWrite (ledPin4 = LOW);
    digitalWrite (ledPin5 = LOW);
    digitalWrite (ledPin6 = LOW);
    digitalWrite (ledPin7 = LOW);
    digitalWrite (ledPin8 = LOW);
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
    ledPin1 = LOW;
    ledPin2 = HIGH;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = HIGH;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = HIGH;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = HIGH;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = HIGH;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = HIGH;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = HIGH;
  }
}

digitalWrite (ledPin1 = HIGH); should be digitalWrite (ledPin1, HIGH);

PS if ( (x = LOW) && (y = LOW) && (z = LOW)) should be if ( (x == LOW) && (y == LOW) && (z == LOW)). = is for assignment, == is for comparison.


Why Arduino Mega 2560 throw error when i try to upload example I'm try to connect my Arduino Mega 2560 to PC, but I think it's not easy as I imagine. I spent a lot's of time to install USB driver. Here is a screenshot:

When I try to upload blink example, Arduino IDE throw this error:

Sketch uses 656 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM10"
avrdude: ser_drain(): read error: The handle is invalid."

Please help to run one simple example.

I think this screen may help to understand my problem:

I install driver for this site and everything is working well.
driver download:  wch.cn/download/CH341SER_EXE.html

I'm recommend to unplug arduino first and install driver, after that plug and enjoy.

Here is a video:
https://www.youtube.com/watch?v=FhmG5J-AHrg


What is the relationship of an Arduino .ino file to main.cpp? Is the .ino file an alternative from a main.cpp file?

If yes, then could someone mind explaining the structure of the .ino file in main.cpp and its relationship?

The Arduino uses the gcc compiler. That compiler wants a normal main function of course. Arduino has put a layer on top of that with setup and loop.

The hidden main function for basic Arduino boards is in main.cpp (click on it to see it).
You see that init is called, and setup and loop and a few other things.

To learn how to use setup and loop, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.

The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.

When you know how to use setup and loop, try the Blink Without Delay example. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.