text:
Arduino code not working properly (Please Help)
I am having some trouble getting my board to perform the function I want it to perform. This is a project I have due in a few days, and I have hit a wall I just can't seem to get past. Now, I will say the issue is definitely in the way I coded the program, but I don't really know enough about Arduino (and coding) to understand why it is not working. My board is properly hooked up to use 3LEDs, a speaker, a photoresistor, and an ultrasonic sensor (detects distances). My Arduino program takes serial input from a GUI that I created in MATLAB. I have verified the MATLAB code is good, and the serial port is communicating properly. I have made an alarm that goes off when light or motion is detected. It has 3 basic functions:

Set the alarm
Turn off the alarm
"snooze" which just delays for 5 minutes and then the alarm goes off

The snooze and turn off alarm parts of my code are working great, but the set alarm is where I am having trouble. The snooze option sets off the yellow LED to verify it is on "snooze". The red LED comes on when the alarm is currently going off. The green LED comes on when the alarm is set. When I try to activate the "Set Alarm" function, which is case 'O' in a switch case, the light does come on, but the sensors are not picking up any input as far as I can tell. Again I have verified the pins and everything are set up correctly as I have isolated those and verified they work. I have a suspicion that the problem is because I have the sensors initialed within the switch case of the "Set Alarm" (case 'O', not 0). I don't really know how to get the sensors to run continually within that switch case until the "turn alarm off" case is activated. I need the sensors to be activated/reset by "Set Alarm" case.
**I am also new to this forum so please let me know if I am missing anything!
here is my code:
void setup()
{
  Serial.begin(115200);
  pinMode(12,OUTPUT); //RED
  pinMode(13,OUTPUT); //GREEN
  pinMode(14,OUTPUT); //YELLOW
  pinMode(16,OUTPUT); //SPEAKER
  pinMode(4,INPUT); //Echo
  pinMode(2,OUTPUT); //Trig
}

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

  switch(b)
  {
    //Turn Alarm off
    case 'A' :
    {
    digitalWrite(12,LOW);//red off
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    noTone(16);
    delay(500);
    }
    break;

    // Set alarm
    case 'O' :
    {
      int light;
  light = analogRead(0);
  unsigned long distance;
    digitalWrite(2,LOW);
  delayMicroseconds(2);
  digitalWrite(2,HIGH);
  delayMicroseconds(10);
  digitalWrite(2,LOW);
  distance = pulseIn(4,HIGH);
  distance = distance/58; //centimeters
  delay(500);

    digitalWrite(12,LOW); //red off
    digitalWrite(14,LOW); //yellow off
    digitalWrite(13,HIGH); //green on

  if (light < 400)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

  if (distance < 50)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

    }
    break;

    // snooze option
    case 'Z' :
    {
    digitalWrite(14,HIGH); //yellow on
    digitalWrite(12,LOW); //red off
    digitalWrite(13,LOW); // green off
    noTone(16);
    delay(300000UL);
    digitalWrite(12,HIGH); //red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }
    break;
   }

  }
}

Any help would be very much appreciated!

Hi Geraldo and welcome to Arduino Stack Excange. Please take the [tour] and read all the way to the bottom to earn your first badge. Your code appears to missing the top section with your includes and global variable declaration. Could you please check and add it.

Please use the Auto Format to format your code. In the Arduino IDE, go to Tools > Auto Format or use the keyboard shortcut Ctrl + T.

The most simplest way to troubleshoot a program is to add Serial.println(); statements everywhere. For example you could add Serial.println("Setting Alarm"); in the first line of the case for setting the alarm.
You will notice that the set alarm code only runs once through, instead of continously. You should use the case to set a mode or a state in where the sensors are checked continously.
First I would create a variable called setAlarmMode and set it to false.
setAlarmMode = false;

Then I would remove the reading of sensors from the case statement and instead set setAlarmMode to true.
// Set alarm
case 'O' :
  {
    Serial.println("Setting Alarm");

    // Set the LEDs for the mode
    digitalWrite(12, LOW); //red off
    digitalWrite(14, LOW); //yellow off
    digitalWrite(13, HIGH); //green on

    setAlarmMode = true;
  }
  break;

Now I would insert this code outside of the if (Serial.available() > 0) code block:
// Read sensors
if (setAlarmMode == true)
  {
    Serial.println("Reading sensors");
    int light;
    light = analogRead(0);
    Serial.print("Light sensor value: ");
    Serial.print(light);

    unsigned long distance;

    // Do trigger pulse
    digitalWrite(2, LOW);
    delayMicroseconds(2);
    digitalWrite(2, HIGH);
    delayMicroseconds(10);
    digitalWrite(2, LOW);

    distance = pulseIn(4, HIGH);
    distance = distance / 58; //centimeters
    Serial.print("   Distance sensor value: ");
    Serial.println(distance);

    if (light < 400)
    {
      Serial.println("Light below threshold");
      setAlarmMode = false;
      activateAlarm();
    }

    if (distance < 50)
    {
      Serial.println("Distance below threshold");
      setAlarmMode = false;
      activateAlarm();
    }

    delay(500);
  }

I have also created a function to hold the common code of showing the alarm:
void activateAlarm(void)
{
  digitalWrite(12, HIGH); //red on
  digitalWrite(13, LOW); // green off
  digitalWrite(14, LOW); //yellow off
  tone(16, 832);
  delay(500);
}

Thank you so much for your help! I really appreciate it. The program works great now.

The problem is that, if you enter 'O', you go thorugh the set alarm case only once. If no alarm was triggered, it just falls through the if statements and is then back in the main loop. In that main loop, you only check for your sensors, if something was entered to the serial console. That means if you do not enter anything during a loop, nothing happens.
The solution to this would be to implement a finite state machine.
That means you use a state variable for the switch case. You then update your state based on the state and the external conditions. In your case you can just update the state using user input.
I changed your code a bit for a possible (but bad) implementation. I did not verify or check for errors. I recommend using a more solid implementation, if you plan to build upon this code for more complex behavior.
char state = 'A'; //initialize state in Off state
char b;          // make user input variable global
void setup()
{
  Serial.begin(115200);
  pinMode(12, OUTPUT); //RED
  pinMode(13, OUTPUT); //GREEN
  pinMode(14, OUTPUT); //YELLOW
  pinMode(16, OUTPUT); //SPEAKER
  pinMode(4, INPUT); //Echo
  pinMode(2, OUTPUT); //Trig
}

void loop()
{
  if (Serial.available() > 0)
  {
    b = Serial.read();
  }
  // close user input section

  switch (state) // run switch case every loop
  {
    //Turn Alarm off
    case 'A' :
      {
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        noTone(16);

        delay(500);
      }
      break;

    // Set alarm
    case 'O' :
      {
        int light;
        light = analogRead(0);
        unsigned long distance;
        digitalWrite(2, LOW);
        delayMicroseconds(2);
        digitalWrite(2, HIGH);
        delayMicroseconds(10);
        digitalWrite(2, LOW);
        distance = pulseIn(4, HIGH);
        distance = distance / 58; //centimeters
        delay(500);

        digitalWrite(12, LOW); //red off
        digitalWrite(14, LOW); //yellow off
        digitalWrite(13, HIGH); //green on

        if (light < 400)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

        if (distance < 50)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

      }
      break;

    // snooze option
    case 'Z' :
      {
        digitalWrite(14, HIGH); //yellow on
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        noTone(16);
        delay(300000UL);
        digitalWrite(12, HIGH); //red on
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        tone(16, 832);
        delay(500);
      }
      break;
  }

  state = b; // update state based on input

}


text:
How to get started with writing code for a Hall Effect sensor?
One of my biggest questions concerns coding a Hall effect sensor to find wheel speed with an arduino mega.
I’ve got an lcd in digital pins(7,8,9,10,11,12) and a Hall effect sensor in digital pin 2.
I just have no idea how to code the actual rpm measuring process. Does anyone have any ideas or experience that can help me? My form of measurement is to spin something with a mounted magnet near it. The end game is to measure a car wheel rpm. Pointers? Tips?

yes, many people have ideas and experience ... is that all you wanted to ask?

break the program into individual sections ... start by reading sensor and turning led on and off when signal is detected .... then work on learning how to display numeric data

There are numerous tutorials online. An example is https://maker.pro/arduino/tutorial/how-to-use-a-hall-effect-sensor-with-arduino

You can measure this in either RPM (revolutions per minute) or frequency (cycles per second).
Whether it be a minute or a second, you count the number of times you get a pulse and at the end of the minute/second you copy the total to your variable and reset the counter variable. If you need a fasster update rate, you can count for fractions of minute/second and do the calculation to show it in terms of RPM/frequency.
My first concern when solving this issue is how fast the magnet is going past the sensor (ie how many pulses per second).
If it is slow, you can do it in your main loop as long as you don't have any blocking instructions (such as delay()).
If it is fast you will probably have to look into an interrupt. When the pin goes high, it jumps to the interrupt function and increments a counter. Check the input section for libraires that make the interrupt process easy (or do it the old fashioned way, your choice). Some of the button libraries have interrupt specific functions.

Make sure to only count a pulse once. For example, you could achive this by looking for the rising edge of the pulse.

source: Stack Exchange

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

sort: votes


text:
Stepper Motor button control with A4988 Driver
So I'm quite new to programming and have inevitably worked myself into a corner. What I am trying to accomplish is to allow for a stepper motor, (powered by an A4988 driver) to move with the push of a button. The schematic is as follows:

And the code to try and make the motor move with a button is:
const int = buttonPin = 2;
const int = stepPin = 3;
const int = dirPin = 4;

int buttonState = 0;

void setup(){
    pinMode(stepPin,OUTPUT);
    pinMode(dirPin,OUTPUT);
    pinMode(buttonPin,INPUT);
}

void loop(){
    buttonState = digitalRead(buttonPin);

    if (buttonState = HIGH){
       digitalWrite(dirPin,HIGH);{
           digitalWrite(stepPin,HIGH);
           delayMicroseconds(500);
           digitalWrite(stepPin,LOW);
           delayMicroseconds(500);
           }
    }}

What am I doing wrong?

Seperate each code part and test each part. First check if you can detect a push on the button by turning on a led or sending a message to the serial monitor. Then create for example 100 steps for the stepper mode in code. Then you can put the two things together. Please add extra information to your question: which stepper motor is is?

Please edit the question to include a description of the problem. I can see one definite problem with your code and one thing which probably isn't what you want, but it would be useful to know how it doesn't work.

Sometimes microstepping doesn't work with particular motors. I suggest configuring the driver board for full step operation until you get your code working properly.

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


text:
Serial.read(); and state machine for AT commands
I have a strange type of issue: the index of the array doesn't increment and when I print the value from the serialdata[pointingfinger] it just gives me an empty space.
This is a state machine (I guess) that should check what is the current char that's being written into the array and its position to avoid searching it later. When we have a finished line it changes the bigger state machine to another mode (that checks if four chars further is the command) when the processing is done it should get back getting the next line.
This is Arduino Leonardo and Serial is the USB and Serial1 is where I send and receive AT commands.
const long interval = 1000;
static long currentMillis;

char plussignpoint = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; //Array to store the chars before parsing

int rdpos = 0;

int pointingfinger = 0;

char timeen = 0;
byte stat0 = 0;
char futstat0 = 0;
char searchcharpos = 0;

char enabled = 0;

char searchchartype = 0;

char smsvalid = 0;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write("ATE0\r");
}

void loop() {
    if (millis() - currentMillis >= interval)
    {
      Serial1.print("AT+CCLK?\r"); //ask for the time

      enabled = 1;

      currentMillis = millis();
    }

    if (enabled == 1) {
      if (stat0 == 0) {
        if (Serial1.available () > 0) {
          pointingfinger++;
          serialdata[pointingfinger] = Serial1.read();
          if (serialdata[pointingfinger] == '+') {

            searchcharpos = pointingfinger;
            searchchartype = 1;
            futstat0 = 1;
          }
          else if (serialdata[pointingfinger] == '$') {
            if (smsvalid = 1) {
              searchcharpos = pointingfinger;
              searchchartype = 2;
              futstat0 = 2;
            }
            if (smsvalid = 0) {
              stat0 = futstat0;
              pointingfinger = 0;
            }
          }
          else if (serialdata[pointingfinger] == '\n') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else if (serialdata[pointingfinger] == '\r') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else {
            stat0 = 0;
            pointingfinger = 0;
          }
        }

        if (pointingfinger == 255) {
          pointingfinger = 0;
          enabled = 0;
        }

      }
    }
}

EDIT: I forgot to include what AT commands it should parse:
Arduino: AT+CCLK?

SIM800H: +CCLK: "04/01/01,01:35:31+00"

         OK

What data do you get from Serial? Your problem heavily depends in that data, so please include it.

When checking value of smsvalid you use assignment operator = instead of comparison operator ==.
            else if (serialdata[pointingfinger] == '$') {
                if (smsvalid == 1) {
                    searchcharpos = pointingfinger;
                    searchchartype = 2;
                    futstat0 = 2;
                }
                if (smsvalid == 0) {
                    stat0 = futstat0;
                    pointingfinger = 0;
                }
            }

And also you increment pointingfinget prior writing to serialdata buffer. This means that the first character will be written at index 1. So the first character serialdata will be zero, which means empty string.
      pointingfinger++;
      serialdata[pointingfinger] = Serial1.read();

There are many issues with your code, I pasted your code to online gdb c++ compiler, so you can play with it and see what is going on.
Those AT state machines aren't easy to finetune on Arduino. I spent a lot of time debugging similar code and found out that the best way is to unit test all possible situations in visual studio or xcode. Arduino is just C++ and if you copy/paste some portions of your code to C++ IDE, after implementing few functions or classes it should work. For example, to make your code working in XCode, I had to implement some dummy Serial1 class and simplify the loop code:
class _Serial1
{
    std::string buffer{"OK\r\n"};
public:
    int available()
    {
        return (int)buffer.size();
    }

    char read()
    {
        char c = buffer[0];
        buffer.erase(0, 1);
        return c;
    }
} Serial1;

void loop() {
    if (enabled == 1) {
        if (stat0 == 0) {
            if (Serial1.available () > 0) {
                pointingfinger++;
                serialdata[pointingfinger] = Serial1.read();
                if (serialdata[pointingfinger] == '+') {

                    searchcharpos = pointingfinger;
                    searchchartype = 1;
                    futstat0 = 1;
                }
                else if (serialdata[pointingfinger] == '$') {
                    if (smsvalid == 1) {  // ==
                        searchcharpos = pointingfinger;
                        searchchartype = 2;
                        futstat0 = 2;
                    }
                    if (smsvalid == 0) { // ==
                        stat0 = futstat0;
                        pointingfinger = 0;
                    }
                }
                else if (serialdata[pointingfinger] == '\n') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else if (serialdata[pointingfinger] == '\r') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else {
                    stat0 = 0;
                    pointingfinger = 0;
                }
            }

            if (pointingfinger == 255) {
                pointingfinger = 0;
                enabled = 0;
            }

        }
    }
}

And the compiler immediatelly pointed me at the incorrect assignments and also I was able to debug the code step by step and see what is happening inside.
In my situation I was interfacing SIMCOM900 gprs module and I made a state machine that allows me to write code like this:
virtual void Program()
{
    switch (Pc())
    {
        case 0: _ASSERT(strlen(mApn)>0);
                Stream() << "AT+CSTT=\"" << mApn << "\",\"\",\"\"\r\n";
                break;
        case 1: Expect("OK\r\n");
                if (Expect("+CME ERROR")) { Error("CME Error when attaching apn"); Return(false);}
                if (Timeout(25000)) Return(false);
            break;
        case 2: Stream() << "AT+CIICR\r\n"; break;
        case 3: Expect("OK\r\n");
                if (Timeout(15000)) Next(); break;
        case 4: Stream() << "AT+CIFSR\r\n"; break;
        case 5: if (ReadIpAddress()) Next();
                if (Timeout(2000)) Return(false); break; // longer?
        default: Return(true);
    }
}

Here is a bit older version of it:
https://gist.github.com/gabonator/88b80d9c6b16d699d6f4234ebc3a2587

wow I didn't know of such way to debug Arduino programs! Thanks! In the online compiler is cout printing chars one by one and not the whole array or I am writing them to the same index?


text:
How to count positive electrical pulses?
I have a device that has one blinking LED.
I want to count the number of blinks. I planned to do it using Arduino. I will connect two terminals of LED input to Arduino digital input pins, and I will count the number of positive voltage pulses
I just want to know if it is possible? and if yes then can you please hint the code for the same?

be aware that an LED can be turned on by applying Vcc to the LED, but it can also be turned on by applying 0 V ... it all depends how the LED is connected in the circuit

Look in the Arduino IDE.  There is an example called "State Change Example"  That's what you need.

Trying to use the voltage over the LED might not work, because it only changes from 0V to the forward voltage of about 2V (+/- some tenth). Use jsotola's comment and use the side that gets switched, this could as well be at the current limiting resistor.

You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).
If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.
The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.
I will give the pseudo code so you can figure out the actual code:
bool _ldrPin;
unsigned long int _counter;

setup()
{
   // Set Serial
   Serial.begin(9600);

   // Set LDR
   setAnalogPin(X, INPUT);
   _ldrPin = readAnalog(X);
}

loop()
{
    if (!_ldrPin && readAnalog(X) == HIGH)
    {
        // Rising edge, increase counter
        _counter++;
        Serial.Write(_counter);
        _ldrPin = true;
    }
    else if (ldrPin && readAnalog(X) == LOW)
    {
       // Falling edge, reset status
        _ldrPin = false;
    }
}

There is no "light diode resistor". I think you mean a light dependent resistor. Though I wouldn't suggest an LDR for blinking measurement, they are rather slow. Depending on the blinking frequency this could very well be too slow. A photo transistor is a better choice (a phototransistor is basically a diode in reverse, which get's conductable by light), it can work very fast.

Sir, I am planning to solder. But I think I have to solder both the wires from the led. I thin voltage difference is relative, so how do I compare the difference between voltage(when LED glows) using digital pins.

@chrisl Thanks for the notification (I mean indeed light dependent resistor). I never tried a photo resistor (added your name, upvoted your comment).

@SSR At least both wires should be connected to something otherwise you don't have a (closed) circuit, at least not with the LED in it. For comparing you might use an opamp but that's probably worth a different question.

Detecting the LED Pulses
You want to detect each LED pulse. For this you will need edge detection code. There is an Arduino example built into the IDE and information describing the function here: https://www.arduino.cc/en/Tutorial/BuiltInExamples/StateChangeDetection
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge. In simple terms the code can be translated to this:
if ( (lastLedState == LOW) && (ledState == HIGH) )

where ledState would be assigned by a digitalRead and lastLedState would record the value of ledState at the end of the loop function (ie. just before it reads in the led states again).
Full Code
Now if we optimise the above statement and put it into context:
unsigned long int pulseCounter = 0;
const int LedInput = 3;    // Digital input 3
bool ledState = 0;
bool lastLedState = 0;

void setup() {

}

void loop() {
    ledState = digitalRead(LedInput);

    // If the LED turns ON
    if (ledState && !lastLedState)
    {
        // Increment your counter
        pulseCount++;
    }

    // Update LED flag
    lastLedState = ledState;
}


text:
I2C communication is not working
I have been working on my project but I get an error and I need some advice or correction.
I use I2C method to communicate between master and slave. I've got two questions:

I send 7 inputs (from master) to the slave but only receives 6
Will my coding make an output like this video

Master Code
// Master Code
#include <Wire.h>
byte nChar =0;
char input[7];

void setup () {

  Serial.begin(9600);
  Wire.begin();
}

void loop()
{
  if (nChar < 7) {if (Serial.available()) { input[nChar++] = Serial.read();}}

    else {

      Wire.beginTransmission(1);

      //a
      Wire.write(input[0]);
      Serial.print("Drawer : ");
      Serial.println(input[0]);

      //x
      Wire.write(input[1]);
      Serial.print("Output : ");
      Serial.println(input[1]);

      //00
      Wire.write(input[2]);
      Wire.write(input[3]);
      Serial.print("Output : ");
      Serial.print(input[2]);
      Serial.println(input[3]);

      //y
      Wire.write(input[4]);
      Serial.print("Output : ");
      Serial.println(input[4]);

      //00
      Wire.write(input[5]);
      Wire.write(input[6]);
      Serial.print("Output : ");
      Serial.print(input[5]);
      Serial.println(input[6]);

      delay(15);

      while (Serial.available())
      {
        //Remove extra
        Serial.read();
      }
      Wire.endTransmission();
        nChar = 0;
    }
  }

Slave Code
#include <Wire.h>
byte ledPins[] = {12, 11, 10, 9, 8, 7, 6};
byte ledPins2[] = {12, 11, 10, 9, 8, 7, 6};
byte count;
byte nChar;
char c;
char input[8];
char data[30] = "";
int n;
#define nBits sizeof(ledPins)/sizeof(ledPins[0])
#define nBits sizeof(ledPins2)/sizeof(ledPins[0])

void setup()
{
  Wire.begin(1);
  Serial.begin(9600);
  for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins2[i], OUTPUT);
    }
  Serial.begin(9600);
}

void loop()
{
  if (nChar < 8) {                    //accumulate three characters
    if (Serial.available()) {
      c = Serial.read();
      input[nChar++] = c;
    }
  }
  else {
    input[8] = 1;                   //atoi() expects string terminator
    n = atoi(input);                //convert the input characters to integer
    dispBinary(n);
    delay(100);                     //wait for any additional characters
    while (Serial.available()) {    //ignore them
      c = Serial.read();
    }
    nChar = 1;
  }
}

void receiveEvent(int howMany)
{
  while (1 < Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

void dispBinary(int n) //Vertical
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins[i], n & 1);
      n /= 2;
    }
  }
}

void dispBinary2(int n) //Horizontal
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins2[i], n & 1);
      n /= 2;
    }
  }

}

void b()
{
  if (data[0] != 'a')
  {
    dispBinary(atoi("00"));
    delay(100);
    dispBinary2(atoi("00"));
    delay(100);
    goto fin;
  }
  if (data[1] = 'x')
  {
    char xdata[2] = {data[2], data[3]};//(data[2], data[3]);
    dispBinary2(atoi(xdata));
    delay(100);
  }
  if (data[4] = 'y')
  {
    char ydata[2] = {data[5], data[6]};//(data[5], data[6]);
    dispBinary(atoi(ydata));
    delay(100);
  }

fin:;
}

Where is the Wire.onRequest ?

Most coders would your while (1 < Wire.available()) { write as while ( Wire.available() > 1) { and read it "repeat while there is more the 1 byte available". but wait, why leave that one byte there? you want "repeat while there is no more byte available".
you need while (0 < Wire.available())

Which coding sir ?

change while (1 < Wire.available()) to while (0 < Wire.available())

Another question why it became on same line. Why not it become one line one output. I cant put image to share with you. How to do ?

replace Serial.print(c); with Serial.println(c); ln is line


text:
Did I Brick my Controllino?
I recently obtained a Controllino Mini to be used in a small industrial project. While checking it out I also wanted to test the built-in RTC capabilities. In doing so I toyed around with the available commands from the supplied library. After uploading another sketch it seems I have bricked the Controllino, since I cannot upload anything else :

avrdude: stk500_recv(): programmer is not responding avrdude:
  stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

and the reset LED is permanently lid. When looking at the pinout diagram of the Controllino Mini I saw that there was a small remark  near the top stating

Not proper handling of the RTC/INT output can cause permanent
  controllino reset , so I guess I somehow reached that state.

Since I am pretty new to the whole Arduino / Microcontroller scene I don't really know where to go from here.

Is it a viable idea to try and burn a new bootloader ?
Is there a simpler way to reset the state of the device?
What did I even do wrong ?

Any help is greatly appreciated !
Christian
Below is the sketch that got me into this mess:
#include <Controllino.h>

unsigned char day, weekday, month, year, hour, minute, sec;
#define analogInputPin A0
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(analogInputPin, INPUT);
Controllino_RTC_init(1);
Serial.print("Initalized RTC: ");
Controllino_SetTimeDate(1,6,4,2016,15,14,10);
}

void loop() {
 Controllino_ReadTimeDate(&day,&weekday,&month,&year,&hour,&minute,&sec);
  float voltage = 15*(analogRead(analogInputPin)/1023.0);
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.print(sec);
  Serial.print(" : ");

  Serial.println(voltage);

}

I just received an answer from the official team which should work, I'll leave it here for further reference:

Open the device and disconnect (remove) connection board for approx. 30 seconds from the control board – RTC is disconnected from power (gold cap disconnected) and because of that there is reset of all RTC registers.
Plug the connection board back in to the control board. Now we need to rewrite the SW inside the Controllino which caused wrong RTC setting.
Open the Controllino example RTC sketch in Arduino IDE and prepare it to upload (function Controllino_RTC_init(0); shall reset all registers inside the RTC).
Pres and hold reset button on the Controllino device.
Connect the USB Cable (still hold the reset button, SW inside the Controllino doesn’t start)
Click for upload the sketch in Aruduino IDE and wait for „uploading“ message on debug line, than immediately release the reset button and uploading shall be finished (=> hold the reset button during the compiling phase)
If not successful, repeat the procedure

But did it work? Atleast it's nice to know they give a reasonable answer, but I'm curious if it fixes anything.

I will get back to you on that ;) I will probably be able to test it in a couple of hours

I just got to testing, it worked just fine and I can use my Board again :). it's probably notable that you only have to remove the very top of the boards which is connected via a very small pinheader to the board below. Take care not to break anything.

That's good news. Doesn't fix the underlying problem, but at least it's a reasonably easy way of recovering from it.

It certainly looks like the INT pin of the RTC can kill the whole unit. Bit of a FUBAR on their part I would say.

Is it a viable idea to try and burn a new bootloader ?

If the problem is that INT pin then you won't be able to replace the bootloader, and even if you did it wouldn't fix the problem.

Is there a simpler way to reset the state of the device?

It looks like you will have to make a hardware modification - cut the connection between /INT and /RESET on the board - if you can identify which track that might be - or use a soldering iron to heat and lift the /INT pin of the RTC chip, which might be easier, depending on what the chip is (they are amazingly short on information).

What did I even do wrong ?

Probably nothing serious - it's the design that is at fault. Anything that has the potential to completely cripple a system like that without even trying is just idiotic.

Hey, Thanks for the well written answer. As you can see I have received an answer from the official team which should work.

Great stuff. I guess they must have answered that same question a million times.

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


text:
What are the consequences of different clock speeds on different boards?
I am a programming amateur, arduino noob, trying to decide which board will be better for my project. I need a small board. I am trying to decide between the Teensy 3.2 and the RFduino. I want to have blue-tooth capability for over air routine changes to a WS2812B LED strip, which makes the RFduino attractive because of its integrated BLE4.0 antenna. However, I want to be able to have enough speed for imperceptible LED modulation, which makes the 72MHz speed of the Teensy attractive.
What would be the objective difference between the 16MHz processor on the RFduino versus the 72MHz on the Teensy3.2? Is this something I should be concerned with?

What sort of LED strip?

Planning on 3M of 60LED/M WS2812B strip as of now.

You'll have to set some kind of timing requirement. Like: I want to be able to send and execute a bluetooth message in .. milliseconds. That's where it gets interesting. You might come to the conclusion that bluetooth is the limiting factor (thus a higher clock speed won't help a thing).

On the LED strips, the WS2812B's have a fixed timing, so a faster processor != faster LED strip you might try a "DotStar", SPI-controlled or APA102 led strip. In that case, faster SPI = faster LED strip. But those strips need 64 extra bits and 8 bits extra per LED.

You have to set your requirements, or atleast elaborate what you want to achieve.
Best would be to program in a set amount of effects on the microcontroller and only send which effect you want to "start" with maybe even a color.
But you have to specify stuff, you should make a list like this:
Length of messages
(Max) baudrate of bluetooth device & microcontroller

amount of bits in the total LED strip
speed of sending bits into the LED strip

Maximal time from sending to effect

Sample calculation for NeoPixel (WS2182)
If you can make a good approximation (or find actual values) you can determine which speed you are going to need. This might even be 1Mhz, try to avoid premature optimization.
60 leds/m for 3M = 180 leds.
24bit data per LED.
180*24 = 4320 bits of data.
One bit takes around 1,3uS, so 4320*1,3 = 5616 uS
Which is 5,616 milliseconds to update the LED strip. (Processor Mhz won't help you here)
Sample calculation for DotStar (APA102)
180 leds, 32bit per LED = 5.760 bits total.
+64 bits (32bit start frame, 32bit end frame).
5824 total bits.
You can set the SPI clock divider to 2.
So if your board runs at 16Mhz, divided by 2, you get 8Mhz SPI output.

8 megahertz = 8 000 000 hertz

(EDIT)

The fastest rate is "divide by 2" or one SPI clock pulse every 125 nS. - Nick Gammon (http://www.gammon.com.au/spi)

Neopixels take 0.85us + 0.4us = 1,25 us (1250ns).
So they would be 10x slower.
(never mind this calculation, it was from before using Nicks' facts)
8.000.000  |  5824
 1 sec     |   x

(Your x value will be the time in seconds to update the DotStar strip with SPI@8Mhz)
What was your point?
After this you can check your baudrate + message length to see how long sending/receiving your message will take.
You can then reliably tell if you need 1, 8, 16 or 72Mhz.
I believe the DotStar led strips should be faster, but I haven't completely calculated it out. You could ask yourself if it's worth trying to omptimize that.
BUT, note that the DotStar/SPI led strip allows you to have "interrupts". Which means you can receive characters over the bluetooth while you're writing to the LED strip.
And, we're probably overthinking the situation. But it's better to overthink it using hard values :)

As was mentioned earlier about the DotStar LED strip/led
There is one thing missing in the calculation above. The End Frame shows as a 32 bit frame of all 1's. That is almost correct. The least obvious is that you need to add 1/2 of a bit for each led in the strip. This is due to the way that the clock is sent down the line. So the 180 led strip would require 90 bits in the End Frame. If you don't do this you will have some of the leds at the end that are not reacting correctly. I know this sounds strange, had me for a while (I use Raspberry Pi).
Also, I have seen where some have tested the SPI mode of sending the data down the line and managed to achieve about 16Mhz clock speeds. Great for POV display.
The DotStar don't require refreshment at all. Each LED has it's own PWM chip built in. They are more expensive than the Neopixel, so it depends on the application as to which is better for you. I loaded my string with colors and then disconnected the data lines (led strip on different power supply) and turned off my Pi. Yup, the DotStars stay as they are.
It has been said they are 'addressable' which is not truly accurate. When sending data, it is the first one, then the second and on. If you wanted, you can change only the first few. Odd hack. Just send the Start Frame (32 or more 0's) and start sending data to the first without affecting the rest of the strip. Note: you might have to account for the 1/2 bit clock loss. eg: 1 bit per 2 leds.
Here is a pretty good description of the DotStar functionality :
https://cpldcpu.com/2014/11/30/understanding-the-apa102-superled/
Here is a Youtube tutorial (2 short videos) that helped me quite a bit:
https://www.youtube.com/playlist?list=PLhXSL6B3uLd551fEQlQGd3LrhzvudKfJQ

You would think on the face of it that a faster processor will give you "more speed" however that does not necessarily work in a linear way. The faster processors tend to have more sophisticated chips. And "more sophisticated" can be code for "it takes more clock cycles to achieve the same thing".
I have code that drives 300 NeoPixels in a seamless manner, on a 16 MHz Arduino Uno, however during the driving it is pretty processor-intensive (and interrupts have to be off). So certainly you can have some smooth effects at 16 MHz. However controlling them in real time, via Bluetooth, may be a different thing.
NeoPixels will "remember" the last thing that was sent to them, so (when interrupts are active) you could be accepting new instructions, and the pixels will just display what they were last sent. This may be acceptable for you.
The Adafruit page for RGB LED Strip mentions that their library is only for the AVR processors. So that may be a consideration for you.
Even with other display strips, you may find that, during reception of radio signals, the strips cannot alter their patterns at high speed. The 72 MHz you quoted is only 4.5 times as fast as 16 MHz. The NeoPixel timings are in the order of nanoseconds (350 ns for a zero-bit) so timing is tight. Having 4.5 x the clock speed isn't necessarily going to give you enough leeway to do radio communications.

I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air. Does this change your answer at all?

Your design seems to me to consist of two components:

Showing some pattern
Receiving a new pattern (or code for a new pattern)

You can't be doing both at precisely the same time. (Maybe with two processors you might - one doing the radio, and one displaying the pixel pattern). I found I could refresh 1000 pixels in 63 ms, which is roughly 16 FPS. If you have less pixels it will be faster. I don't know exactly how long it takes to determine if a Bluetooth message has arrived, I assume not particularly long.

Planning on 3M of 60LED/M WS2812B strip as of now

So, 180 pixels. At 63 µs per pixel that would be 11.3 ms to refresh the strip. You can see that this gives you quite a bit of time over in one second to receive new instructions.

I see now that I should elaborate more on "real-time". I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air.  Does this change your answer at all? Edited in original question.
Also added the LED IC spec -- could you confirm that WS2812B "remembers"? I have only found literature that LPD8806 "remembers" as you describe.

Certainly the WS2182 pixels that I have a page about here (amongst lots of pages that other people have) remember the setting. If you disconnect the Arduino (but leave power to the pixels) they retain the last setting. That's how they are designed. A 10 µs (or so) gap in sending any bits latches the previous setting. Once latched it stays there indefinitely.

@aeolus you only have to write to the strip when you want to change it. If everything would be lost immediately, you wouldn't be able to work with these strips ;)

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


text:
I’m having a tough time trying to program 2 fsr sensors
Can anyone help me please?
I’m having a tough time trying to program 2 fsr sensors.                                                                                The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed?                     I have got only one to work by using this code:
/* FSR simple testing sketch.

Connect one end of FSR to power, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground

For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading

  // We'll have a few threshholds, qualitatively determined
  if (fsrReading < 10) {
    Serial.println(" - No pressure");
  } else if (fsrReading < 200) {
    Serial.println(" - Light touch");
  } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze");
  } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze");
  } else {
    Serial.println(" - Big squeeze");
  }
  delay(1000);
}

So what would be the correct code in order to get two sensors to work at the same time?

Do you get ANY output on the serial monitor? If so can you share it?

Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:
int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);
  delay(5);
  fsr2Reading = analogRead(fsr2Pin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading
  Serial.print("\t");
  Serial.print(fsr2Reading);

Just started on forum, don't know how to format code yet, sorry.

There's a {} button in the editor.


text:
rf24 change order of data
I'm using two Arduinos with the rf24 modules.
I want to control a process with those, but for now I'm just checking the connection.
This is the code of the master:
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
unsigned char msg[4];
unsigned char serial_msg[1];

String mensaje = "ii";

int CE = 9;
int CSN = 10;

RF24 radio(9,10);

//const uint64_t pipe = 0xE8E8F0F0E1LL;
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

bool done;
int incomingByte = 0;

String stringOne  = "";

void setup(void){
    Serial.begin(9600);
    radio.begin();
    radio.setRetries(15,15);
    radio.openWritingPipe(pipes[1]);
}

void loop() {

    radio.stopListening();

    if (Serial.available() == 3) {

        while(Serial.available() > 0)
        {
            incomingByte= Serial.read();

            stringOne = String(stringOne + String((char)incomingByte));

        }
        Serial.println(mensaje);

        incomingByte = Serial.read();
        serial_msg[0] = incomingByte;

        radio.write(stringOne.c_str() ,2);

    }

    stringOne  = "";

    radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
    delay(10); // necesario para activar el modo de esucha

    if (radio.available())
    done = false;
    {
        while (!done)
        {
            if (sizeof(msg)==4)
            {
                done = radio.read(msg,sizeof(msg) );
                Serial.print("Estado: ");
                Serial.println(msg[0]);
                Serial.print("Voltaje: ");
                Serial.print(msg[1]);
                Serial.print(msg[2]);
                Serial.println(msg[3]);
            }

        }

    }
    mensaje = "";
}

What t does is read data for the serial monitor, convert it to a string and them send the string.
The code of the receiver is this:
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

int CE = 6;
int CSN = 7;
RF24 radio(CE,CSN);  /// ()
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

bool done = false;

int voltaje = 141;
String string_vol= "789";
enum states {
    ESPERA,
    ENCENDIDO,
    PAUSA
};
enum states state = ESPERA;

unsigned char msg[2];
char incomingByte = '_';
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
unsigned long interval = 1000;

void setup() {

    Serial.begin(9600);
    radio.begin();
    radio.startListening();
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);

}

void loop() {

    string_vol= "789";
    currentMillis = millis();
    if ((currentMillis-previousMillis)>interval)
    {
        previousMillis = currentMillis;
        msg[0] = char(state);
        radio.stopListening(); // Dejamos d escuchar para poder hablar
        string_vol = String(String((char)state)  + string_vol );
        radio.write(string_vol.c_str() ,4);
        radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
        delay(10);
    }
    if (radio.available())
    done = false;
    {
        while (!done)
        {
            done = radio.read(msg,sizeof(msg));
        }
    }

    switch(state) {
    case ESPERA:

        if (msg[0] == 'i')
        {
            state =  ENCENDIDO;
        }

        break;
    case ENCENDIDO:

        currentMillis = millis();

        if (msg[0]=='r')

        {
            state =  ESPERA;
        }
        else if  (msg[0]=='d')
        {
            state =  PAUSA;
        }
        break;
    case PAUSA:
        if (msg[0]=='r')
        {
            state =  ESPERA;
        }
        else if  (msg[0]=='c')
        {
            state =  ENCENDIDO;
        }
        break;
    }
}

This one acts as a state machine, and sends a string in this case:
string_vol= "789";

plus the actual state of the Arduino:
string_vol = String(String((char)state)  + string_vol );

When this Arduino is in state one:
In the other side I got:
Estado: 1
Voltaje: 555657
When is in state II I got:
Estado: 2
Voltaje: 555657
But if it's in state zero, which is the initial one, I got:
Estado: 55
Voltaje: 56570
It change the  position of the state for one of the chars of the string
EDIT.
The  issue is when sending the '0' of the first state, I changed enum to:
enum states {
    foo, //  revisar, solo usada para comenzar en 1
    ESPERA,
    ENCENDIDO,
    PAUSA
};

Now it works fine because the first state is '1', still don't now why it doesn't work if I use the '0'

The problem you run into is that you are trying to insert the binary value of 0 into an Arduino String.   That may actually be possible, but the way you attempt to to do it utilizes some C-style mechanisms, specifically representing a string as a pointer to some characters terminated by a null byte - which is to say 0.
Your code:
string_vol = String(String((char)state)  + string_vol );

Invokes this String constructor from WString.cpp
String::String(char c)
{
    init();
    char buf[2];
    buf[0] = c;
    buf[1] = 0;
    *this = buf;
}

Which tries to turn the input char into a C-style string containing the input and then its own terminating null.  But in the case where state=0, that ends up being a buffer of two 0's.  A C-style string is terminated by the first 0, so when interpreted that way, the buffer is considered empty.  The last line of this constructor uses the buffer to invoke yet another constructor, that treats the input as a C-style null terminated string:
String::String(const char *cstr)
{
    init();
    if (cstr) copy(cstr, strlen(cstr));
}

Since strlen() finds the input here in the state=0 case to be empty, it produces an empty String.  You then append some other data, and that is all that you see, with no state included in the packet.

As this demonstrates, it is necessary to to be careful mixing binary and textual representations.
One thing you might do would be to add an offset to the state before transmitting, and subtract it out on the receiver.  If you have 9 or fewer states, adding the character code of '0' (ie, 0x30) would transmit them as potentially printable digits.  If you have more, you could add 'A' and transmit them as letters of the alphabet.  In the end it doesn't really matter what you add, as long as any value you intend to transport can be represented in all the intermediate data formats it passes through.
Of course the nRF24L01 parts will transmit binary data just fine; if you want to go ahead and move binary data through them you can, you just have to avoid using anything with C-style char * mechanics that is going to see 0 in the data as a terminator, not a character.


text:
Accepting strings and integers via UART
My intention is to write a code that asks a user to enter the name and then the age. The code should then simply display the persons name and age. To do that, I have written a simple code. I find it difficult to get it to work.
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer
    while (Serial.available()==1){
        temp = Serial.read();
    }

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    age = temp;

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available()==1){
        temp = Serial.read();
        delay (10);
    }

}

The error I receive is that the program already outputs age without me even typing it.  Would it be possible to know the error?
I use both NL and CR to send in characters to Arduino and the Arduino IDEs default UART terminal.
EDIT:
Listening to advice gotton from answers I got the code to work but in a very weird way. My new code works! but it proves the clearing of buffer cannot be done by just reading it. This is in contrast to Arduino documents. My new code is as follows.
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer **WHY IS THIS CODE NOT EFFECTIVE?**
    while (Serial.available() >= 1){
        temp = Serial.read(); // performing dummy reads untill buffer empty.
    }

    temp = Serial.read();
    delay (1000);
    temp = Serial.read();
    temp = Serial.read();
    temp = Serial.read();

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    temp = temp - 48;
    age = temp*10;
    delay (1000); // providing the user a day to enter next digit of age

    if (Serial.available()){
        temp =  Serial.read ();
        temp = temp - 48;
        age = (int) temp + age; //whatever that is added have to be of same type. Else they need to be cased to same type.
    }

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available() >=1 ){
        temp = Serial.read();
        delay (10);
    }

}

In what way does it "not work"?

As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.
It is likely you are receiving everything in ASCII code.  That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.
This is fine when you are working with character strings.  But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal.  That is, subtract 0x30.
It should now be obvious that you can only enter 1 digit at a time when using a terminal.  That you will have to reconstruct the number as the user types each digit.  For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.
Since this is such a common conversion, there are Arduino libraries that do this for you.  Consider using ParseInt for this purpose.
Added later...
In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed.  And that the code is only waiting for the CR.
The delays are necessary as UART communication, as most communications, takes a finite amount of time.  And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.
Consider "looking" for the LF character after finding for the CR character and removing the added delays.

Great answer. Thank you.
Could you also please tell me why my code automatically moves to accepting age without me even typing it? I'm clearing the UART buffer by reading it untill it becomes empty prior to asking the user for age. Still, the code goes on and spits out the age of the user without me even typing it.
Thank you for teaching me my error and telling me that I need to handle user inputs for integers as single ASCII charactors.

You did not repeat your code design when entering a string of characters when you coded up the part of your program to enter the age.  You basically said: "If there is something from the terminal read it.  Otherwise skip reading anything."  As you can't type that fast (time between pressing the enter key and typing the 1st digit of the age), the program continued on to the end.

If you are a beginning programmer, I would recommend you do all your own parsing and ASCII to integer conversion.  It is good experience.  As your programs become more complex, you can benefit from using libraries to keep you programs "clean" and their purpose obvious.

no I have stated "while (Serial.available()==0);" just after I asked to enter age. therefore shouldn't the program halt there until I type something? I mean at that point the program is supposed to stop there and wait  till I type something am i right? At times, it take the new line charactor ASCII 10 as age. I do not understand how it takes a new line charactor as age because I am clearing the buffer by reading before asking for age.

Thank you. I am sort of a moderate level I believe. but I really want to know whats happening behind. THats the reason I want to make this work. but its not as easy as it sounds I guess.

After this line: "// clear the UART Buffer",  try changing  "  while (Serial.available()==1){    " to "  while (Serial.available() >= 1){    "

Im sorry it did not work. I tried it. same result.

the question is just after Serial.println ("What is your age?"); I have included the line
while (Serial.available()==0). Therefore it cannot proceed if the buffer is empty. Aparently reading it didnt make it empty.

Stack Exchange isn't a good place to debug code.  But, going on, my next suggestion is to print out the character read after each and every read.  I would use "Serial.print(temp, HEX)" so everything (including control characters) are printed as hex number.  Then look them up in the ASCII table to find their exact meaning.  You might have some other bugs but once you get this working you can spot and fix them.

Sorry I didnt know that. I would not post this type of questions here again.
Okay. I will do that and see.
thank you a lot for your help

I made the code work as per your advice. Unfortunately, it requires a weird delay and I do not understand why. Please telll me if you could understand already why it is so.

Let us continue this discussion in chat.


text:
Sampling frequency
I am an undergraduate student at a public university in Maryland. I am currently doing a project with an arduino and I came across a problem that I could not figure out after several days of researching. Regarding my project, I am trying to collect 6 data (acceleration and gyration in x,y,z) from an accelerometer/gyroscope sensor at a desired constant rate (trying to make it 1000 Hz, so about 1000 sets of the 6 data per second) into a SD card. However, I could not make the arduino do this; I am able to collect the data, but not at a constant sampling frequency of 1000 Hz. Could someone help me set the sampling frequency at 1000 Hz please. Here are some of the information of the sensors and arduino I am using:

Arduino nano
MPU-6050 gy-521 accelerometer/gyroscope - http://playground.arduino.cc/Main/MPU-6050
SD card reader - http://www.aliexpress.com/item/SD-Card-Reader-Module-for-Arduino-ARM-Read-and-Write-Free-shipping/526750081.html?spm=2114.12010108.1000023.4.JkncUu&spm=2114.12010108.1000023.4.JkncUu

Also, I have posted my code. Thank you in advance for the help.
My code:
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
unsigned long time;
#include "I2Cdev.h"
#include "MPU6050.h"
MPU6050 accelgyro;
#define OUTPUT_READABLE_ACCELGYRO

const int sdcard = 7;
int num;
int16_t ax,ay,az,gx,gy,gz;
LiquidCrystal lcd(10, 9, 5, 4, 3, 2); //12 is 10 and 11 is 9

void setup()
{
    Serial.begin(115200);
    lcd.begin(16, 2);
    pinMode(8, INPUT_PULLUP);
    Serial.print("Initializing SD card...");
    if (!SD.begin(sdcard))
    {
        Serial.println("initialization failed!");
        return;
    }
    Serial.println("initialization done.");
    accelgyro.initialize();
}

void loop()
{
    lcd.setCursor(0,0);
    lcd.print("Push button");
    lcd.setCursor(0,1);
    lcd.print("to start");
    int sensorVal = digitalRead(8);
    if (sensorVal == 0)
    {
        delay(500);
        num = 1;
        collect();
    }
}

void collect()
{
    File myFile = SD.open("test.txt",FILE_WRITE);
    myFile.println("Begin:");
    myFile.print("x-axis  ");
    myFile.print("y-axis  ");
    myFile.print("z-axis ");
    myFile.print("\n");

    Serial.println("Begin:");
    Serial.print("x-axis: ");
    Serial.print("\t");
    Serial.print("y-axis: ");
    Serial.print("\t");
    Serial.print("z-axis: ");
    Serial.print("\n");

    if(myFile)
    {
        while (num == 1)
        {
            accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
            lcd.setCursor(0,0);
            lcd.print((double) ax/16384*9.81);
            lcd.setCursor(7,0);
            lcd.print((double) ay/16384*9.81);
            lcd.setCursor(0,1);
            lcd.print((double) az/16384*9.81);
            lcd.setCursor(7,1);
            lcd.print(time);

            time = millis();

            Serial.print("Time: ");
            Serial.println(time);
            Serial.print(ax);
            Serial.print("\t");
            Serial.print((double) ax/16384*9.81);
            Serial.print("\t");
            Serial.print(ay);
            Serial.print("\t");
            Serial.print((double) ay/16384*9.81);
            Serial.print("\t");
            Serial.print(az);
            Serial.print("\t");
            Serial.print((double) az/16384*9.81);
            Serial.print("\n");

            myFile.print("Time: ");
            myFile.println(time);
            myFile.print(ax);
            myFile.print("\t");
            myFile.print(ay);
            myFile.print("\t");
            myFile.println(az);

            int sensorVal = digitalRead(8);
            if(sensorVal == 0)
            {
                delay(500);
                num = 0;
                Serial.println("STOPPED");
                myFile.println("STOPPED");
                Serial.print("\n");
                myFile.print("\n");
                myFile.close();
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Stopped");
                delay(2000);
            }
        }
    }
}

What is connected to D8? If you want to collect data at 1kHz, why are you delaying for 500ms each loop? Have you heard of interrupts?

If you want people to analyse your code try formatting it properly and including some comments. This is good for your own future analysis as well.

Sounds ambitious! Have you measured how long does it take to do the measurement, update the lcd, and write out all data to an SD card?

uint128_t : I am only delaying at the very beginning and at the very end when the button is clicked to stop the while loop that reads the data from the sensor.

milliways: sorry, I will make sure I do that next time

Gee Bee : even if i just measure them, wouldn't they just do it at their default frequencies? i should have been more specific with my question before, is there a way to change the default frequency to make it whatever you desire? is the only way to do this with a delay?

You will not remotely be able to achieve 1000 Hz operation of a loop which performs so many time consuming operations.  Even leaving out the possibility of substantial delay on some attempts to write to the SD card, your serial output alone could never keep up.  A 115200 baud serial implementation can only transmit on the order of 11 thousand characters per second, which means there is only time for 11 or so per your hoped interval, and you produce far more than that.  (And buffering is irrelevant if you are continually producing data faster than you can transmit it)
If you want to achieve a high sampling rate, you are going to have to pare the code down to the bare minimum required functionality and analytically or experimentally determine how much time each portion takes.
If you want regular samples, you are also going to have to study the rate at which the sensor produces them - you may actually want to consider letting the sensor be the timing master, and simply record the samples as they become available.
And you will need to study the SD card writing process and determine its possible worst-case delay.  To overcome that, you may find that you have to collect your samples in an interrupt and use most of your available RAM to buffer them across the worst-case card delays.  If the data you need to store is only a few megabytes, you might consider an SPI flash for its more deterministic timing behavior.


text:
reading pwm signal doesn't work correctly
my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.
i ran this code on the arduino:
#define Pin 3

int pwm_value;

void setup() {
  pinMode(Pin, INPUT);
  Serial.begin(9700);
}

void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);
}

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.
I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.
I have realy no idea to solve that. Can you please help me?
Thank you!

Are you sure it's PWM and not PPM?

Did you also connect the GND of the Arduino to the GND of the receiver? In case you did you could try using pinMode(pin, INPUT_PULLUP);

check if the problem is the fact you have set 9700 baud rate on your sketch while the commonly used 9600 is supported from arduino IDE.

I slightly modified your code and it works for me. Check if this works for you:
#define Pin 3
#define Source 5
unsigned long  pwm_value;

void setup() {
    pinMode(Source,OUTPUT);
    pinMode(Pin, INPUT);
    Serial.begin(9600);
    analogWrite(Source,500);
}

void loop() {
    pwm_value = pulseIn(Pin, HIGH);
    Serial.println(pwm_value);

}

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).
About getting signal on floating pins
Getting a signal on a floating pin is normal.
When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!

the serial connection over 9700 was the problem. with 9600 everything worked just fine. Thanks so much for the answer!


text:
I put some defines into a .h file, and get errors
I'll post the whole code if you really need to see it, but my question is pretty simple.
In my sketch I define some parameters:
#define SSID "Kaywinnet"
#define PASSWORD "806194edb8"
#define MQTT_SERVER { 192, 168, 1, 124 }

And, the sketch compiles just fine.
But, rather than putting my net parameters into every sketch, I wanted to just use a .h file so that if something changes, I only have to change it once.
Here's the problem.  When I put these three lines into a .h file, I get an error when the first parameter is used in the sketch:
expected primary-expression before '.' token

Here is the code where I use the value:
//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

The error is on the .ssid= line.
So, why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??
Here's the ino file:
    /*****

  Projects/esp8266/MQTT nodes/light2.ino
  10/3/2017- Clone of studio.ino

  IDE settings:
  Board: "Generic 8266 Module"
  Flash Mode: "DOUT"

*****/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESPHelper.h>

//#include <Kaywinnet.h>
#define SSID "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

//#define toggle    //Using toggle switch.
#define pushbutton    //Using pushbutton switch

#define NODENAME "light2"
const char *cmdTopic =  NODENAME "/light";
const char *statusTopic = NODENAME "/light/status";
const char *connectName =  NODENAME "lights";
#define OTAPASSWORD "xxxx"

//Defaults to DHCP, if you want a static IP, configure below
//#define STATIC_IP
#ifdef STATIC_IP
IPAddress ip(192, 168, 1, 50);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
#endif

//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

//Declare an object of class WiFiClient
WiFiClient esplight2;
PubSubClient client(esplight2);

#define esp8266-01    //Either sonoff or esp8266-01

//Define the GPIO pins on the 8266-01
#ifdef esp8266-01
const int buttonPin = 0;    //GPIO0
const int relayPin = 2;     //GPIO2
#endif

#ifdef Sonoff
const int buttonPin = 0;     //GPIO0
const int extraPin = 14;
const int ledPin = 13;
const int relayPin = 12;
const bool ledOFF = HIGH;
const bool ledON = LOW;
#endif

int switchVal = 0;
int currentVal = 0;
bool relayState;
String payLoad;

// * *************** RelayControl, remember the state ***************
//
void RelayControl(bool state) {
  //Serial.print("relayState: ");
  //Serial.println(relayState);

  digitalWrite(relayPin, state ? HIGH : LOW);
  relayState = state;

  //Feedback over MQTT
  if (relayState) {
    client.publish(statusTopic, "on");    //Tell Node Red about the current status
    Serial.println(String(statusTopic) + "= on.");
  } else {
    client.publish(statusTopic, "off");
    Serial.println(String(statusTopic) + "= off.");
  }
  Serial.println();
}

void timeLoop (long int startMillis, long int interval) { // the delay function
  while (millis() - startMillis < interval) {}
}

/*
 * ************** blink the LED ************************
   We assume the LED is on after connecting.
*/
void blinkLED() {
#ifdef esp8266-01
  return;   //No led on the esp to blink..
#endif
#ifdef Sonoff
  digitalWrite(ledPin, ledOFF);
  delay(500);
  digitalWrite(ledPin, ledON);
#endif
}

/*
 * ******************** set up WiFi ****************
*/
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(SSID);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}

/*
 * *************** MQTT callback ********************
*/
void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");

  String messageTemp;
  for (int i = 0; i < length; i++) {
    //Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  messageTemp.trim();            // trim the white space off the string

  Serial.println(messageTemp);

  // If a message is received with the topic 'cmdTopic', check if the message is either on or off.
  if (topic == cmdTopic) {
    if (messageTemp == "on") {
      Serial.println("Light2 is ON");
      RelayControl(HIGH);
      blinkLED();

    }
    else if (messageTemp == "off") {
      Serial.println("Light2 is OFF");
      RelayControl(LOW);
      blinkLED();

    }
  }
}

/*
 * **************** Connect to MQTT broker **************
   This functions reconnects your ESP8266 to the MQTT broker and subscribes to topics.
*/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(connectName)) {
      Serial.println("connected");
#ifdef Sonoff
      digitalWrite(ledPin, ledON);
#endif
      // Subscribe or resubscribe to a topic
      client.subscribe(cmdTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

/*
 * *************** SETUP ********************
*/
void setup() {

  //espHelper
  myESP.OTA_enable();
  myESP.OTA_setPassword(OTAPASSWORD);
  myESP.OTA_setHostname(NODENAME);
  myESP.begin();

#ifdef Sonoff
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledOFF);     //The Sonoff LED is low-true.  This starts with it off.
#endif

  pinMode(relayPin, OUTPUT);
  RelayControl(LOW);  //Start with the heat off

  pinMode(buttonPin, INPUT_PULLUP);

  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  //Save the initial switch position.
  currentVal = digitalRead(buttonPin);

  Serial.print("cmdTopic= ");
  Serial.println((String(cmdTopic)));
  Serial.print("statusTopic= ");
  Serial.println((String(statusTopic)));
  Serial.print("connectName= ");
  Serial.println((String(connectName)));
  Serial.println("...............");
}

/*
 * *************** LOOP ***********
   The loop function begins with making sure that your ESP is connected to the broker.
*/
void loop() {
  myESP.loop();  //run the loop() method - this keeps the network services running

  if (!client.connected()) {
    reconnect();
  }
  if (!client.loop())
    client.connect(connectName);

#ifdef toggle
  /*
   * ******** Toggle switch attached **********
  */
  //Has the switch position changed from the last loop?
  //If yes, the save the new setting and toggle the heat.
  switchVal = digitalRead(buttonPin);
  if (switchVal != currentVal) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal != currentVal) {   //debounce
      currentVal = switchVal;
      relayState = !relayState;
      RelayControl(relayState);

      /*    //For simultaneous control over MQTT
            if(relayState){
                client.publish("studio/heat","on");
              }else{
                client.publish("worksgop/light","off");
              }
      */

    }
  }
#endif

#ifdef pushbutton
  /*
   * ***** Momentary pushbuttom switch attached *******
  */
  //When the switch input goes low, toggle the light.
  switchVal = digitalRead(buttonPin);
  if (switchVal == LOW) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal == LOW) {   //debounce
      relayState = !relayState;
      RelayControl(relayState);
      delay(1000);            //Delay if the button is held too long.
    }
  }
#endif

  yield();
}

And here is Kaywinnet.h
#define ssid "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

Did you #include the .h file in your sketch before you used the macros?

Majenko-  Yes.  The include line is at the same place in he sketch as the internal defines.  If I uncomment the include and comment the three defines right under it, compile fails.

Why is SSID lowercased in Kaywinnet.h?

Yeti and per1234 found the error - DOH! Thanks...

Here's the ino file:
  ...
#define SSID "Kaywinnet"

...
  .ssid = SSID,

...
  And here is Kaywinnet.h
#define ssid "Kaywinnet"

...
  The error is on the .ssid= line.

C++ is case sensitive. You changed the macro name from SSID to ssid when you moved the defines to the .h file.

why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??

easy:
1) go back to the non-fancy version where you put the strings back into the code.
2) get it to compile.
3) then extract the strings to macros.
by going through that, you will know precisely the mistakes you made.

You lost me on this one.  What do you mean to 'extract the strings to macros'?


text:
Constantly read analog in in SWITCH/CASE setup
I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.
CODE HAS BEEN UPDATED
//-------------------------------------------------------
// BUTTON AND POT - TEST
// KNOWN ISSUE - POT ONLY TAKES ON READING
// vonderasche
// 7/28/2016
//-------------------------------------------------------

const int BUTTON_PIN = 9;
const int LED_PIN = 3;
const unsigned long DEBOUNCE_TIME = 50;

int val = 0;
int pot = 0;

int state = 0;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

bool button_press()
{
    static bool last_state;
    static unsigned long last_state_change;
    unsigned long now = millis();

    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

void loop()
{

    unsigned long now = millis();
    static enum { OFF, ON, POT } state;

    if (button_press()) switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        state = ON;
        Serial.println(state);
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        state = POT;
        Serial.println(state);
        break;
    case POT:
        Serial.println(state);
        int Mode = button_press();
        while (val < 1023) {
            val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            state = OFF;
            break;
        }
    }
}

The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.
So, you might do something like this:
case POT:
int Mode = digitalRead(BUTTONPIN);
while(Mode == LOW) {
    val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        state = OFF;
        break;
        Mode = digitalRead(BUTTONPIN);
    }
}

If you want to use the debounce, do something like this:
static enum { OFF, ON, POT } state;
unsigned long now = millis();
int x = 0;

while (x == 0) {
    switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        if (button_press()) {
        state = ON;
        }
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        if (button_press()) {
        state = POT;
        }
        break;
    case POT:
        val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        if (button_press()) {
        state = OFF;
        }
        break;
    }
}

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.

Is there another option for the while condition. I have my button press setup as a boolean function for debouncing.

You could potentially put the while switch statement in a loop. That way, it would read the whole code every time it goes through the loop, so if you press down the push button, it will switch the state, and if you don't press the push button, it will just do the same state again. That way, it WILL change the LED based on the potentiometer every time you adjust it, AND it ill work with a software debounce. Hope this helps!

Im sorry can you please be more specific. Maybe some pseudo code.

I've edited my post. Please tell me if that works, and if it doesn't, can you post the code for "button_press()" so I can understand the code better.

i updated the post with the full code I have. It was interesting to see the use of a while statement. The LED would turn on but it wouldn't cycle thru the different states when the button was pressed.

authors: ธรัช กมลธนิศร


text:
Do I need 3 voltage dividers to control ESP8266
I am buying an ESP8266 and the plan is to control it serially from an Arduino. I am going to use a voltage divider(Using a voltage divider is temporary and I know the cons of using voltage dividers).
I calculated out the values of the voltage divider and I am going to use 220 ohm and 440 ohm value resistors to get 3.3 volts and 250 ma from the Arduino 5v pin so I can power vcc and ch_pd on the ESP8266.
The question is do I need to use a separate voltage divider to connect Arduino TX to ESP8266 RX and Arduino RX to ESP8266 TX. Or will it be safe to connect RX and TX directly to Arduino RX and TX.
Honestly I am extremely new to this and I don't even know if I am going at this right. If I am tell me.

You have to convert Arduino's 5V TX so that it'd be compatible with ESP's 3.3V RX.

You're planning on using a voltage divider to provide 250mA current? How much voltage would be dropped across a 220 Ohm resistor with 250mA drawn through it? 55 Volts.

For ESP 3.3V power supply, I'd recommend a distinct 3.3V regulated supply.
Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.
Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.
You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or Vin directly if your UNO is powered through the DC power jack, not USB)
For ESP RX a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a MOSFET based level shifter:

The advantages of this circuit are:

it has the fastest switching response time
it can work in both directions (3.3V -> 5V and 5V -> 3.3V)

You can also buy some cheap ready-made breakouts using this circuit and offering several level shifters.
For ESP TX, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).

The RX pin is 5V tolerant (at least it is on all of my boards!) and almost certainly your arduino will recognize 3V as logic high for the TX pin. So you don't really need any level conversions there (no other pin is 5V tolerant).
Are you sure your ESP8266 board doesn't already have a 5V to 3V3 regulator? I've never seen one!

Yes there are some development boards by adafruit that do come with voltage regulators. I am going to be writing a blog on how low cost arduino can be in the future maybe so I am not going to be using dev boards. I will say that the dev boards are worth  the extra $8 though for anyone reading this.


text:
Why send my Arduino sometime Hex and sometimes the wrong?
Hi i have an Arduino mega 2560 i send data from the Arduino over USB to PC. That works when i test a simple Serial.print("Hello"); but that is not that what i need. I send a timestamp as a longe Value and the databyte as a short Value. When i send the timestamp as BIN like that:
      //Initialisisation

const int RX = 0;
const int TX = 1;
const int RX1 = 19;
const int TX1 = 18;
unsigned long currentMillis;

void setup()
{
  pinMode(RX, INPUT);   //Readpin for USB
  pinMode(TX, OUTPUT);  //Writepin for USB
  pinMode(RX1, INPUT);  //Readpin for bus
  pinMode(TX1, OUTPUT); //Writepin for für bus

  Serial.begin(38400);   //open interface for USB
  Serial1.begin(4800);   //open interface for bus

  while (!Serial & !Serial1 &! Serial2)
  {
    ;//wait for serial port connect.
  }
}

void loop()
{
  //Ask if the timestamp over 8 hours, when yes,
  //send the time to the pc and reset currentMillis.
  currentMillis = millis();
  if (currentMillis >= 28800000)  //milli() 8 hours is a 4 byte  timestamp 28.800.000 millisec.
  {
    unsigned long timestamp = currentMillis;
    sendBinaryTime(timestamp);
    currentMillis = 0;
  }//end if

  //if the businterface available, read a byte
  //and send it with the timestamp to the PC.
  //If the businterface not available send an error.
  //short incomingByte = Serial1.read();
  //sendBinaryValue(incomingByte);
  if(Serial1.available()>0) //if the bus (serial1) available?
    {
      short incomingByte = Serial1.read(); //read the next byte from _rx_buffer
      sendBinaryValue(incomingByte);
      sendBinaryTime(currentMillis);   //sendBinary send a long over the bus
    }//end if
}//end Loop()

//Methods for sending long values

void sendBinaryValue(short incomingByte)
  {
    int temp = (incomingByte & 0xFF00)>>8;
    Serial.println(temp, HEX);
    temp = (incomingByte & 0x00FF);
    Serial.println(temp, HEX);
    return;
  }

void sendBinaryTime(unsigned long currentMillis)//send milliseconds after every byte
{
  int temp = (currentMillis & 0xFF000000)>>24; //send 16 bit of the low value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x00FF0000)>>16;      //send 16 bit of the high value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x0000FF00)>>8;
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x000000FF);
  Serial.print(temp, BIN);
  return;
}

All is fine i haven´t any error. But i want the timestamp as DEC so i have changed the code to:
       void sendBinaryValue(short incomingByte)
 {
   int temp = (incomingByte & 0xFF00)>>8;
   Serial.println(temp, HEX);
   temp = (incomingByte & 0x00FF);
   Serial.println(temp, HEX);
   return;
 }

void sendBinaryTime(unsigned long currentMillis)
{
 int temp = (currentMillis & 0xFF000000)>>24;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x00FF0000)>>16;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x0000FF00)>>8;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x000000FF);
 Serial.print(temp, DEC);
 return;
}

Now when i look on the serial monitor i get an error.
Here you can see it:

I send an A as ASCII sign that must be Hex 41 and i receive a Hex 5 but why? When i send the timestamp as BIN i get the 41 and haven´t any problem.
I hope someone can help me with friendly wishes sniffi

Please, post a testable code, with setup() and loop(), so we can reproduce your problem. I tried the obvious and got “41”, as expected, which proves you have a problem in a piece of code you are not showing to us. How do you expect us to help you with that?

I have fix it, i think perhapes it is an already known problem.

I have found several problems with your program, although they may not
be related with your primary problem:
while (!Serial & !Serial1 &! Serial2)

You mean while (!Serial || !Serial1 || !Serial2), although this is
only useful with virtual serial ports, like on the Leonardo. On the
mega, all of these ports are real hardware ports.
void sendBinaryValue(short incomingByte)

The way you name the parameter is misleading: a short is not a byte,
it's two bytes.
int temp = (incomingByte & 0xFF00)>>8;

You are bit-shifting a signed number, which is going to do a sign
extension. This is probably not what you want.
Serial.print(temp, DEC);

You are printing several numbers one after the other with no separator.
This is going to cause ambiguities: you cannot know whether "345" means
"3 45" or "34 5".
Finally, I don't get the purpose of your functions. Why don't you just
print the numbers like this?
Serial.println(incomingByte, HEX);
Serial.println(currentMillis);

Ok i have delete the while(!Serial & !Serial1 & !Serial2) . I have changed the ringbuffer to 16bit (my short) because i want handle flags at the high byte. Can i send a short and a long over Serial.print?

Yes, you can print() numbers from 8 to 32 bits, signed or unsigned.

Ok i have change all now the bug is fixed thanks for all


text:
How can i receive data from Mega2560 on PC with Visual C#
How can i receive the data from my Arduino Mega 2560 with Visual C# on my PC.
I send a short databyte (2 bytes) and a timestamp (4 bytes) over USB to PC
//initialization

const int RX = 0;
const int TX = 1;

void setup(){

pinMode(RX, INPUT);   //readpin for USB
pinMode(TX, OUTPUT);  //writepin for USB
...

Serial.begin(28800);   //open interface
}

 //loop()

 Serial.print(incomingByte, BIN); //sending databyte

 sendBinary(currentMillis);   //send timestamp

//method for timestamp

void sendBinary(long currnetMillis)
 {
  int temp = currentMillis&0xFFFF;  //16 bit of the low-byte
  sendBinary(temp);
  temp = currentMillis >> 16;       //16 bit of the high-byte
  sendBinary(temp);
 }

I have surched in the internet for an example but i didn´t find a good. So i ask here what ist the best way with Visual Studio C# to receive the incoming data?
An example code will be nice because i´m a beginner and didn´t understand the jargon.
With frindly wishes sniffi

I haven't tried the code below, but it should point you in the right direction.
All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

Open Visual Studio, create a C# command line project.
Paste this code inside main()
    System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
    try
    {
        while (true)
        {
            int readData = port.ReadByte();
            System.Console.WriteLine("Read {0} from the port", readData);
        }
    }
    catch(Exception)  // Press CTRL-C to exit.
    {
    }
    port.Close();

Compile the code and run it.


text:
Use doorbell output (12VDC) to power arduino?
Not sure if this is possible, but could I use my existing doorbell setup to power an Arduino? I'd also like to preserve the existing chime's functionality either through the existing button or triggering it through the arduino.
My doorbell chime is made by Nicor and its input is 120VAC, but outputs 12VDC. This seems to be a very unconventional setup, but I've confirmed its output with a multimeter (it's also printed on the chime itself). The chime is very similar to this: http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU (only difference I can see is the output). The 12V line runs to my front door where it's connected to a light up button. Here is a picture of the button's circuitry: https://i.sstatic.net/YsSu0.jpg
What I'd like to do is use the chime's 12VDC output to power the arduino so I don't have to rely on another power source or batteries. I will be adding smart features to the doorbell via the arduino, but my main hangup is getting power to the arduino. I've tried connecting the doorbell wires to VIN and ground, which successfully powers on the Arduino, but it also triggers the chime. It appears closing the circuit triggers the chime to play.
Is this possible to do?

Connecting 12v to an Arduino's VCC pin would likely destroy it.  You want the Vin pin.  But you also don't want to be in series with the buzzer - the voltage drop from that second mistake might be the only reason your Arduino still functions.

Sorry, I actually meant the VIN pin.

The button board looks amazingly complex for "just a button". As others have noted, it may just carry signal-level voltage, not enough to power the Arduino. Plus, if pressing the button closes a circuit, the +12V might disappear at the exact time when you want it - when you want to hear a chime.

This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.
The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.
Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.
The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.
So what's the easiest way to accomplish your task?
Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.
You need to replace/augment the LED on the ringer with the Arduino. The 2.2k R19 could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.
The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit  pulls all the current out from under the LED, just as it will an MCU in the same slot.
You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.
So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.
Good luck; sounds like a fun project and a good challenge.
EDIT:
I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...

You need to find the transformer for your doorbell system and take the power from there. It seems like somehow you are using the signal wires for the door bell instead of the power wires.
The door bell transformer should/could be in a utility room, closet, by your heating and air unit. once you find that look at the output of the transformer. I know some are AC 12 volts, and I feel like that arduino will not like that...

The transformer is part of the chime and it's connected to mains power. The chime takes 120VAC in and outputs 12VDC. If you take a look at the amazon listing (http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU), you can kind of see what the wiring looks like (see the other images).

So get a little 12Volt or 9volt transformer and wire it into the mains at the door chime. I bet you have one laying around the house!

But the problem is that I am unable to run additional wires so I'd like to use what's already there

I understood that you were putting the arduino by the door chime, if so You wouldn't be running any extra wires.

Sorry, I'd actually like to have it by the button

The problem with putting your Arduino across the button circuit (if this is a conventional bell and button) is that the Arduino will be powered off during the button press. That may not be ideal....

Hmm, Put a capacitor and diode isolate the arduino and cap, the capacitor will keep the arduino on for the brief second the connection is broken?

Even ignoring the button press for now, how could I power the arduino without triggering the chime?

Now that I think about it, The 12volt you are getting at the chime is a signal wire, probably carries very low current. I feel like the doorbell is a NC or normally closed switch. When its pressed it breaks the circuit telling the chime to chime, when hooking the arduino up the chime detects a voltage drop and triggers the chime... although the chime is sending power to light the doorbell...? It's hard telling with out being able to look at it and try somethings.
When you hook the arduino up is the chime ringing constantly or something?
If it just does it once, whats the issue?

The chime is actually triggered constantly when hooked up to the arduino, which is why that hasn't worked for me.

You want the Arduino at the bell itself? Sorry but I don't see any way. Either run power to this area, or relocate the Arduino to where there IS sufficient power (and once you do that, think about why you wanted the Arduino "at" the the actual button, so you can consider possible solutions).

If your extra features only need to sense the button press, then your arduino can go at the chime and use the 12V source that also powers the chime.
You put an opti-isolator's led side in series with either leads of the button loop. A digital input with high pull-up can read the state of the detector side of the opto-isolator.
This assumes that your extra features do not include providing some kind of visual or auditory output at the button. But remember that just because you want to read the button state, you need not detect it at the button physically--just electrically.


text:
Transfer serial data to struct variable in Arduino
I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.
struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

static testing_var const test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.
void loop() {

  if (Serial.available()>0) {
    var1 = Serial.read();
}

I need to pass this var1 as the variable pt in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.
EDIT:
I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:
void setPlain(struct PlainText *myPlain, const char* thePlain){
    myPlain -> plaintext = the Plain;
   }

Then, in the loop, I use:
  if (Serial.available()>0) {
    var1 = Serial.read();
    setPlain(&PlainText, var1)
}

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

You need to design and implement a protocol to encapsulate the data.