text:
Is it possible to digitally stop a moving motorbike using an Arduino module?
I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.
Is it possible to do it using an Arduino and some other modules maybe?

Put a (NC-)relay in series with the ignition cable. That way you can "remove the key" using the Arduino.

with autos in general, it might be illegal to stop it if its moving, as that could cause a wreck and expose you to injury liability. its best to keep it from being started, or kill it when idle.

Legality might not be an issue here as this is just a throwaway project I have to do for internals.I am not really aiming to make this a commercial product.

Make an actuator poke a stick through the wheel, this often is very (or too) effective. (:

Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.
Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.
Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.

starting an engine can draw 50 amps, make sure the relay can handle that much current (most cannot)

If the motorbike has a starter motor, I hope it's on a relay of its own.

If you try to use the brakes with the Arduino, make sure you do it gently; an abrupt break (especially on the front wheel) might cause lethal injuries.


text:
3 buttons digital inputs
I have 3 digital button inputs, I want to do a continuous scan of 3 of them until a button is pressed and to know which button has been pressed. Please help, I'm new to programming and arduino.
Thanks

Try out this code. You can see result on Serial Monitor. I hope it will help you.
const int kPinBtn1 = 2;  // Button 1
const int kPinBtn2 = 3;  // Button 2
const int kPinBtn3 = 4;  // Button 3

void setup()
{
  pinMode(kPinBtn1, INPUT); // Button 1 as Input
  pinMode(kPinBtn2, INPUT); // Button 2 as Input
  pinMode(kPinBtn3, INPUT); // Button 3 as Input

  digitalWrite(kPinBtn1, HIGH); // Pullup
  digitalWrite(kPinBtn2, HIGH); // Pullup
  digitalWrite(kPinBtn3, HIGH); // Pullup

  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(kPinBtn1) == LOW)      // If button 1 pressed
  {
    Serial.println("Button 1 pressed"); // Print "Button 1 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn2) == LOW)      // If button 2 pressed
  {
    Serial.println("Button 2 pressed"); // Print "Button 2 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn3) == LOW)      // If button 3 pressed
  {
    Serial.println("Button 3 pressed"); // Print "Button 3 pressed" on Serial Monitor
  }
}

Usually you would take advantage of a pin change interrupt and only then read the state of all buttons. This solution will pollute the Serial Monitor while a button is being kept pressed. But it fulfils the requirements of C. Dave. I'm not sure if he exactly knows which direction he is heading.

@C.Dave - I guess since you are new to programming Kwasmich kept it simple.  Once you have that working you could research arrays (in C or C++) and you'll find that you can half the amount of code.

@C.Dave Glad to know.

source: Stack Exchange

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

sort: votes


text:
Input-Output Circuit Issue
I have design a circuit with 2 led (red and UV) and 2 button.So, the circuit supposed to work like this:
If i press the button for red led, the red led lights up and the uv led turn off, and if i press the button for uv led the uv led lights up and the red led turn off.

But the circuit is not work like that, when i upload the code, the uv led suddenly turn on without touching the button.The red led had no issue.The red led turn on when the button is push.And turn off when the button is unpress.But when i push the red button, the uv led does not turn off.It stay glow.The uv led turn on whatever i push the button or not.
Here is the code :
int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT);
  pinMode (uvbutton, INPUT);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == HIGH)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == HIGH);
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}

Your Schematic seem to be wrong. Let me do correct it.

Are your buttons definitely plugged into pins 2 and 3? The schematic and the code look correct, but the picture looks like there is they're not plugged into neighbouring pins - it looks like there is a gap between them, but it is very hard to tell conclusively.

Try out this schematic. It will work.

So code will be :
int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT_PULLUP);
  pinMode (uvbutton, INPUT_PULLUP);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == LOW)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == LOW)
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}

To make that work need to change pinMode (redbutton, INPUT);
pinMode (uvbutton, INPUT); to pinMode (redbutton, INPUT_PULLUP);
pinMode (uvbutton, INPUT_PULLUP); and invert the logic in if's

@jwpat7 Yeap, you're right.

But im using a pull up resistor on the button.So, i didnt need INPUT_PULLUP right?I think my schematic and my code are wrong.Btw thanks for your help

@deadguy88 May be you're right. But it is better to apply pull up through program because why you use extra circuitry if that things happens through program. Usually, I prefer this things. Try out my code and schematic. It will definitely work.

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


text:
PulseIn tachometer
I tried to create a tachometer for my motorcycle using an Arduino Uno.
I am trying to measure the voltage of the ignition coil (stepped down to not destroy the Arduino).
I am trying to determine the time between two explosions (one ignition coil high voltage).
I tried to use the pulseIn command in the following way:
unsigned pin=8;
float t;

unsigned long rpm;

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

void loop() {

    rpm=pulseIn(pin,LOW);

    Serial.println(rpm/60);
}

The problem with it is that it won't display stable values. It will go all crazy.
With an open circuit it still displays random values.

Are you sure that pulse is not shorter than 10ms?

i tested both pulseIn(pin,LOW) and pulseIn(pin,high) and neither worked. At most, my bike does 14.000 rpm, meaning 14.000/60 (233) rps.
233 rps ..... 1000 ms
x rps............1 ms
x=233/1000.
I guess it is less than 10 ms.
Is that the problem?

https://www.arduino.cc/en/Reference/pulseIn - under 10ms it wont work right

but if you have tested it with smaller speed, the problem will be somewhere else

I am curious, how do you get to incorporate ignition coil into your circuit?

I suspect that it is already too late for that Arduino. How are you safely stepping the voltage down in such a way that it doesn't a) kill the Arduino, and b) kill you?

btw: http://arduino.stackexchange.com/questions/318/how-precise-is-the-timing-of-pulsein?rq=1

pulseIn works for values less than 10ms, it returns time in 'micro Seconds'. Try        Serial.println(pulseIn(pin,LOW));

I did not use the high voltage terminal. I took the minus from the coil primary minus (the 12v terminal) and the plus from the battery, since the ground is the one that continuously varies in an ignition coil. I used a voltage divider to step the voltage down to acceptable levels.

No one mentioned that there is back EMF from primary coil when switch (or points) becomes open. This means that there is 200-300V applied backwards to your voltage divider while you think there is only 0-12V.

I can't tell you why that isn't working, but I can give you a working alternative.
unsigned int pin=8;

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

void loop() {
    unsigned float rpm = 0;

    while (digitalRead(pin) == FALSE) {
        rpm++;
        delayMicroseconds(1);
    }

    Serial.println(rpm/60);
}

I might've forgotten something, but that should work.
Edit: the comments may be right, are you stepping down your input voltage?

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


text:
Correct connections: 7-segment, 4-digit display with common anode
I see this connections for 4-digit display.

All used pins set up on output. But, really, is it correct connections?
Why it used A* input pins, and, digital pins set up on output, it is right?
Maybe all pins need used by digital pins with NPN transistors? Collector is 5V, Base - Arduino digital pin, emitter - resistor with display anode, next, collector is display segment pin,  Base - Arduino digital pin, emitter - Ground.
What resistance is needed for the resistor? I think, more than 220 Ohm?
Sorry, but I'm really a beginner in electronics.

Where is the datasheet for the display?

http://imgur.com/a/SIB0s

Where is the rest of the datasheet for the display?

(5-1.8)/220=0.014amps is within the UNO's allowed consumption, so you're fine there. that said, i would invest in a max7219 to free up all those pins and make coding simpler with existing libraries.

That circuit looks OK to me.  It will allow you to light (reliably) a single segment at a time.  The A* pins will be used in digital output mode.
The A* pins are connected to the four anodes of the digits - each digit has common anodes for all the segments.  They should be driven HIGH to 'select' a digit.
The D* pints are connected to the cathodes of each segment.  They should be driven LOW to light that segment.
For example, to light the 'A' segment of the first digit, you would set:

A1 HIGH, to drive the anode of the first segment
A2, A3, A3 LOW, so that the other three segments are not driven
D5 LOW, so that current flows from A1 to D5, lighting the digit
D6-D12 HIGH so that no current flows from A1 through any of the other segments.

The expectation is that you will cycle around (very fast), lighting each required segment on each required digit in turn.
Without a (proper) data sheet we can't tell you what the correct resistor value is, but the 220R shown is probably OK.

Thank you. I was looking for a datasheet on the marking, but I can not find the full description.


text:
Is there a way to setup an interrupt to trigger at n number of clock cycles from now?
I currently have an nRF transmitter/receiver pair setup on my desk. The transmitter is sending a single byte (0xAA) every 5ms. The receiver sets an LED high to indicate that it received the byte, which is about 10us (+/-2) after the byte was sent. I want to use this nRF pulse for a precise timing/sync application with +/-0.5us accuracy so I need to filter these receiver pulses such that I can estimate the time the transmitter actually sent the byte and the time the next one should arrive. I created an algorithm that uses past nRF pulse times (measured in clock cycles using Teensy's ARM_DWT_CYCCNT register) to estimate the next pulse and it seems to be working reasonably well - though I can't say yet if I'll get the 0.5us accuracy I want.
Now I want to take that estimate and have my microcontroller set an output pin high as soon as the clock count reaches the estimated clock value. Currently I do this by waiting in a while loop and polling the register, but the loop itself takes up several hundred clock cycles which reduces my accuracy. Is there a way to instead have an interrupt trigger when the clock cycle counter reaches my estimated value? I would somehow need to set this interrupt after computing each estimate.
Thanks!

Output Compare sounds like your best bet. Set the Output Compare value to your timeout value, and start the timer running from 0 when you get your pulse. When the timer == the OC value the output turns on.

Where's your code?

Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.
Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.
Other approaches also exist but the two outlined here are easier.


text:
Arduino to Beaglebone black
I have an Arduino uno3 which gets data from a digital caliper and shows the data in serial monitor. Now I should make a connection between this Arduino and my Beaglebone black through SPI to get the data sent from caliper in Beaglebone black. and I don't know what to do and how to create codes related to this purpose.

Have a look at the first several links from googling for Arduino and my Beaglebone black through SPI.  Here are a few comments on those first few links:
• SPI - Beaglebone Black Master Arduino Uno Slave (forum.arduino.cc topic 446924.0) – This page asks your question in more detail, and includes Beaglebone master code and Arduino Slave code.  However, the poster makes an egregious error in the Arduino code by saying Serial.println("SPI"); within the SPI interrupt service routine.
• Communicate Beaglebone Black and Arduino via SPI
(ulasdikme.com) – This page addresses your question in rather more detail, and apparently shows working code.  It also explains how to enable SPI in the Beaglebone device tree.  Note, this poster too makes an egregious error in the Arduino code by saying Serial.println(c); within the SPI interrupt service routine.
• SPI communication: BeagleBone Black (as Master) to 4 Arduinos (as Slaves) (adurthi.com) – This page covers level shifting and device tree setup and provides ok code.  It seems to cover BeagleBone concerns nicely, and has ok Arduino code as well.
One or two of the above also make reference to Nick Gammon's excellent SPI pages:
• SPI - Serial Peripheral Interface - for Arduino (gammon.com.au forum id=10892) – This page is where you should start if you have questions about how SPI works.  After you are familiar with SPI basics, scroll down to the “How to make an SPI slave” heading, and set up the master-slave example with two Arduinos.  When you have that working, you can substitute or add a BeagleBone as master.  Other code examples further down the page include  “How to get a response from a slave”, slave SS pin interrupt examples, SPI via USART, speed settings, SPI on ATtinys, sending data structures, and (under the heading “SPI under IDE 1.6.0 and later”), exegesis of SPI library methods.
• Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329) – This page illustrates master-slave communication between two Arduinos, using one as a slave to forward information sent from a system being debugged.  Also illustrates use of I2C for similar purpose.  Note, Debugging The Arduino With The SPI Interface Instead Of Serial.println() (utopiamechanicus.com) is a follow-on article, by another author, about this debugging technique.


text:
From Exploring Arduino Text
I am working thru the Exploring Arduino text mostly with success up until chapter 4. I have most of the parts required but for Figure 4-3 I used the following:
100nF Capacitor, (In place of 1uF Capacitor)
1N4007 Diode Rectifier, (In place of 1N4004 Diode)
S8050 NPN Transistor, (In place of PN2222 NPN)
DC Motor rated for 3V with a Reference Current of 0.35 to .4 Amps (Text lists "DC Motor")
Im aware that the Capacitor was undersized, Diode was a 4 series (so I assumed it was compatible), and the Transistor also the same but of a different manufacturer. Im also aware that the motor is underrated compared to the 9v input, but I didnt think this would cause a problem for a small time period.
My problem is that after about 10 seconds of running (both with the motor free spinning as intended, and sometimes just staying put but making a high pitched noise) the bread board started smoking. So, I disconnected everything and gave up for the day.
What was it that caused the breadboard to start smoking? Do you think I damaged my Arduino?
Link to companion site with diagrams: http://www.exploringarduino.com/content/ch4/

the parts sound fine, you probably hooked something up wrong. i've never seen smoke from something that continued to work perfectly after. if you gave a 3v motor 9v, then anything in it's path is probably damaged; the lower-voltage motor drew several extra watts over design.

Thanks for the reply, im pretty confident that I wired it correctly, i guess i can give it another try. Should i replace the motor with a higher rated one?

If you used the 9 V battery as described in the diagram, but with a 3 V rated motor, then the motor starts smoking and you might damage it. Use e.g. 2 AA batteries with 1.5 V instead of the 9 V battery, then it should work without smoke and your motor will survive much longer.


text:
ColorPal Sensor
First off let me preface this my explaining my background. I am a mechanical engineering student and have some programming knowledge but it's limited. I'm trying to make a skittle sorter and I right now I'm working on the color identification part. I bought a ColorPal sensor for the project but I'm having trouble using it. I modified the demo a bit and it sort of works but not as well as I would like. Can someone please help me with my code or perhaps suggest an easier color sensor to use. Also I hope I paste my code correctly.
#include <SoftwareSerial.h>

#define sio      6           // ColorPAL connected to pin 6
#define unused   255         // Non-existant pin # for SoftwareSerial
#define sioBaud  4800

// Received RGB values from ColorPAL
int red;
int grn;
int blu;

// Set up two software serials on the same pin.
SoftwareSerial serin(sio, unused);
SoftwareSerial serout(unused, sio);

void setup() {

  delay(2000);

  Serial.begin(9600);
  reset();                    // Send reset to ColorPal
  serout.begin(sioBaud);
  pinMode(sio, OUTPUT);
  serout.print("=(00 $ m)!"); // Loop print values, see ColorPAL documentation
  serout.end();               // Discontinue serial port for transmitting
  pinMode(sio, INPUT);
  serin.begin(sioBaud);       // Set up serial port for receiving
}

void loop() {
  readData();
}

// Reset ColorPAL; see ColorPAL documentation for sequence
void reset() {
  delay(200);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  pinMode(sio, INPUT);
  while (digitalRead(sio) != HIGH);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  delay(80);
  pinMode(sio, INPUT);
  delay(200);
}

void readData() {
  char buffer[32];

  if (serin.available() > 0) {
    // Wait for a $ character, then read three 3 digit hex numbers
    buffer[0] = serin.read();
    if (buffer[0] == '$') {
      for (int i = 0; i < 9; i++) {
        while (serin.available() == 0);     // Wait for next input character
        buffer[i] = serin.read();
        //Serial.print(buffer[i]);
        if (buffer[i] == '$')               // Return early if $ character encountered
          return;
      }
      //Serial.println("");
      parseAndPrint(buffer);
      delay(10);
    }
  }
}

// Parse the hex data into integers
void parseAndPrint(char * data) {
  sscanf (data, "%3x%3x%3x", &red, &grn, &blu);  // Pull the R, G, and B values from the data string

  char buffer[48];                               // create a buffer
  //sprintf(buffer, "r = %4.4d    g = %4.4d    b = %4.4d", red, grn, blu);   //print the values into a buffer as formatted integers
  int sum = red + grn + blu;
  //Serial.println(sum);
  if (sum >= 120 && sum < 126) {
    Serial.println("Purple");
  }
  if (sum >=  238 && sum < 248) {
    Serial.println("Green");
  }
  if (sum >= 230 && sum < 235) {
    Serial.println("Red");
  }
  if (sum >=  330 && sum < 340) {
    Serial.println("Orange");
  }
  if (sum >=  420 && sum < 430) {
    Serial.println("Yellow");
  }
}

Sorry, I typed this on my phone so of course I misspelled things, how great.

Please edit your question (click "edit") and mark the code as code.  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.  Note, instead of “sort of works but not as well as I would like” say what it actually does and what you actually want.

Indeed, please say what is wrong with it. I can see a bug, but maybe it's nothing to do with the problem you're seeing.

You can't just sum the RGB values and expect to differentiate the colors.

Probably converting it to hue and then checking it's value will work much better. Did you try using red/green/blue sheets to check if the sensor works?

In parseAndPrint
You need to check the return value of sscanf to see if the function read the data.
The problem you are having is the difference between + and &.  The sensor is providing 3, 3 digit hex values (which should be sprintfed with %03x not %4.4d).  Adding these together isn't going to give you the write answer.  For instance $001001001 should give you a colour of r=1, g=1 and b=1.  If you add those together you get 3, but you really want 0x001 0x001 0x001.
You need to recalibrate you system and keep the three values separate and represent each colour by a minimum and max of those three colours and then check the value 3 values you receive are within the 3 ranges you have.
// Define a structure (could be a class) to hold the data
struct ColourData
{
    int redMin;
    int redMax;
    int grnMin;
    int grnMax;
    int bluMin;
    int bluMax;
    char Name[30];
    ColourData (int rm, int rx, int gm, int gx, int bm, int bx, char* name)
      : redMin(rm), redMax(rx)
      , grnMin(rm), grnMax(rx)
      , bluMin(bm), bluMax(bx)
    {
        sprint(Name, "%s", name);
    }
};

// Define an array containing the data
ColourData colours[MaxColours] = {ColourData(150, 200, 0, 20, 150, 200, "Purple")
                         , // Add some more

// The code to check the colours
for (int index = 0; index < MaxColours; ++index)
{
    if (  red >= colours[index].redMin && red <= colours[index].redMax
       && grn >= colours[index].grnMin && grn <= colours[index].grnMax
       && blu >= colours[index].bluMin && blu <= colours[index].bluMax)
    {
       Serial.println(colours[index].Name)
    }
}


text:
What is difference between analog and digital input and output, and when should i use anlog or digital (input or output)?
How should i determine whether to use input as analog or digital and same for output too?

This question is too general. Rather mention the specific problem you want to solve, in which you cannot find a way to decide between analog Vs. digital.

I am making an line follower robot so i am unable to understand  what to use analog or digital pins.

You also need to specify what sensors you are using for your line following robot.

Array of 6 infrared sensor

There must be over 10000 different sensors of this kind. Put exact references please. References will lead you to datasheets, datasheets will lead you to the solution: either they provide an analog signal or a digital one!

Well all i know that this sensor have 12 pins for output, 6 for digital and 6 for analog.

Then I'm afraid you don't know enough to build your robot. You have a lot to learn first.

You will use digital pin modes when dealing with signals that are either "on" or "off", such as an LED, a switch, or another digital IC.
Analog inputs are used when you want to read the voltage potential of something. This is typically used to read analog sensors. Analog outputs are not really analog at all on the Arduino. Instead, the Arduino uses something called PWM to create a pseudo-analog signal.
You can read more about analog and digital here:
https://learn.sparkfun.com/tutorials/analog-vs-digital

Is it same for output too

For digital? Yes. Digital input and output are the same. Analog input is different from analog output. Analog in uses special hardware to determine a the voltage on the pin, while analog output uses PWM to mimic a voltage on the pin, but it is not truly analog out.

Also note that the analog pins can also be used as digital input and digital outputs. In case you run out of pins.


text:
MISO pin issue in SPI
I have interfaced sd card and ADS1262 (ADC module) with Arduino mega board and sharing the SPI control pin i.e. SCK, MISO and MOSI.
I have found that sd card is not initialized and ADS1262 is giving garbage value.
Now if I remove the MISO pin of sd card then ADS1262 is giving right (although SD card is not initialized.)
Vice-versa, if I remove the MISO pin of ADS1262, sd card is initialized and working perfectly (although ADS1262 is giving garbage value.)
Certainly, there is issue of MISO pin. How can I share MISO pin with both slaves so that both can work properly.
Any comments please.
I am using shifter - TXS0108E.
For SPI interfacing, I have tested two slaves with Mega board and found the below result when MISO is connected with both slaves and MISO pin is removing one by one from slaves.

From Above result, I thing it may be the problem of MISO pin.
I am not getting the idea, how to solve the problem in SPI interfacing in multiple slaves.
Schematic:

Please show us how you've connected everything. Especially the CS pins and the TXS0108E.

It could be the TXS0108 interfering with the SPI bus. MISO must be in a high impedance mode on all inactive devices - the TXS may not be doing that. You need to force it by holding OE LOW when the TFT is not in use. Connect it to the TFT's CS pin through a NOT gate, or use a second IO pin and assert it the opposite of the TFT CS pin.

Also SD cards are notoriously bad at sharing the SPI bus. Try different SD cards.

See How do you use SPI on an Arduino?. From your now-deleted comment: all other devices are expected to have their MISO line in a third state - in other words, input (high impedance). First state is output+high, second state is output+low, third state is input.

Hi Nick, i got the point that all other devices are expected to have their MISO line in a third state but I am not getting the logic that how can I put the inactive device's MISO line in a third state. TFT and SD card both are working on the TXS0108E and the ADS1262 is working directly on 5V. I have still many IO pins to use so it is better to use IO pin to make the MISO pin in third state, if any logic is there.

You probably want to use two SPI busses. If you absolutely need to use one bus, attach a digital out pin to each of the CS pins, one on the 1262 and one on the SD card. When you need to talk to one of the deviced, pull its CS line low to enable it.

I am interfacing ADS1262, SD card and TFT with arduino mega. In that, I am sharing the all three spi lines i.e. miso,mosi and sck. All three slaves has individual cs line. But only, TFT is working fine, ads1262 is giving garbage value and sd card is not initialized, Although, individually, each slave is working fine. I have tested two slaves with arduino mega (instead of all three slaves) and found above given table's result. If I remove the one slave's miso pin, the other slave is working fine and vice versa. So it is the purely spi base problem. but i don't get idea to solve the problem.

You mention in passing that you use a shifter, yet you don't say what you are shifting or where you are shifting it. A full schematic of the whole SPI portion of your project is required.

Some sd card modules which use 5v-3.3v logic level shifters may not have a proper circuit wich is very well explained in this guys blog
http://www.vishnumaiea.in/projects/hardware/interfacing-catalex-micro-sd-card-module
so until you don't make some changes in the sd card module you wont be able to have multiple slaves on your spi bus.


text:
Autolock transistor for powering Arduino
I have a portable project where I want to take care about batteries getting discharged.
Usually I just put a switch at the very beginning of my circuit that completely cuts off the electricity when switched off. The problem with this approach is that if you forget to switch it off your batteries will discharge.
So I was thinking about an approach that after some inactivity time cuts off the circuit (I want to completely cut off the electricity to minimize power consumption, so I'm not interested in sleeping modes or similar approaches).
So my approach consist in changing a switch for a regular push button that   enables the circuit when pushed, and then one of the arduino pins is used to lock the transistor until a function times out and the pin gets to a low voltage (see image)
In the arduino code I can just test a simple program that keeps the circuit closed for 10 seconds and then switches it off.
setup() {
    pinMode(3,OUTPUT);
    digitalWrite(3,HIGH);
    delay(10000);
    digitalWrite(3,LOW);
}

loop() {
}

For the transistor part I'm not sure what to use. I was thinking about using an motor driver L298 (which should work and also accepts some load for other electronics that I might have in the project)
However this looks like something that should already exist (either in a shield or maybe integrated in some Arduino variant).
Does anybody have experience with such an approach or a suggestion on any standalone transistor that would also do the job?
Any help is appreciated :)
.

Search "transistor latch circuits" for a lot of articles about them including how-to. From there you can decide whether to build or buy.

from the look of it, most n-chan mosfets would work as expected. i would add a diode to the left "rail"

Here is a mock-up of what I usually do.

simulate this circuit – Schematic created using CircuitLab
Keep in mind that the resistors are just an example value: you'll have to make some calculations.
Now, M1 is a PMOS, while M2 is an NMOS. Both MOSFETs should be able to turn on and off with the voltages you can supply them (so look at their Vgs curves). Moreover the M1 mos will be the one where all the supply current will run, so you'll have to choose it wisely. The M2 mos will only have to supply a small current, so the smallest one is fine. Beware that if the Vin voltage is greater than the maximum Vgs voltage of M1 you'll have to add a resistor between M1 gate and M2 drain to form a voltage divider with R1.
The R4 and D1 are used if you want to detect a SW1 push (for instance to turn off the device). If you don't need this feature, remove them both.
The circuit works this way: when you push the button, a voltage (for instance 5V - 0.6V of D1) will come to the arduino Vcc. The arduino then should immediately bring up the pin. This will turn on M2, which in turn switches on the M1 transistor, thus bypassing the switch. When you remove it, the arduino stays powered.
When the arduino decides that it should turn off (either because you pressed the button again, or because it timed out, or who knows) it executes two instructions: one to pull down the pin and the other is while(1). This prevents it to continue executing the program. The M2 transistor shuts down, the M1 gate floats to Vin and so it shuts down too.
You can find the transistor as discrete componetns (sometimes also in the same SOIC-8 package. Usually I use big pMOS (e.g. IRF9310 in SOIC8) and smaller nMOS (usually in SOT-23 case). I do this because I can easily solder them also on perfboards (SOIC8 single transistors have a lot of redundancy for pins, while SOT-23 ones can be mounted easily on 3 pads).

If you would like an out-of-the-box solution, the Pololu Pushbutton Power Switch is a lovely piece of hardware that lets the device turn itself off :)
Update: Adafruit also released a "Low Power Timer Breakout" that allows a device to be turned on automatically from 1s-2hr intervals, and then disable the power supply from the device once each run is done.
If you need less often than 2 hr intervals, you could increment a number in EEPROM in setup() each run and immediately re-enter sleep if the number doesn't match your desired value.


text:
Smooth breathing led
I am trying to make a simple breathing led circuit in which the intensity of the led varies between 0 and 255. I followed the Fade tutorial on the Arduino site, which gives me what I want, but I notice that the change in brightness is much more noticeable when the intensity is at 0.
In other words, the brightness seems to be bouncing back from 0, rather than slowly gliding back up.
I tried mapping the value of the delay to brightness: del = map(brightness, 0, 255, 10, 1); but that did not do the job.
The mapping seems to work better when I use 30 instead of 10 as longest delay time:  del = map(brightness, 0, 255, 30, 1); but I think what I really need is to implement some sort of sinusoidal function to make transitions smoother, but I am really struggling with the math... Any suggestions?
Here is the code:
int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 1;    // how many points to fade the LED by
int del;

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }

  // here I map the delay to brightness
  del = map(brightness, 0, 255, 10, 1);

  delay(del);
}

Maybe use a sinewave to set the brightness. Or possibly you want a logarithmic scale?

Sinewave would be good, and a logarithmic scale too.. just really not sure about how to implement those...

I think you should look into gamma correction. Our eyesight is logarithmic, so for our eye to see something as twice as bright, it has to be around 4 times as bright. For example, using the standard fade sketch, the leds starts to increase in brightness fairly rapidly, but then seems to slow down.

These days there are so called "Digital Potentiometers", these can work with a board, to actually change the voltage into the led, instead of simulating it with a pwm

There's two ways you could algorithmically do what you want, both with different results.
The first is with a sinewave:
for (int i = 0; i < 360; i++) {
    analogWrite(5, (sin(i * 0.0174533) + 1) * 127));
    delay(3);
}

Basically you work your way 360 degrees around a circle and take one axis (e.g., the vertical one), offset it so that the values are all positive (sin gives a value between -1 and +1), then multiply it to fit the full brightness.
This is the smoothest way of fading an LED, but it doesn't respect the different sensitivities your eye has to the different brightnesses (you see more brightness variation when it's dim compared to when it's bright).
The other method is much cruder but does respect those differences in sensitivities. This specific method only gives you 8 brightnesses as opposed to 256, but they are on a log2 curve:
for (int i = 0; i < 9; i++) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}
for (int i = 7; i > 0; i--) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}

The theory of this one is it uses bit-shifting to gradually fill a byte with 1 from the least significant bit upwards.
When i is 0, this formula:
int v = (i << i) - 1;

gives:
1 << 0 == 0b00000001
0b00000001 - 1 = 0b00000000

If i is 4, you get:
1 << 4 == 0b00010000
0b00010000 - 1 = 0b00001111

So you effectively end up with a set of values:
0: 0
1: 1
2: 3
3: 7
4: 15
5: 31
6: 63
7: 127
8: 255

That code gives -1 3 15 47 127 319 767 1791 4095 1791 767 319 127 47 15 3.

Seems there's a typo there - i instead of 1 - easily done. I've also fixed another bug.

The three 255 values for RGB colour space  (255^3) is 16,581,375 colours. These include for brightness level.  The reason you're experiencing brightness issues is not to due with your arduino board but, with the RGB color space.  And by breathing, and i'm guessing here, that you are trying to transition thru RGB:
void colorLoop() {

    static int Col1;
    static int Col2;
    static int Col3;

    static int C1;
    static int C2;
    static int C3;

  if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

  C1 = random(1, 3);
  C2 = random(1, 3);
  C3 = random(1, 3);
  }

  if (((C1 == 1) && (Col1 != 0))) {
      Col1 = (Col1 - 10);
  }
  if (((C2 == 1) && (Col2 != 0))) {
      Col2 = (Col2 - 10);
  }
  if (((C3 == 1) && (Col3 != 0))) {
      Col3 = (Col3 - 10);
  }

  if (((C1 == 2) && (Col1 != 250))) {
      Col1 = (Col1 + 10);
  }
  if (((C2 == 2) && (Col2 != 250))) {
      Col2 = (Col2 + 10);
  }
  if (((C3 == 2) && (Col3 != 250))) {
      Col3 = (Col3 + 10);
  }

if (((Col1 <= 90) && ((Col2 <= 90) && (Col3 <= 90)))) {  //avoid black
   C1 = 2;
   C2 = 2;
   C3 = 2;
 }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
     leds[i] = CRGB(Col1, Col2, Col3);
    }
    delay(100);
    LEDS.show();
  }

You may have more success or find it easier to use a HSL or HSV colour space. HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:
https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors
here is a similar effect using the HSV color spectrum:
void rainbow_fade() {

 int ihue = 0; //some microcontrollers use HSV from 0-255 vs the normal 0-360
    ihue++;
    if (ihue > 255) {ihue = 0;}
    for(int i = 0 ; i < LED_COUNT; i++ ) {
     leds[i] = CHSV(ihue, 255, 255);
    }
      LEDS.show();
      delay(100);
  }

I thought about making a regular fade, with a logarithmic delay:
for an example:
val=30*(1-((sqrt(brightness))/(sqrt(255))));
delay(val);

I'm not sure that it will work with a normal led. Some 20mA leds are still bright with only 1mA. The programmable RGB 5050 leds (for example the NeoPixels) are easier for a smooth visual brightness change.
The human eye is logarithmic for light brightness. Therefor a 10-based exponent or a less steep natural-based exponent can be used.
This will give a smooth brightness change:
y = a * exp (-b * x * x);
// x is incrementing in time.

If you really need a very smooth brightness change for a normal led, you might need an extra output with a higher resistor value to the same led, for a higher resolution at low brightness.

Use a timer interrupt and in thee Isr change a pwm generator duty cycle. Or
Use a timer and set up two compare channels with a fixed offset. In the compare Isr, advance the math points forward and then flip an output pin. You will see the brightness goes up and down, whose speed depends on the offset.

No need for gamma correction.
edit: to demonstrate how the 2nd approach might work, here is a quick example.
It runs off of TIMER0, Output Compare Ch A and Ch B.
TIMER0 is set with a 256x prescaler, free running. Ch A is set to interrupt every LED_PR ticks, and Ch B is set to interrupt every LED_PR + LED_OFFSET ticks. they run the same user interrupt handler -> to flip a pin attached on LED_PORT / LED pin.
tmr0_init(TMR0_PS256x);                 //initialize tmr0 with a prescaler
tmr0a_setpr(LED_PR);                    //set up output compare ch a period
tmr0a_act(led_flp);                     //install user handler for ch a
tmr0b_setpr(LED_PR + LED_OFFSET);       //set up output compare ch b period, with offset
tmr0b_act(led_flp);                     //install user handler for ch b
ei();

and here is how it works in simulation:

the DC will go up then down, then up and then down, ....

Just recently I published a blog post about this very topic at https://thingpulse.com/breathing-leds-cracking-the-algorithm-behind-our-breathing-pattern/
Turns out you get very pleasing results if you use f(x) = e^sin(x). If you bring this down to 0 and have an amplitude of 255 the formula becomes f(x) = (e^sin(x) - 1/e) * (255/(e - 1/e)). Finally, you stretch x so you get a frequency of 12-20 breaths per minute: x * PI/2.
#include <math.h>

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

void loop() {
  float val = (exp(sin(millis()/2000.0 * PI)) - 0.368) * 108.0;
  analogWrite(9, val);
}


text:
Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build
on attempt to build  I get the following error
C:\Users\gmyer\AppData\Local\Temp\build5d24776aeb7b2efec3566cec737c36d8.tmp\sketch\trash\bootloader.c:1:1: error: unknown type name 'This'

 This modules tests receiving vacuum data from the

 ^

The problem is that I have no file of that name, and no text that exactly matches that any where in my sketch.  and my sketch is located in C:\Software
I have tried rebooting, deleting the Temp directory, reverting to known working code.  but it keeps regenerating.

I found the offending file in a sub directory of the C:\Software sketch directory.  I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.


text:
Using Air Quality Sensors like MQ135 to sense dust particles
Using MQ135 (or similar) to sense dust particles in PM
I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}

You class this as costly?

@Majenko: i class that as very expensive; easily 4X the 2nd cheapest part in a build, when gas sensors are only a buck or two... it's hard to get a build out the door for $10-20 if a part cost $15...

The MQ sensors can not be used to sense dust particles. They are Electrochemical gas sensors which are sensitive for certain gasses. They are not sensitive for dust particles. Dust is not a gas, but tiny solid particles.


text:
exit status 1 'mcpButtonState' cannot be used as a function
I keep getting this error and I don't know why.
mcpButtonState is an array, and I would like to change one of its values using a line like this:
mcpButtonState(thisPin) = 0;

(it's inside of a for loop looping trough all my pins).
This is my complete code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h
#include <Wire.h>
#include "Adafruit_MCP23017.h"
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
Adafruit_MCP23017 mcp;

int mcpButtonPins[] = {0,1,2,3,4};
int mcpButtonCount = 5;
int mcpButtonState[5];

int analogButtonPins[] = {0};
int analogButtonCount = 1;
int analogButtonState[1];

int potiPin = A2;
int soundVolume = 15;

void setup() {
  mySoftwareSerial.begin(9600);
  //Serial.begin(115200);
  mcp.begin();
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
    mcp.pinMode(thisPin, INPUT);
    mcp.pullUp(thisPin, HIGH);
    mcpButtonState(thisPin) = 0;
  }
  //ANALOG BUTTON SETUP
}

void loop() {
  int potiValue = analogRead(potiPin);
  int newVolume = (potiValue / 1023 * 30);
  if(newVolume != soundVolume)
  {
    soundVolume = newVolume;
    myDFPlayer.volume(soundVolume);
  }
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
     if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 0)
     {
      mcpButtonState(thisPin) = 1;
      myDFPlayer.play((thisPin + 1));
     }
     else if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 1){}
     else {
      mcpButtonState(thisPin) = 0;
      }
  }
  //ANALOG BUTTON PLAYING
}

Use [] not ():
 if((mcp.digitalRead(thisPin) == 0) && (mcpButtonState[thisPin] == 0))

Note the use of && instead of the word and.


text:
3D printer Arduino sketch
I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?

With stepper motors you don't need any form of encoder. Only a limit switch.
A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.
If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.
All you need to do is count.


text:
DS18B20 - Thermometer and Sensor discrepancy (varying)
This is a follow-up question from this other question
I followed of the user Jot (get the sensor away from the sun and use a delay in arduino program)
But the results are still varying.
I recorded the temperature measured in the sensor, the temperature measured using a mercury thermometer and calculated the difference. The data was collected within 8 days
Here's the data (sorted):
SENSOR  THERM   DIFF
32.69   31.25   1.44
32.00   30.25   1.75
31.94   30.50   1.44
31.87   30.50   1.37
31.44   29.50   1.94
31.00   29.00   2.00
30.75   29.00   1.75
30.50   29.00   1.50
30.44   28.80   1.64
30.31   28.90   1.41
30.25   28.75   1.50
29.87   28.00   1.87
29.81   28.00   1.81
29.81   28.00   1.81
29.81   28.25   1.56
29.75   28.20   1.55
29.69   28.00   1.69
29.56   27.00   2.56
28.75   27.25   1.50
28.69   27.00   1.69
28.56   27.00   1.56
28.44   27.00   1.44
28.25   26.80   1.45
28.00   26.50   1.50
28.00   25.50   2.50
28.00   25.00   3.00
27.75   25.50   2.25

The average difference is around +1.76°C but that's not linear, and as you can see there are fluctuation in the same sensor value, 28.00 has three associated temperatures(25.0, 25.5, 26.5).
I'm not sure what to do, if the difference was regular I could simply subtract that from the sensor readings, but it seems that it varies a lot(Min: 1.37°C, Max: 3.00°C)
Any ideas?

good use of data! it's actually not that far off for a $1 sensor. If you subtract 1-2C from the sensor, you'll be pretty close on almost every sample. try a DHT22 for more precision.

The best fit linear model would be THERM_HAT=SENSOR*1.10237- 4.81422 per  summary(fit<-lm(THERM ~ SENSOR,x)) in R.

Most readings are pretty consistent. There are only a few that are way of. But there could be some other factor that was influencing the reading. Maybe there was a draft.  Maybe you made multiple reading in a row which would slightly warm up the part....

This isn't so much an Arduino question, but you are asking how to do better than a simple offset.  The next level of complexity is to do an offset and scale.
If this is the best data you can get from your setup, a better calibration than just an offset would be finding the best offset and scale.  You can do this with your data in R with:
> x<- read.table(header=TRUE,text="SENSOR  THERM   DIFF
 32.69   31.25   1.44
 32.00   30.25   1.75
 31.94   30.50   1.44
 31.87   30.50   1.37
 31.44   29.50   1.94
 31.00   29.00   2.00
 30.75   29.00   1.75
 30.50   29.00   1.50
 30.44   28.80   1.64
 30.31   28.90   1.41
 30.25   28.75   1.50
 29.87   28.00   1.87
 29.81   28.00   1.81
 29.81   28.00   1.81
 29.81   28.25   1.56
 29.75   28.20   1.55
 29.69   28.00   1.69
 29.56   27.00   2.56
 28.75   27.25   1.50
 28.69   27.00   1.69
 28.56   27.00   1.56
 28.44   27.00   1.44
 28.25   26.80   1.45
 28.00   26.50   1.50
 28.00   25.50   2.50
 28.00   25.00   3.00
 27.75   25.50   2.25
 ")

summary(lm(THERM ~ SENSOR,x))

... to get:
Call:
lm(formula = THERM ~ SENSOR, data = x)

Residuals:
     Min       1Q   Median       3Q      Max
-1.05217 -0.16263  0.08482  0.21809  0.47224

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -4.81422    1.60425  -3.001  0.00602 **
SENSOR       1.10237    0.05369  20.533  < 2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3816 on 25 degrees of freedom
Multiple R-squared:  0.944, Adjusted R-squared:  0.9418
F-statistic: 421.6 on 1 and 25 DF,  p-value: < 2.2e-16

... from which you can use the intercept and SENSOR parameters as an intercept and scale like:
therm_estimate = -4.81422 + 1.10237 * sensor;

You could plot the data in R like:
library(ggplot2)
ggplot(x,aes(x=SENSOR,y=THERM))+geom_point() +geom_smooth(method='lm')

Looking at the graph and data, your mercury thermometer is reading sometimes to the nearest 0.1th, and sometime to the 0.25th, and that is causing patterns in your data.  Maybe use a better, high-accuracy, calibrated lab thermometer if you want to be sure you aren't calibrating against something unreliable.

Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?
There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.
You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?
I wrote before: "To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)". That is what I did, out of curiosity. It turned out to be accurate.

Yes, I did the distilled water test. The mercury sensor is spot on on those temperatures. I was about to buy some others sensors but I can't be sure if those will be good either, buying from the internet is always a risk, I haven't damaged the sensor as far as I know.

Make sure there they are measuring the exact same physical temperature  -- pack the thermometer and sensor together in a little box or something to minimize air currents and stabilize the transients.   The mercury thermometer could also be non-linear in the range of interest, even it it matches at the 0,100C.  Lab-grade thermometers are graduated to the nearest 0.1C, rather than the 0.25C you are reporting.

Buy a few more to compare. The DS18B20 can return a temperature that is maximum 0.5°C below up to 0.5°C above the actual temperature. As far as I know every single one of them meets that specification.

The DS18B20s would be easy to automatically test and cull during production.   Much easier than consumer-grade liquid thermometers.


text:
Arduino Due, program not there after power off
When i program my arduino Due after a RESET, my program is still there.
However, when i power off my Due and then turn it back on, no program is there!
There is no persistence in the program and i have to program it all again!
I am programming it throught the Programming port.
EDIT: If it doesn't boot properly with my code and then i press the RESET button, then my code is loaded and it works like i programmed it. But how can i make it so that it works straight away, after it's fed with power?


text:
Serial Monitor (user input)
I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.
  String readString;

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

       void loop()
       {

         if(Serial.available()>0)

         {
            char c = Serial.read();
            readString +=c;
            delay(2);

                   if (c == '1')
                    {
                     delay(1000);
                     Serial.println("Hello");
                     c = "";
                    }

                                 if (c == '2')
                                  {
                                    delay(1000);
                                    Serial.println("Bye");
                                    c = "";
                                  }
             else
            {
             readString= "";
            }
          }
        }

Fix your code indentation.

Welcome to Arduino SE.  Be sure to take the tour to see how it works here:  https://arduino.stackexchange.com/Tour

You have most of what is needed but you have it structured incorrectly.
Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.
The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.
The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.
This code is untested:
char cMode;

void loop()
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}

You missing setup() loop here where you have to initialize serial communication. Check out my code, you will be find what I mean.

Try out this code. It will helpful for you.
char serialData;

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

void loop()
{
  if(Serial.available())
  {
    serialData = Serial.read();

    if(serialData == '1')
    {
      Serial.println("Hello");
    }
    else if(serialData == '2')
    {
      Serial.println("Bye");
    }
  }
}


text:
Deprecated Conversion error
I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming
How to remove it?
C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino: In function 'void updateState(byte)':
C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are const char* and the function parameters are declared as char*.
The correct way to fix this would be to update DisplayInfo() so that the parameter types are const char*. The dirty fix is to cast the parameters in the call.
   DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

But I would not recommend that.
Cheers!

The correct way is always the better and the header of DisplayInfo() should be changed to use const keyword in parameters. If code is third party, author/maintainer should be also informed to patch it. Good answer @mikael-patel :)

An alternative is to declare some string constants and then pass the variable names into the function. i.e. const char cRFIDScanner[] = "RFID Scanner"; const char cStarting[] = "Starting up"; DisplayInfo(cRFIDScanner, cStarting, HIGH, HIGH);


text:
How fast is a SD page read from a file?
For a project I would like to do, I asked a question about whether to use SD or EEPROM (see Question
I checked how much memory I would need without any restrictions which is like 2 MB (or more) so a SD card seems the best solution.
However, I'm a bit worried about the speed. In one of the answer comments is mentioned that 20 ms is an eternity for a microcontroller. However, I might need to do the following within 20 ms:

Parse a MIDI event (CPU power only, does not take long)
Read one or two SD pages (1/2 times block of 512 bytes)
Change/add/remove the MIDI event (CPU power only, negligible)
Send out MIDI data (barely no time, mostly hardware)

In worst case I can get like 10-20 MIDI events I need to handle within 20 ms. Especially for step 2 I don't know how much time it will.
My plan is to create a big file with a PC program to be stored on the SD card. Than I can let the Arduino read pages of 512 bytes from predefined places (with seek in a file).
I'm intending to keep the file open at all times and use seeks to go to the right place and read 512 bytes every time (assuming it doesn't matter to read 1 or 512 bytes since the page size is 512 bytes anyway).
So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?
(btw, I want to try first on an Uno, but probably I will later go to a Mega (or add more SRAM to store temporary data).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.
Cheers!

Thanks for this answer, although the answer is no, still 40 pages per second is feasible which still is ok (but not optimal). Just hope it doesn't matter to read non-contiguous blocks for the max spee of 1 MB/s and the seeks don't take too much time.

No, there is much more going on when accessing an SD. You should count on 200-300 Kbyte/s max substained. The SD SPI protocol requires both synchronization and addressing so the effective bandwidth is lower. High speed SD uses multiple data pins (and additional hardware support).

that would mean a page read of 512 bytes would take 2.5 ms? And 512 bytes is the minimum amount to read I read somewhere.

@MikaelPatel: would it be possible to use 2 sdcards and 2 SPI buses to (almost) double the throughput?

Just for reference for others:
I received my micro card reader (from Catalex, v1.0, 11/01/2013) today and used a 1GB micrSD card.
The times measured ar at 4 addresses (2000, 120000, 40000 and 12000) again and are a seek to the address, and the reading of the bytes mentioned before the colon and the time after the colon in micros.
Result: Seek is 25..2500 micros depending on the file position, reading below 256 bytes is approx. 2-3 ms, reading 256 bytes 4-6 and 512 bytes 7-8  ms.
Initializing SD card...card initialized.
---------
Address: 2000
seek    : 24
read   1: 2276
read   2: 2308
read   4: 2344
read  10: 2380
read 256: 4780
read 512: 7328
-----------
Address: 120000
seek    : 2536
read   1: 5008
read   2: 5040
read   4: 5084
read  10: 5120
read 256: 5312
read 512: 7888
---------
Address: 40000
seek    : 2468
read   1: 4940
read   2: 4972
read   4: 5016
read  10: 5052
read 256: 5252
read 512: 7828
---------
Address: 120000
seek    : 2504
read   1: 4992
read   2: 5024
read   4: 5060
read  10: 5104
read 256: 5296
read 512: 7864


text:
How i can have one code for multi sensors
am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

You have to keep some points in your mind:
(1) You have to ensure that pins must be not conflicting with each other. If you merge all sensor codes in one code then pins must be conflict. So you have to change pin number.
(2) If all sensors have separate working then make the function for all that sensors. It will very helpful for understanding and debugging the entire code.
(3) Don't try to merge all codes same time. Add one by one and also change pin number during that.

am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

This could be considered a general question: Is it possible to merge several sketches and if so how?
The first step is to check pin conflicts: Are any of the sketches using the same pins (or resources)? If that is the case this needs to be resolved.
The next step is to check timing. Is is sufficient to run each loop() after each other or does the timing behavior also require changes.
The idea is then to simply "merge" the different setup() and loop() functions to a single setup() and loop().
In most cases, the timing behavior will leave no other choice than to rewrite the code.
There are a few tools (such as a Scheduler) that can be used but they require additional understanding of programming and nothing for the novice.


text:
How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)?
I went through Sparkfun's website on how to power a project because I wanted to calculate how much battery capacity I needed for my project. I saw an ATmega 328 micro-controller that is used as the brains for the circuit: it draws about 20mA under normal conditions.
So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me, I am new to this.

Do you have a reasonably accurate multimeter? You can put it in series with the power circuitry and measure the power draw in your specific situation.

It should be a clamp ammeter otherwise you risk smoking your multimeter with the large currents.

A clam amp meter for measuring milli amps???

I once measured the current draw of my Uno in normal conditions (active mode), and it was around 40 – 50 mA. A bare ATmega328P in POWER_SAVE mode is about 2 µA. Never measured on a Mega.

ya, i dont think you need to worry about a clamp style meter for measuring the current draw of a microcontroller......

The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.
Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). (However, see below)
The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.
I have a page about power saving that you might find useful if your objective is to minimize power usage.

Edited to add more about power consumption
It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.
I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.

Sorry, but I just read this now (since it was bumped to the homepage) and I'd like you to further explain the "the voltage regulator has to throw away some of the extra voltage as heat" sentence. The only thing that should increase the current consumption is the RN5C-D couple (20k, which draw 0.35mA at 7V and 0.6mA at 12V, for an increase of 0.25mA); the fact that you are experiencing a 8 times larger increase is puzzling on my side. Even thermal increase in the 1117 has a much lower impact (50°C change about 5% the quiescent current - which is 6mA, so 0.3mA). What am I missing?

I'm seeing about 100mA from my Mega2560. It's static within about 1mA or so all the way from about 6.6V upwards.

@frarugi87 - upon re-measuring I am still finding between 1 and 1.8 mA more consumed at 12V. I can't fully explain that but am working on it. Which revision Mega2560 board do you have? Mine doesn't seem to have a revision number, so it is probably the first one released.

@NickGammon I haven't measured mine; the data I gave came from an analysis of the schematic of rev3; the rev1 mega2560 has another IC, so maybe it's its fault...

@frarugi87 It appears that I was wrong. See amended answer. Much more extensive testing shows that the current consumption decreases slightly with an increase in voltage.

@NickGammon Thank you for your effort in this :) I think this is still strange, since I expected an increase in the current of some hundreds of microamps; maybe the part was heating up slowly, so testing it back and forth (7 -> 12 -> 7) could give more infos, but I fail to understand why a heated up part consumes less... In any case I agree with you; this is very interesting, but is OT in this answer. If you plan to add a page to your website with these measurements and so on please share the link since I will be very interested in your tests and opinions :)

@frarugi87  You are right I am getting off the topic, but just for your info, running the loop backwards (12V down to 7V) gave a very similar plot, so it seems the part is heating up, and that is causing the difference.

@NickGammon Good to know; thank you for these updates and for your patience :)

You may be right that AtMega chip will draw relatively small amount of energy. But there are other components in the Arduino that will draw much more. (Voltage regulator as a best example.) In the end, the current drawn can (and will) be 10x larger.
And there is another problem, you have to know how much power will connected sensors draw.
What you can do is build your own 'less greedy' Arduino and use sleep abilities of AtMega chips.
Here are some links to go through:
https://openhomeautomation.net/arduino-battery/
https://circuits.io/circuits/1717500-power-rail-blocking-with-an-arduino/
http://www.gammon.com.au/power

Why do you say tht the voltage regulator is an example of what draws much more current? usually the voltage regulator by itself consumes  moderate current (6mA in the worst conditions), and only when using the Vin power supply. What drains the most are the two microcontrollers. and there are also some LEDs....

How did you get 6mA?

Sorry, I remembered wrongly. It's 6mA typically, 10mA worst case. From the schematic you see that the voltage regulator is an NCP1117; its datasheet has a parameter called "Quiescent Current", which has that value

"Quiescent Current" is the current the regulator disipates when there is no load... POWER dissipation of the voltage regulator will be much bigger. Power, not current. For sure using 9V battery and regulator is much worse (energy-wise) than providing directly 5V. (Just guess, but i think 9V battery (as it is compound of cells) has less capacity than the same size 5V battery...)

BUT I do agree, that voltage regulator was not the best example to start with!

yes, the power dissipated by the voltage regulator is very large. For instance when you have a 11V power supply, the regulator will dissipate about the same power as all the components at 5V combined together. But the current drawn depends mostly on the components at 5V. In any case I noticed you wrote "draw ... energy", but since draw is linked to current I thought that you were referring to it

I should have expressed more clearly... In case of voltage regulator, that is not the case. But in case of unnecessary leds, converters, other components, the DRAW is a case.

I saw an ATmega 328 microcontroller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

the datasheet provides the best guidance on that. typically 10ma - 20ma is fairly standard for 8-bit mcus. other components on the board, like opamps, or regulators, leds, may consume a little bit more so I would say 20ma - 30ma total is a good estimate for the board.

So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me I am a newbie to this.

the datasheet showed 20ma typical so I would put the board to 30ma total. 5000mah/30ma = ...

Note that one of those “other components on the board” is itself a microcontroller that may draw its own 20 mA.

And looking at the measurements in another answer, the current is 65-70mA


text:
How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)
I want to get acceleration data from a ADXL355 sensor.

My code:
void readFIFO (){
long data[3];
byte data2 [9];

digitalWrite(chipSelectPin, LOW);
SPI.transfer( (FIFO<<1) | 1);
for (int i = 0 ; i < 9; i++){
    data2[i] = SPI.transfer(0x00);
}
digitalWrite(chipSelectPin, HIGH);

Serial.println("Byte data in hex and binary");
 for (int j = 0 ; j < 9 ; j++){
    Serial.print("element "+String(j) +": ");
     Serial.print(data2[j],HEX);
     Serial.print(" ");
     Serial.println(data2[j],BIN);
 }
 for (int z = 0 ; z < 3; z++){
    data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
 }
 Serial.println("concatenated values: ");
 for (int i = 0 ; i < 3 ; i++){
    Serial.println(data[i]);
 }
}

Sample output:
Byte data in hex and binary
element 0: F9 11111001
element 1: 1B 11011
element 2: 51 1010001
element 3: 0 0
element 4: FD 11111101
element 5: 90 10010000
element 6: C3 11000011
element 7: 2A 101010
element 8: 20 100000
concatenated values:
-28235
4057
12962

The values are two's complement. Are these the correct values? If not what am I doing wrong?

You need to sign extend the results.
e.g.
If the value is -1 your 3 byte values will be: 0xff ff f0
Combining these in to a single 32 bit value as you do gives you: 0x00 0f ff ff
Which is not -1.
What you need to do is check the most significant bit of the value and if it is set then set the top 12 bits.
for (int z = 0 ; z < 3; z++){
  data[z] = (((long)data2[z*3]<<12) | ((long)data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
  if (data2[z*3] & 0x80)
    data[z] |= 0xfff00000;
}

Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.

FIFO buffers are extremely useful for IC's with an ADC so you can poll the sensor for the data less frequently and get all samples that were collected in the interim. This prevents you from having to have a very tight sampling loop if you have many sensors to communicate with.


text:
How to create TCP server on Arduino UNO WiFi?
I'm currently trying to make my Arduino UNO WiFi work as a TCP host, so I can send him a TCP message and it sends a response.
I had no problem doing this on the Arduino Galileo Gen 2 using the EthernetServer, but since this one is using WiFi, EthernetServer isn't an option.
I can, however, run a web server, but that's not what I want.
So how do I make the Arduino receive, handle and respond to sent TCP/IP messages?

Ethernet and wifi are basically the same thing but only joinig Ethernet is codewise different than joining a wifi address and thus these two need 100% different code because wifi and Ethernet are a different thing.
See, compare codes in below links, and you see the difference is on making up the level 1 connection, and tcp and ip on 2 and 3 do not change.
https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinoethernet/arduinoethernet/arduinoethernet.ino
https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinowifi/arduinowifi/arduinowifi.ino

Thank you, however I'm still getting the "WiFi shield is not present". May I ask you how I can fix that issue? I've tried a lot of things but I still get that error. And is it still neccesary to give the SSID and password if the Arduino Uno WiFi is already connected to the wifi?

To initialize the used connection object, I suppose yes.

Okay thanks. Now I'll try to fix the "WiFi shield is not present" message

For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".
Hope this can help you.

this 'late' answer is ok, only there is now a better option then the slow UnoWiFi-Developer-Edition-Lib. the new library for Uno WiFi is UnoWiFiDevEdSerial1 library


text:
what is the use of Serial.begin(9600)
I mean what it does, why it is needed, what if we don't use it, similarly   for Serial.println(sensorValue).

Can you tell me what if i don't write it m program, what will happen

Serial.begin() initializes serial-port hardware and data structures so you can use the serial port.  See Serial.begin and Serial.println doc pages at arduino.cc for details, and see the answers to What is Serial.begin(9600)? for more background.

As the name suggests, serial.begin(9600) is a command you give to the Arduino to begin serial communication. I'm assuming you're a beginner. Anyway, as you might've seen on the IDE, there's a serial monitor. It outputs data that you configure it to output. It won't work unless you begin the serial communication using. The serial.begin(x); command. X is a variable baudrate, and I highly suggest going with 9600.
Okay, also, serial.println(sensorValue) is a command that the program gives to the Arduino to print the variable sensorValue to the serial monitor. Keep in mind that you can also print this through a Bluetooth module by connecting the tx to the rx and the rx to the tx pins. Hope this helped! :)

Serial.begin(9600); configures the UART interface and sets it to the right baud rate. If you don't to that you can't use the UART interface.
Serial.println(sensorValue); outputs the sensor value to the UART. If you don't use that you won't see the value of the sensor on the UART.
If you don't want to use the UART then don't use it. If you do want to use the UART then you must use the commands that control the UART.


text:
Problems powering standalone arduino with USB powerbank
I've successfully migrated and ATMEL328P-UP microcontroller from the Arduino Uno Board to a breaboard, following these instructions: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. Everything is OK, the bootloader worked and code is already uploaded an running.
The ATMEL is connected to a pair of sensors, and all the system works using 3.3V. And here comes the problem: I'm using a 5V USB power bank to power up everything. When I make this connection:
USB Power Bank @ 5V -> Arduino Uno board (without the microcontroller) -> 3.3 V Output from the board -> ATMEL/Sensors on the breadboard
everything works just fine! Now I decided to replace the Arduino uno board with an LM317 voltage regulator which gives me the 3.3V needed. The connection is this:
USB Power Bank @ 5V -> LM317 with 3.3 V output -> ATMEL/Sensors on the breadboard
and nothing happens! Is as if there wasn't enough current to feed the ATMEL nor the sensors. I've checked the Vcc/GND pins of the sensors and the ATMEL and they're all getting the required 3.3 V, but for some reason the system seems to be OFF.
What could be happening? I'm sure the USB power bank is at full charge, so it should be able to supply enough current. Any suggestions?
Thanks guys!

Can you show the actual LM317 circuit?

How have you connected ground through the board and breadboard?

@MikaelPatel: I'm not going through the board in the second case (it's been replaced by the voltage regulator).

@Majenko The LM317 circuit is as the one shown here. In my case R2 = 1.6K and R1 = 1K to ensure that Vout = 1.25(1+1.6/1) = 3.25 V* . Connections are as follows: +5 V Power Bank -> Vin LM317; Vout LM317 -> Vcc ATMEL (pin 7)

According to the datasheet, the LM317 needs an input voltage 3v higher than the output. Since 6.3<5, there's not enough margin for the LM317.
You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find these modules very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.
you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of these style converters, and they seem to work very well.

Indeed! According to the datasheet, 5V are not enough for the LM317; so even if the LM317 delivers the required 3.3 V it might be an issue with the current?... I'll give the AMS117 a go and let you know!

your current would be fine, if it weren't the LM317 would be hot. It's the voltage drop from the 317's darlington pair transistors that cause the problem. The AMS117 uses only a single pnp transistor and thus drop less voltage.


text:
Arduino UNO WiFi RestServer returning "not found"
I'm trying to run RestServer on my Arduino UNO WiFi, and I'm currently using the tutorial from Arduino: http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
Everything works as expected, but whenever I change this:
  // is "digital" command?
  if (command == "digital") {
    digitalCommand(client);
  }

To this:
  // is "digital" command?
  if (command == "test") {
    digitalCommand(client);
  }

and go the the same URL but instead of "digital", user "test", I get a "not found" error.
(from http://url/arduino/digital/13/1 to http://url/arduino/test/13/1)
Am I doing something wrong? Or are the URLs in that example the only possible ones?

Try "/arduino/digital/test"...


text:
Arduino UNO WiFi "wifi shield not present"
I currently use the Arduino UNO WiFi, but when I try to use the WifiChatServer example, I keep getting the same error: wifi shield not present.
What am I doing wrong?

That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C->UART converter chip.
You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE.
  Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.


text:
How to execute three functions at the same time?
How to implement three functions, which can execute in the same time (function of input random variables)?

You can't. An Arduino only does one thing at a time. The trick is to write your program so it interleaves your functions together.

See my post about How to do multiple things at once

No single processor can do more than one thing at a time. The best you can hope for is that each function runs for a short time only and gives the processor to the next one, giving the illusion that there is more than one thing happening at once. This is called multi-tasking or multi-threading.
There are some libraries that will do this for the Arduino (search "RTOS Arduino" or "Arduino multitasking"), or you can write each functions using the principles of Finite State Machine programming to achieve the same effect.

You can implement three functions but you can't able to execute them same time.

How to implement three functions, which can execute in the same time (function of input random variables)?

Micro-controllers such as the AVR used on Arduino boards have only one processing core but there are many hardware modules (ADC, UART, SPI, TWI, Timers, etc). Using these it is possible to achieve several "functions" at the same time, i.e. pure concurrency.
Some examples, while waiting for ...

ADC (analogRead) there are over 100 cycles
SPI (spi.transfer) there are 16 cycles
UART (Serial) is actually already concurrent with buffering and ISR's.
The same goes for I2C (twi).

These cycles can be used to interleave different functions or improve performance (e.g. pre-fetching, pipe-lining).
Another example; using direct port read it is possible to read the state of several pins at the same time.
With simple collaborative multi-tasking it is possible to context switch between several functions (tasks) on delay or yield. This can be done with a scheduler.

How to implement three functions, which can execute in the same time (function of input random variables)?

have three executors / arduinos, one for each function.

If the result of each function can be expressed as a single byte (i.e. an integer between 0 and 255) then you could:

Connect 3 shift registers (e.g. 74595 ic) to 3 pins on your Arduino
Assign one pin to each function
Use the shiftOut function to output the result of each function one bit at a time on its relevant pin
Use a 4th pin connected to all 3 shift registers as a common latch - when this pin is set HIGH the outputs from the 3 shift registers will all change at the same time.

Or put the three SR's in series, using 2 pins less


text:
Is there any way to use a JTAG programmer with the Arduino IDE?
I am doing a lot of work with custom boards I've designed with the ATSAMD21G. I'd like to get away from using USB to program my boards since the USB port takes up space on the PCB and consumes extra pins. Is there any recommended way to configure the Arduino IDE to simply dump out the compiled program into a JLink debugger, much like the Atmel Studio IDE can?

For a one-click upload, you can make a custom hardware definition that calls any executable of your choosing.

The IDE makes a .hex file which you can then program onto your chip with a suitable programmer.


text:
Blink 2 LEDs one at a time every x seconds
Newbie here - literally opened my Arduino about 3 hours ago. I have been able to code 2 LEDs to blink randomly, but what I want to do is have one of the two blink every 10 seconds.
My current code:
void setup() {
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {
  // set 2 random on/off values
  byte on4 = random(2); //returns a random choice of 0 or 1
  byte on5 = random(2);

  //Write the value of each variable to the pins.
  digitalWrite(4,on4);
  digitalWrite(5,on5);
  delay(500);
}

I know I have to do something to the loops, I just can't figure out what.

Try out this code. It will helpful.
const int kPinLed = 4;      // LED at pin 4

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as OUTPUT
}

void loop()
{
  digitalWrite(kPinLed, HIGH); // LED ON
  delay(10000);                // 10 Sec delay
  digitalWrite(kPinLed, LOW);  // LED OFF
  delay(10000);                // 10 Sec delay
}

Choose if you want to keep pin 4 or 5.
Remove every reference to the other.
Move the declaration of the remaining pin outside of the loop, before the setup function. Ex: byte on4;
inside setup, assign a value (1 or 0) to the surviving pin. Ex: on4 = 0;
inside the loop, change the value of the pin. EX: on4 = !on4;
digitalWrite changes the state of the pins driving the LEDs.
Remove the one you do not want.
delay expresses how long the system waits, in milliseconds.
Change accordingly.
byte on4;

void setup() {
  on4 = 0;
  pinMode(4, OUTPUT);
}

void loop() {;
  on4 = !on4;
  digitalWrite(4,on4);
  delay(10000);
}

This should work, but I have not tested it.

You need to split the logic into 2 parts. One part will select the pin that you want to blink and the other will blink the pin.
I'll show how you do this using delay() but, clearly, it would be better to use the BlinkWithoutDelay methods of counting time so the processor can do something else. This code is untested and is set up so that you can just add pins to the ledPin array with no other changes and it will always work properly.
uint8_t ledPin[] = { 4, 5 };  // Arduino pins with the LEDs

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

void BlinkOne(uint8_t pin)
{
  digitalWrite(pin, HIGH);
  delay(5000);
  digitalWrite(pin, LOW);
  delay(5000);
}

void setup(void)
{
  for (uint8_t i=0; i<ARRAY_SIZE(ledPin); i++)
    setMode(ledPin[i], OUTPUT);
}

void loop(void)
{
  uint8_t thisPin = ledPin[random(ARRAY_SIZE(ledPin))];  // select which pin

  BlinkOne(thisPin);  // blink that pin
}


text:
Char transmission using Virtualwire RF signal
This is a really basic problem, but I haven't been able to resolve it myself and would really appreciate the help.  So I've been struggling for a few weeks now to set up RF communication between two arduino uno chips.  I have the transmitter and receiver hooked up to 5V supply, with the data pins connected to digital pin 4.  My code looks like this:
Transmitter code:
#define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;  // variable used to store transmission data

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

void loop(){
  digitalWrite (rfTransmitPin, HIGH);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, HIGH);
  delay(2000);

  digitalWrite (rfTransmitPin, LOW);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, LOW);
  delay(2000);
  }

Receiver code:
#define rfReceivePin 4  //RF Receiver pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;   // variable used to store received data

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(rfReceivePin, INPUT);
  Serial.begin(9600);
}

void loop(){
  data=digitalRead(rfReceivePin);    //listen for data on Digital Pin 4

   if(data = HIGH){
    digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
    Serial.println(data);
  }

  if(data = LOW){
    digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
    Serial.println(data);
  }
}

This should be really simple, but for some reason I'm reading a continual HIGH signal from the receiver module.  I'm trying to sort out the basic functionality of the RF tx-rx pair before developing code to send a char using the Virtual Wire library, but I can't even get it to function at this level.  Since my code is so basic I'm convinced it must be a hardware issue and I'm not sure what I'm doing wrong.  Any suggestions?

VIf you using Virutalwire try exemple in the library.
You can't send simple digitata data with Rf.
Best Regards Mikael
link Virutalwire

Hi Mikael, thanks for the reply.  I've tried running the example transmitter/receiver code, and all I get is the setup printout on the serial monitor, the message doesn't come through.

http://www.hackshed.co.uk/rf-communication-between-2-arduinos/

This will you show you how you use VirutalWire

Turned out to be a faulty receiver, it's all working as it should be now :-)

Glad you got it working


text:
SSD1306Ascii Library
Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?

Yes, you can edit the library yourself, or copy its functions to your sketch and modify them.
You can also use another library, like u8g2.

Adafruit library uses a buffer and it's using it as a lookup to invert the color. SSD1306Ascii has no buffer, so copying the code over won't work.

@gre_gor I'm not sure I follow your reasoning. The SSD1306Ascii library can be modified to send the right pixels to the display, or you can copy its functions into your sketch and modify them there. As some example starting places, you could add a function similar to SSD1306Ascii::write that inverts the pixel data (b) before sending it to the display; or you could modify the initializer to invert the whole display: change this from SSD1306_NORMALDISPLAY to SSD1306_INVERTDISPLAY.

@Chris Combs Since im mainly looking for low memory space i cant use u8g2. library or ssd1306 adafruit library since they occupy relatively a lot of space.

@DineshKarthie u8g2's page buffer mode only needs 128 or 256 bytes of ram... if you are referring to program size then you can keep it down by including smaller fonts, more details here: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L124-L127


text:
Can't Flash ESP8266 latest firmware, says "Fast Flashing error" and "Invalid head of packet(' ')
I can't figure out how to flash the firmware found on http://www.electrodragon.com/w/ESP8266_AT-Command_firmware. I am using ESP8266 Download tool v3.4.4. When I am adding a firmware in download path it goes on till a fixed percentage (77 or 99..mostly) and gives the error Invalid head of packet, FAST FLASHING ERROR. One more thing is that the tutorials I am using to do this have many download path entries filled in the download tool while mine are just blank. It says upload the combined file to 0x0000. I tried uploading V1.54... file's content (both files) but still got the similar error(https://i.stack.imgur.com/wiQ5K.png). :P
So anyone could just guide me through this as I am a complete newb into this. Please mention any other information needed in comments.
PS

I am pretty sure the power supply is adequate as I have been using esp8266 with the old firmware smoothly. I have also connected a 200uF capacitor b/w gnd and vcc(3.3v from FTDI).
I have double checked the connections.(Yes, GPIO0 is grounded).
I flashed an earlier version successfully ai-thinker-v1.1.1.bin but when I connected it to arduino IDE serial monitor it started giving unending gibberish text :P.


text:
Run exe or apk on Arduino
how to run exe file or apk file on Arduino UNO?
Please suggest me any way to execute both file. Thank you.

You're really not getting what an Arduino is, are you?

What is Arduino?

If a PC or Smartphone is akin to a family car, an Arduino is akin to one of the wheel bolts holding the wheels on.

@Majenko: but sir, we run c program on arduino. So IDE creates exe and run it on device. How that happened?

No, the IDE does NOT create an EXE. It creates a HEX. Embedded programs are vastly different to executables that run on an operating system.

@Majenko ok sir thank you for clearing concept

You cannot.  An APK is an Android package, and an EXE is a Windows executable.  Neither can run on an Arduino,


text:
Why is my circuit working only when I touch it?
I have connected digital pin 2 of arduino to the circuit as shown:

The problem is that the LED is not turning on normally its only turning on when I touch anything on collector side of circuit. What seems to be the reason? Seems like grounding problem as its turning off when I don't touch my legs to ground.

Thank you in advance.

if that's an npn, it's (probably) backwards. you also need to common the ground with the MCU

Hint: Use wires intended for breadboards. The battery wires lack pins.

Sounds like you have guessed it: although it's very hard to say from those photos, it doesn't look like you have the circuit grounded.
Connect a ground from the Arduino to the black wire from the battery.

Yes, you are right its working now. Thank you very much :D.

Sorry for the photos, I uploaded this from my phone and I put connections in image descriptions, but they are not visible in the post.


text:
Enter timing value via keypad for bldc motor spin
I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?
The idea for this code is to enter the speed and timing via keypad.  After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?
Here is my code so far...
#include "Keypad.h"
#include "LiquidCrystal.h"
#include "Servo.h"

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

Servo myservo;

const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("S:");
  lcd.setCursor (0,1);
  lcd.print ("T:");

  myservo.attach(11);
}

void loop()
{
    static char buffer[4], spintime[4];
    static byte i = 0, a = 0;
    char key = keypad.getKey();

    // i < 3: prevent buffer overflow
    if  ('0' <= key && key <= '9')   // this is for speed entry
    {
        buffer[i] = key;
        ++i;
        buffer[i] =0;  // null-terminate buffer
        lcd.setCursor (2,0);
        lcd.print(buffer);
    }

     if  ('0' <= key && key <= '9') // this is for timing entry
     {
        spintime[a] = key;
        ++a;
        spintime[a] =0;  // null-terminate buffer
        lcd.setCursor (2,1);
        lcd.print(spintime);
    }
    else if (key == '#')            // this is to run the motor after speed and timing are entered
    {
        int value = atoi(buffer);
        myservo.write(value);       //speed of motor
        int timing = atoi(spintime);
        delay (timing*1000);        // keep the motor spin for ( timing entered) second
        myservo.write(0);
        i = 0;
    }
}

As I understand it, you want to enter the speed, then the time, then '#'.
Let's imagine you want a speed of 22 and a time of 3.  The device will see 2, 2, 3, #.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.
My suggestion: we'll enter speed followed by *, and time followed by #.  (There are other possible solutions to this.)
We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter 123456789#, we will register 123#.  (Again, there are other solutions.)
There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.
Lastly, I am assuming your code to drive the motor and read keys is correct.
Here's some loop code which I hope will do the above.  It will read numbers until it finds either a * or a #, convert the number to an integer, and store it as either time or speed.  When it has both speed and time, it will spin the motor and reset the values.
void loop()
{
    // Where we will store the number as we type it.
    // This buffer is large enough for a 3-digit number, pull a null terminator
    char buffer[4];

    // The speed of the motor
    static int speed = 0;

    // The time to spin for
    static int time = 0;

    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i<3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key || '*' == key)
        {
            // Null terminate
            buffer[i] = 0;

            // Convert to an integer
            int value = atoi(buffer);

            // Set the appropriate value
            if ('#' == key) time = value;
            if ('*' == key) speed = value;
            break;
        }
    }

    // If we have both speed and time...
    if (speed > 0 && time > 0)
    {
        // ...spin the motor at the required speed
        myservo.write(speed);
        // ...and for the required time
        delay(time*1000);
        // ...then stop it
        myservo.write(0);

        // Reset the values for next time
        time = 0;
        speed = 0;
    }
}

thanks for the insight mark smith... but I wanted it to do like this (code below) how to I  enter the speed first, then enter the timing second... after that... pressed #  for the motor to move to the desired speed according to the timing... how do I combine the speed entry and time entry...

Could you edit your question to state the actual question, please? Also please include code to set the speed, if you have it, because I don't know how to control your motor. I'll try to help with getting input.

i have change it mr. Mark... i hope you can really help me with this.

Answer updated.

Mr Mark... i have tried your code... I enter speed of 123 then pressed #... after that I enter 10  then pressed *... after entering all the entries... the motor suppose to spin according to the time given...however nothing seem to happen... your code seems right tho...does pressing *  after to time entry suppose to activate the motor??

Read my answer again, more carefully.

thank you so much Mr Mark Smith.... it worked!!!!... i appreciate it... God bless you Sir... :)

Mr. smith... how do i make the timing displayed on the lcd to be counted down... let just say... i want 10 second... then the display show 10,9,8,7,6.... 1... is it possible with delay()??

That's an entirely separate question. Please post it as a new question, complete with a minimal, complete, verifiable example. Remember to tell us how much of the problem you have already been able to solve - for example, can you display anything on the LCD?