text:
How to make data sent by Python (via serial connection) wait for Arduino to finish current task?
I am trying to make my Arduino micro-controller and my Mac talk together, and I have created a functional serial connection. My computer is sending data to my Arduino, and my Arduino is sending a 1 when it is ready to receive a new piece of data.
I have created an if-else statement (Python script below), which is either sending a new line of data to the Arduino or waiting for the Arduino to be ready for receiving a new line of data.
The problem is that ser.read() in the first part of the Python script always returns 1, which means that the script is sending the individual data lines faster than the Arduino connected stepper motors can possible react.
In the Arduino script you can see that I am sending the state-status in the first line of the serialEvent() function, which in my world should let the Arduino finish its job, before a new "task" is coming. However, it is for some reason not working. Can anybody help me out here?
Python script
import os
import time
import serial

# Name of csv file with drawing coordinates
csvFile = "scaled_coordinates.csv"

# Create serial connection
ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

wd = os.getcwd()
myFile = open(wd + "/coordinates/" + csvFile)

state = '1'

while True: # Exits when there is no more lines to read
    print "test"

    if state == '0': # Wait for Arduino to be ready
        state = ser.read()

    elif state == '1': # Send one more line to Arduino
        line = myFile.readline()
        if not line:
            break
        print line
        ser.write(line)
        state = '0' # Wait for Arduino before reading next line

ser.close
myFile.close

Arduino loop function
void loop() {
  serialEvent(); // Call the serial function
  if (coord_complete) {
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
    coord_complete = false;
  }

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

Arduino serialEvent function
void serialEvent() {
  // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
  if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
  }

  while (Serial.available() && coord_complete == false) {
    char ch = Serial.read(); // Get new character
    // EDIT : REMOVE THIS LINE //
    Serial.print(ch);

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

    // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;  // Finish coord_string
      x_new = atoi(coord_string);    // Convert to integer
      x_complete = true;             // Change x_complete to true
      index = 0;                     // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string
    // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      //Serial.write('0');
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }

    // Ends while-loop when true
    coord_complete = x_complete * y_complete;
  }
}

Edit
I have changed a bit in the first few lines of the serialEvent function (See comments).
Here is a sample of the text file I am reading from:
239,275;
1100,275;
300,400;
200,400;
200,300;

I'm voting to close this question as off-topic because you have cross posted it to stack overflow and answered it there. http://stackoverflow.com/questions/33805986/how-to-make-data-sent-by-python-via-serial-connection-wait-for-arduino-to-fini/33853784

If I'm getting things right, your program fails in the above:
when you send the first message in python, you set state = 0. In
  arduino you enter the serialEvent function and while is triggered. You
  get the first char and send it through Serial.print (but this char
  will be send to python!!!). For the sake of example let's say the
  first char you get from cvs is '2'. At this point let's hold on a
  sec and look what happens in python. State was '0' but as you have
  used in arduino Serial.print(ch); now state will be updated with
  '2'. This will cause no more triggers of the if-else statements in
  python.
edit:
By now, and also as a debug, add this lines at your code:
if state == '0': # Wait for Arduino to be ready
    state = ser.read()
    if state != '1':
        print "state: " + state
        state = '0'

However if csv file contains '1's values this will also cause a
  problem. Do you really need that Serial.print(ch) in arduino?

EDIT The new version since comments
Basically if you are trying to do things before new coordinates, you have to do things in a sequential way. You only ask for info after making all the moves. This is the code I've used to test.
Note: I had to adapt your code because was missing the complete arduino code to test it. So I kinda simulated the motor moving etc with delays. Please adapt to your original code
#include <string.h>

bool coord_complete = false;
byte stepper1_disToGo = 0, stepper2_disToGo = 0;
// debug things
int led = 13;
bool led_state = true, x_complete, y_complete;
char coord_string[256];
int index = 0, x_new = 0, y_new = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  memset(&coord_string, 0, sizeof(coord_string));
}

void loop() {

  serialData(); //ask and process more data

  /*
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
  */
  delay(2000); //replace to simulate actions
  stepper1_disToGo = 10;
  stepper2_disToGo = 10;
  coord_complete = false;

  // replaced to simulate
  /*
    // Stay in while loop until steppermotors is done
    while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
    }
  */
  while ((stepper1_disToGo != 0) || (stepper2_disToGo != 0)) {
    stepper1_disToGo --;
    stepper2_disToGo --;
    digitalWrite(led, led_state); // is moving!!!!
    delay(100);
    led_state = !led_state;
  }
}

/*
   you try to use the serialEvent  but the structure of
   your code and the verifications make it act like sequential.
   If you only want to make things after all steps are done there
   is no need for the serialEvent function
*/
void serialData() {
  /*
     This will never be false because you are stuck in the while

    // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
    if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
    }
  */
  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

The structure of your loop should be:

ask for data and wait for it
Read data and parse it
Calculate steps needed
move servos till new positions
repeat

this should be your new code more or less if no mistakes were made because can't really test this version (is missing the variables declarations setup, includes etc...)
void loop() {

  serialData(); //ask and process more data
  // Steps to move from currrent to new point
  target1 = steps(x_current, y_current, x_new, y_new, 1);
  target2 = steps(x_current, y_current, x_new, y_new, 2);

  // Start moving
  stepper1.move(target1);
  stepper2.move(target2);

  // Update current position
  x_current = x_new;
  y_current = y_new;

  // Reset variables
  x_complete = false;
  y_complete = false;
  coord_complete = false;

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

void serialData() {

  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  // we got info!!!
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

It makes sense to delete the Serial.print(ch) but it is still not working for me. I guess I have to clear the serial buffer or something. I can see that the my python code somehow is getting stucked in the if-statement.

@Christoffer can you edit your post and had a few lines of your csv file for testing? thanks.

sure. I have changed the post now.

@Christoffer Hope it helps now to achieve your goals. If it still doesn't work, supply the complete arduino code. However, i'd like to suggest you to parse the csv in python and send coordinates to arduino by using two strings or using a binary data. The easiest away should be using strings and Serial.parseInt() in arduino for each string.

I figured out that the solution was to clear the serial buffer and implement a minor delay. The solution is here: http://stackoverflow.com/questions/33805986/how-to-make-data-sent-by-python-via-serial-connection-wait-for-arduino-to-fini/33853784#33853784

@Christoffer OK, glad you make it work :)


text:
UART Software Serial - Syncing two different sensors with start and stop bytes
I'm using 2 SRF02 sensors on the same Arduino board to attempt to have the transmitter only pulse the 40 KHz wave, while the receiver will be only taking a fake range, i.e. picking up a reading based on another transmission.
I've been using SoftwareSerial and need to know how to synchronize the time for the receiver to know when the transmitter sent the data. What I found is that I'm going to have to do this using start and stop bytes to set them in the same cycle.
How can I do this?
This is my current code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd) {
  mySerial.write(address);
  //set the address of SRF02(factory default is 0)
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
  mySerial.write(cmd);
  //send the command to SRF02
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
}
void setup(void) {
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}

void loop(void) {
  unsigned int reading;
  SendCmd(0x00,0x5C);
  //Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
  delay(70);
  //time for SRF02 to measure the range
  SendCmd(0x02,0x57);
  //Get Fake Range at Address 0x02 - receiver
  delay(10);
  //wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
  if(mySerial.available()>=2) {
    //if two bytes were received
    reading = mySerial.read()<<8;
    //receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    reading |= mySerial.read();
    // receive low byte as lower 8 bits
    Serial.print(reading);
    // print the reading
    Serial.println("cm");
    //Serial.println("Time Sent: ");
    //Serial.print(T_sent);
  }
  delay(250);
  // wait a bit since people have to read the output :)
}

Your code bit
SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
delay(70);//time for SRF02 to measure the range
SendCmd(0x02,0x57); //Get Fake Range at Address 0x02 - receiver

will send a sound burst, delay 70 ms, then start listening for the burst, which by then will have traveled around 24 meters and probably be no longer audible.
You should instead start the fake range listener immediately after sending the burst.  The general idea for one approach is as follows:

Record time (eg, t1=micros();)
Send burst (eg, SendCmd(0,0x5C);)
Record time (eg, t2=micros();)
Listen for burst (eg, SendCmd(2,0x58); // Get microseconds)
Wait 70 ms, then read microseconds result t3
Compute corrected total microseconds, tm=t3+t2-t1
Convert microseconds to cm

Note use of command 0x58 instead of 0x57 to get microseconds instead of cm.  If you used 0x57, instead of adding t2-t1 to t3, you would add t2-t1 microseconds-converted-to-cm to a cm reading.
The reason for the computation tm=t3+t2-t1 is that the second command is issued about t2-t1 microseconds later than the first command, as explained in the next paragraph.
There is an unknown delay d1 between when t1 is recorded and when the first SRF02 acts; and there is an unknown delay d2 between when t2 is recorded and when the second SRF02 begins listening.  The correct amount to add to t3 is t2+d2-(t1+d1), which is t2-t1 if d1 equals d2, a more-or-less plausible assumption.  If your experiments reveal a constant error, add a small constant offset to compensate.
I doubt you should have the delayMicroseconds(100); statements in SendCmd(), and would recommend getting the code to work ok, then see if it still works ok when you take them out.  The delay(10); is unnecessary if you rewrite your 2-character-wait correctly (ie as a while rather than an if), and the delay(70); is unnecessary if you start conversion with command 0x5A,  “Fake Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete” and then properly wait for two characters to arrive, instead of a blind wait followed by a test if they've arrrived.

unsigned int reading;
unsigned long t1=micros();
SendCmd(0, 0x5C);//send pulse with transmitter
unsigned long t2=micros();
SendCmd(2, 0x58);//return value in microseconds
  delay(70);//time for SRF02 to measure the range //SendCmd(0x02,0x5E);
  unsigned long t3 = SendCmd(2,0x5E);
  unsigned long tm = t3+t2-t1;

 unsigned int reading;
  unsigned long t1=micros();
  SendCmd(0, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();
  SendCmd(2, 0x58);//return value in microseconds

  delay(70);//time for SRF02 to measure the range
  //SendCmd(0x02,0x5E);
  unsigned long t3 = SendCmd(2,0x5E);
  unsigned long tm = t3+t2-t1;

Hey thanks for the input. When I created t3, I get an error saying void value not ignored as ought to be.

After you do SendCmd(2,0x5E);, you need to read the serial reply from 2nd SRF02, and store that 16-bit value into t3.

i dont know how to store the value returned, it tells me the the void value not ignored as ought to be. am i not supposed to use t3 = SendCmd(2, 0x5E) to store ?

SendCmd() doesn't return a non-void value, so you aren't supposed to say something = SendCmd(...).  Instead, just issue the SendCmd(2, 0x5E), then read 2 serial bytes and combine into 16-bit value, like you did for reading

This is my updated code based on your suggestions, jwpat, although I did not understand your comment with delay(70); not being needed if I start conversion with (2,0x5A).
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
  mySerial.write(cmd);//send the command to SRF02
  //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(0, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x58);//listen for pulse
  //SendCmd(2, 0x5A);
  delay(70);//time for SRF02 to measure the range
  //SendCmd(0x02,0x5E);
  SendCmd(2,0x5E);//Get range

 while(mySerial.available()>=2)//if two bytes were received
  {
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(Dist); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  }
  delay(250); // wait a bit since people have to read the output :)
}

After running this code my results keep being the following values regardless of me shifting the distance between the sensors:
72cm

Instead of while(mySerial.available()>=2) { t3 = mySerial.read()<<8; ... as you have, say  while(mySerial.available() < 2) {};  t3 = mySerial.read()<<8;. That is, you need to stall until two characters are available from the 5E command, and then read them.  Probably what's happening now is that first time in, since mySerial.available()>=2 is false, your while doesn't run; so you return from loop() and then loop() and steps on the ongoing conversion, messing it up; eventually two characters arrive; and this happens over and over the same way.  Note, you should edit this stuff into Q

I made the changes and what i now get is a value of 2302cm in my Serial Monitor

Perhaps you can edit your question and put current code into it.  2302cm is about the distance one expects for a 70 ms delay.  If you are indeed now using while(mySerial.available() < 2) {}; to stall until 2 chars are available you should be able to remove the 70 ms delay and change from 58 command to 5A command.  (Adding "answers" that are really part of the question is a no-no. Edit the question instead.)

gotcha, i just dont have enough space for the new code

also what did you mean by edit into Q?

I meant, edit the items you've been putting into "answers" into the Question.  By "not enough space for the new code", are you referring to the IDE, the target Arduino, or this post?

I was talking about the comments for my replies, but i got it thanks a lot for your help. I updated the new code in another question.

hey I would really appreciate f you can look at my code once more on the new post or even just point me in the right direction. link: http://arduino.stackexchange.com/questions/18123/uart-software-serial-syncing-two-sensors-updated

source: Stack Exchange

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

sort: votes


text:
Arduino Uno WiFi Rev2 "no socket available"
My Uno WiFi Rev2 outputs on the serial monitor after ~30 min "no socket available". Until that point everything works just fine, my requests run as expected. I use the .flush() and .stop() commands, as in several forums suggested. In the following my really messy code (sorry for that, but it's not optimized and only for testing some stuff):

#include <SPI.h>
#include <WiFiNINA.h>

//W-Lan Data
int status = WL_IDLE_STATUS;
char ssid[] = "**********";
char pass[] = "**********";

bool jsonBool;
char jsonChar;
int curlyBracket;
String jsonCode;
String json;

IPAddress HueBridge(10, 0, 0, 30);

WiFiClient WHTTP;

void setup() {
  while (status != WL_CONNECTED) {
    status = WiFi.begin(ssid, pass);
    delay(500);
  }
}

void loop() {
  jsonProcessing();
  httpRequest();

  bar1();

  delay(55);
}

void httpRequest() {
  WHTTP.flush();
  WHTTP.stop();
  if(WHTTP.connect(HueBridge, 80)) {
    WHTTP.println("GET /api/*************/lights/ HTTP/1.1");
    WHTTP.println("Host: 10.0.0.30");
    WHTTP.println("Connection: close");
    WHTTP.println();
  }
}

void jsonProcessing() {
  while(WHTTP.connected()) {
    if(WHTTP.available()) {
      curlyBracket = 7;
      while(WHTTP.available()) {
        jsonChar = WHTTP.read();
        if((jsonChar == '{') && (curlyBracket == 7)) {
          jsonBool = true;
          curlyBracket = 0;
        }
        if(jsonChar == '}') {
          jsonBool = false;
          jsonCode = jsonCode + '}';
          curlyBracket++;
        }
        if(jsonBool) {
          jsonCode = jsonCode + jsonChar;
        }
      }
    }
    WHTTP.flush();
    WHTTP.stop();
  }
  jsonBool = false;

  //processing jsonCode variable

  jsonCode = "";
}

void bar1() {
  //calculating stuff
}

If anything is unclear feel free to ask. This is not the whole code, just the WiFi relevant parts.
The main structure is copied from here https://www.arduino.cc/en/Tutorial/WiFiNINAWiFiWebClientRepeating
so it theoretically should work.
Thanks in advance.

do you have the newest version of the firmware and library?

@Juraj yes, I updated both yesterday but had no improvement.

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


text:
Generating variable frequency of 3 phase SPWM
I got a sample of program to generate 3 phase SPWM from this Controlling output frequency of 3 Phase SPWM Inverter. As far as I understood, the frequency generated is constant. My question is how can I make it a variable frequency generated? I am using Arduino mega right now.

I've edited the code in that post to my latest code! I suggest you take a look at the signal on proteus scope, but first try to filter all signals with 1K ohm resistor and 0.37uF capacitor connected in series. Put your scope probe at the end of resistor. Hope that will help!

can i know what is the max fequency you used in the code? because i'm still trying simulate the code and cant capture the frequency generated. Hope you can clarify me a bit.

It's around 0 - 200Hz. I've checked using my inverter circuit and Oscilloscope.

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


text:
Ethernet shield reconnection problem after power cut
I am using arduino mega and this ethernet shield. Everyting is okey and connection is good. however, the device does not connect to the internet again after a power cut. if I press the reset manually it works again. Also arduino mega is plug-in with uninterruptible power supply but modem is not connected uninterruptible power supply, modem turns off if power cut. I am starting this method each time when sending data from docs. I think it is enought to reconnect to internet and getting IP. what should I do for reconnect internet after power cut

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);

  ThingSpeak.begin(client);  // Initialize ThingSpeak

try to use static IP address or 'reserve' the DHCP assigned IP address on router

other problem could be that your sketch gets next connection if the one doesn't connect and all 8 connections are then in waiting state.

Interesting, I have the same problem. Never bothered to solve it because it's a rare occurence and I figured it had to do with interaction between the Arduino and the PowerlineEthernet device I'm using.

@Juraj I don't believe static ip will solve my problem. because each time I am checking internet connection and getting IP.

add #define PRINT_DEBUG_MESSAGES before #include "ThingSpeak.h" to see if it connects


text:
Arduino Uno SD card fails to initialize
I'm not sure why my SD card fails to initialize when I run my code (below) but works when I just check to see if it is being read by the Arduino with the CardInfo code in the Arduino library.
The data logger is from Adafruit and the sensor that I'm connecting to it is a MaxBotix one. I've tried reseting the SD card and the Arduino and switching out the SD card. When I verify the code in Arduino there are no issues, so I'm not entirely sure why this isn't working. Any help is greatly appreciated.
UPDATES:
I was able to get it to initalize the SD card by moving
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

after the
Serial.println().

but now it's not saving data or even creating a new document and it's not printing data as a new line. Things went south when I added the averaging portion of the code because before then it was printing data as a new line and the SD card initializing.
My time is extremely wrong I'm getting a date like 2165/165/165 165:165:85.
1
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
/*
The goal of this code is to collect 10 data points a minute, average them, and store them to an SD card
*/
#define LOG_INTERVAL 6000 // mills between entries (reduce to take more/faster data)
// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0// Wait for serial input in setup()
RTC_DS1307 RTC; // define the Real Time Clock object
// The analog pin that connect to the sensor
const int ultrasonicPin = A0; // declare the input pin for the ultrasonic sensor
unsigned long time;
// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;
const int numReadings = 10; //define number of samples to keep track of
int readings[numReadings]; //the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
// the logging file
File logfile;

void error(char *str) {
  Serial.print("error: ");
  Serial.println(str);
  // red LED indicates error
  //digitalWrite(redLEDpin, HIGH);
  while(1);
}

void setup() {
  Serial.begin(9600);
  Serial.println();
  //initialize all the readings to 0:
  for(int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
    #if WAIT_TO_START
      Serial.println("Type any character to start");
      while (!Serial.available());
    #endif //WAIT_TO_START
    // initialize the SD card
    Serial.print("Initializing SD card...");
    // make sure that the default chip select pin is set to
    // output, even if you don't use it:
    pinMode(10, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
      error("Card failed, or not present");
    }
    Serial.println("card initialized.");
    // create a new file
    char filename[] = "LOGGER00.CSV";
    for (uint8_t i = 0; i < 100; i++) {
      filename[6] = i/10 + '0';
      filename[7] = i%10 + '0';
      if (! SD.exists(filename)) {
        // only open a new file if it doesn't exist
        logfile = SD.open(filename, FILE_WRITE);
        break;  // leave the loop!
      }
    }
    if (!logfile) {
      error("couldnt create file");
    }
    Serial.print("Logging to: ");
    Serial.println(filename);
    // connect to RTC
    Wire.begin();
    if (!RTC.begin()) {
      logfile.println("RTC failed");
      #if ECHO_TO_SERIAL
        Serial.println("RTC failed");
      #endif  //ECHO_TO_SERIAL
    }
    logfile.println("millis,stamp,datetime,depth");
    #if ECHO_TO_SERIAL
      Serial.println("millis,stamp,datetime,depth");
    #endif //ECHO_TO_SERIAL
    // If you want to set the aref to something other than 5v
    analogReference(EXTERNAL);
  }
}

void loop() {
  DateTime now;
  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m); // milliseconds since start
  logfile.print(", ");
  #if ECHO_TO_SERIAL
    Serial.print(m); // milliseconds since start
    Serial.print(", ");
  #endif
  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
  #if ECHO_TO_SERIAL
    Serial.print(now.unixtime()); // seconds since 1/1/1970
    Serial.print(", ");
    Serial.print('"');
    Serial.print(now.year(), DEC);
    Serial.print("/");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.day(), DEC);
    Serial.print(" ");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.print('"');
  #endif //ECHO_TO_SERIAL
  analogRead(ultrasonicPin);
  delay(10);
  int value = analogRead(ultrasonicPin);
  for (int i=0; i < 50; i++) {
    if (millis() < 60000*(++i)) {
      // subtract the last reading:
      total = total - readings[readIndex];
      //read from the sensor:
      readings[readIndex] = analogRead(ultrasonicPin);
      // add the reading to the total:
      total = total + readings[readIndex];
      //advance to the next position in the array:
      readIndex = readIndex + 1;
      //if we're at the end of the array
      if (readIndex >= numReadings) {
        //wrap around to the beginning:
        readIndex = 0;
      }
      //calculate the average:
      average = total / numReadings;
      delay(6000);
    } else if (millis() == 60000*(++i)) {
      logfile.print(",");
      logfile.print(average);
      Serial.print("Ultrasonic Reading = ");
      Serial.println(average);
      //Serial.print("Time: ");
      //time = millis();
      //prints time since program started
      //Serial.println(time);
      //wait a second so as not to send massive amounts of data
      // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
      // which uses a bunch of power and takes time
      if ((millis() - syncTime) < SYNC_INTERVAL) return;
      syncTime = millis();
      delay(100);
    }
  }
}
// this reads in cm

You cannot initialize the SD card more than once.  Pull this code out of the for loop:
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

Put it after the Serial.println().

Make a new sketch that initialize the SD Card and write data to it, without loop.
If this doesn't works,maybe the sdcard is damage.
So, as shash-dev says,initialize the SD card before you start the for cicle and after the Serial.printl().

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


text:
How to read data from an NI DAQ?
I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are other sensors for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?
Some other points:

I also have Arduino Ethernet Shield, if required.
The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices. Is it possible to install this driver on Arduino?
I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

The main answer for your question is already given by Majenko, and is "no". These protocols are much more complicated than you can think, so no way.
However, if I correctly interpret your point 2 (which is The final goal is to have logged data synced so out of the box solutions are also acceptable for me), you don't need to do this. Just use your PC (or raspberry) to collect all the data and make a synchronization inside it. For instance, connect the arduino to the PC via bluetooth, add a serial connection in the labview program and then send all the data the arduino records to the serial peripheral; you will get all the infos in the labview program.
If for any reason this is not possible, you can use a common signal to sync the acquisitions. For instance, when you start the measurements you let the DAQ generate a long pulse (let's say 100ms), then every second or minute it will generate a shorter pulse (let's say 10ms); the arduino also records this signal, so you will have a way to sync acquisitions. Or you can do the opposite: the arduino generates and the DAQ records.
To sum up, the arduino is not capable of doing what you request, but maybe what you need is not what you asked for...

well,  unfortunately raspberry pi is not an option either. NI doesn't even support common linux distros! it is not easy for me to work on a windows machine, specially in the lab/workshop.  The main issue is the garbage sensor I'm using. I strongly discourage anybody from using the type of sensor I have.

@Foad I see your frustration here ;) in any case, if rPI is not supported then arduino, which is MUCH more limited, is totally unsuitable. Try syncing through other means (the signals I mentioned in the answer, or the serial interface). I think that you can implement everything in labview. Or, if you have the drivers for x86 linux, try putting linux on any x86 PC you have; if you succeed, search any x86 single board computer to replace the PC . For instance, wikipedia has a page with comparisons [...]

of SBCs; check the ones which have a x86 or x86-64 processor. Or, in the end, you can try to hijack the protocol between the sensor and the DAQ, and see if you can make a library in arduino to listen to that sensor..

Unlikely.
First you would need a USB shield to be able to plug it in.
Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.

I added more info to the post. How about Arduino boards which are more like a Rasperry pi and we can install a Linux on. and then install the driver offered by NI?

Those are compiled for arm and Debian. The Yun which is the only Arduino I know that runs Linux runs on MIPS And openwrt, so no, definitely not. Just use a pi.

Well, That's plan B, The issue with Pi is that as far as I know it doesn't have analogue or PWM data read and write which I use to read data from other sensors and control some valves.

It has PWM (it's fast enough to do it in software anyway, which is how I do it), and just add an external ADC over SPI or I2C. There's "hats" (what we call shields) that have ADC on them.

I asked my question on Rasperry py SO: https://raspberrypi.stackexchange.com/questions/71614/how-to-read-data-from-an-ni-daq-usb-6259


text:
micro arduino and w5100
I would like to ask if it is possible and how to connect the following module
http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH_DefaultDomain_0&hash=item3aab3dbff6
to the arduino micro
I found some pin layouts but only for Leonardo or Ethernet shield, Uno etc.
Also I've choosen this model because it can be programmed directly in arduino using Sockets API

While it would have been nice to see your research rather then having to spend some time finding this information myself, I did find this http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/ from what I can see this should be compatible to any arduino as long as it has 3 volt pin and 4 i/o pins. While the arduino micro doesn't have a 3v3 pin, as far as I know, that shouldn't be an issue as long as you can drop the voltage from the 5 volt pin, this module should work for you.

actually I though the same but wanted to be sure and ask.
Maybe someone knew more!


text:
Arduino sending data over MAX485
I would like to introduce myself as a student from Czech Republic. I'm currently I'm working on a Meteostation project.
I've got Arduino set up, with plenty of weather sensors, as well as WH1080 sensors connected.
Right now, I'm only able to read the data via serial port on computer with Arduino IDE or show it on my 20*4 display.
Because of the distance between source of data and recipient of data, wireless data transfer is unsuitable for my application.
I found these MAX 485 modules on eBay for cheap:

I quickly got 2 pieces, as well as 5v-3.3v logic level shifter, as I was concerned about different logics on Raspi. I don't know much about Raspi and their pins, as the only thing I ever used with them was DS3231 real time clock module.
Now, the thing I'm trying to achieve is this - I want to be running a bunch of sensors at roof of our house, and have the Arduino send the data to Raspi over the rs485 (on request? as the sensor loop would be like 10-15min so maybe communicate on interrupt?)
What I'm planning to do with the data on the raspi would be running a software like WeeWx or wfrog to process them and possibly render a local website, that I could make public as port forwarding (I have public IP).
However, there are few questions I have, hopefully its not too much to ask

How would the wiring look like? I was unable to find any dumb-proof tutorial online, as I don't know whether or how to use the logic level shifter.
If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?
If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

Thanks in advance for any kind of response, as this is at the moment causing me headaches, as I'm unable to do this on my own. I don't expect anyone to do all the work for me, maybe just point me in the right direction.

My mind boggled a bit reading your question. Maybe this page about RS485 will help you get started.

You didn't get any answers when you asked the same question on raspberrypi.stackexchange.com because the question is too broad.

I also were a beginner (umm, in the previous century, literally). I found it is more rewarding to start with projects which have up to one unknown part, since that is something one can learn. However starting a project as a beginner with so many unknown factors can hardly lead to a success.

May I ask: what makes you think the range is too extended for wireless links, but not for RS485? Given an appropriate transmitter and antenna combination, wireless links can extend over miles inbetween nodes.

@Martin K, have any of these answers helped you?

How would the wiring look like? I was unable to find any dumb-proof
  tutorial online.

I found this tutorial to be pretty usefull.
There really isn't much to it, I suggest trying a short range before going full range.
It's a "half duplex bus system" the ends of the bus should have a "end termination resistor", usually 120Ohms, between the A and B signal.
Since it's half duplex, the Pi and Arduino can't talk at the same time.
You'll have to pull the DE and RE pins high when you want to transmit (and keep them low for receiving).
Basic sketch would be something like:
#define TXEnablePin 13

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

void loop(){
  String data = "";
  Unsigned int sensorValue1 = Sensor.getValue();
  Unsigned int sensorValue2 = Sensor.getValue();
  data += str(sensorValue1) + ":" + str(sensorValue2) + ";\r\n";
  send(data);
  delay(10000);
}

void send(String data){
  digitalWrite(TXEnablePin,HIGH);
  delay(1);
  Serial.send(data);
  Serial.flush();//Wait for everything to be transmitted, before disabling transmitter.
  digitalWrite(TXEnablePin,LOW);
}

I don't know whether or how to use the logic level shifter.

These things are pretty straight forward. You should actually be able to figure it out yourself (given you have the power of the internet).
LV to 3.3V of Pi
GND to GND of Pi
GND to GND of Arduino
HV to 5V of Arduino
Then, whatever 5V signal you want to connect to HVx and whatever 3.3V signal you want to connect to LVx
Example:
Arduino-TX -> HV1
Arduino-RX -> HV2
Pi-TX -> LV2
Pi-RX -> LV1

If I can read the data over serial port, would it be just a plain text
  (as shown on PC in Arduino ide serial monitor), or has each value its
  address that I could then easily accessing to a variable then being
  used to process the weather data?

It would be ASCII (plain text) if you send strings.
You could make different types of requests.
Like; If you send: "Temperature" to the Arduino, it will respond with: "TEMP:10" or something.
But the easiest thing would be to send all values of all sensors in a combined string every 10 seconds or so. And let the Raspberry Pi unpack that string.

If I'm completely wrong in something, or there's some completely
  different way how these things are being done by more experienced
  people, I'd love to hear some suggestions.

I think it's pretty good that you actually already know of the existence of RS485 and why you'd want to use it.
But I also feel that you feel a little uncomfortable with the project as it is.
It's important to handle problems one by one, to avoid getting overrun by problems.
Try to make it working over (short) USB first. Then try a short RS485 link and eventually try a long RS485 link. You can then more easily spot where the problem is. Use facts from multiple tutorials, to boost the confidence you have in the system ;). It may just work if you wire it as said. If it doesn't work, you can always post a question.
If possible, it may also be worthwhile to follow some tutorials on Arduino (get a starter kit and book with tutorial projects?). Within these tutorials they give examples of problems and show what there is to solve them. Without throwing yourself into a dark pit of a project.

Friend, i try same  method (like your) but not working (about of digitalWrite(TXEnablePin,LOW);)!   Auto-Direction is best idea, use an 74HC14 IC with an Capacitor (capacitor == Serial.flush()). Communication never allowed an internal delay, cos missing bits or skip bits position.

I succeeded at about 500kbit speed with hardware delay(PCI-RS232).

Ok, one simple step which might help you to get going.
The no-brainer
There is an RS232 link between your Arduino and the PC. (Of course, it might not be a real RS232, it can be the USB, and over the USB the PC sees the arduino as a serial port what you can write from Arduino. So far so good.
You can easily extend the USB with passive expansion cords, as well as with active USB expansion cords, easily getting an extra 30m. Of course it is not an RS485, but comes at no further thinking.
The RS485
RS485 is basically a clever variant of a serial port, which allows you sending your data over up to 1.5km twisted wire pair.

get an USB-RS485 adapter for your PC or Raspberry side. These are widely available, e.g. http://usb-rs485.eu/?cms=eu85xl&gclid=CjwKEAjwq6m3BRCP7IfMq6Oo9gESJACRc0bNkhzTSQU3wUW_5tebRZDD-zAqflcvcFOq9V8nmZIlRhoCvyPw_wcB
get an RS485 driver chip such as MAX485 (I prefer LTC485, that works straight from 5V, costs like 1 EUR) for your Arduino side.
you'll need two ardino pins - serial read and write, therefore you may prefer an Arduio supporting also Serial1 - so a TxD and RxD wire from the board. When you write to this serial port instead of Serial, the data comes out from the TxD pin of the Ardino panel, instead of going to the PC via the USB.
now, if you can have a simplex system - i.e. only Arduino talks to the PC or Raspberry - then it makes your life a lot easier. Then you only need the TxD from the Arduino, and connect it to the DI of the RS485 driver chip. Connect RE and DE and connect both of them to 5V. That's all.
if you want a two direction communication between the Arduino and PC, that makes things a bit more complicated. RS485 is a half-duplex thing, so your Arduino needs to control when it wants to talk to the line or listen. For that you need a separate pin to be connected to RE and DE together. Put it to 1 to write, 0 to read from the RS485 lines. Note that Arduino is having write buffers, so it will be a little tricky to know exactly when to switch back to listening after writing. Solving this properly worths of a separate question :)
connect A of the MAX485/LTC485 to the A of the USB RS485 interface. Connect B to B. Now you're almost there... Connect also GND of the Arduino to the GND of the RS485 interface. (Although you can see many examples on the net of using only two wires, A and B, in the real life you either need a common GND, or an additional overvoltage protection circuit made of four zener diodes to have it running well forever.)

you're advised of using a twisted pair wire for A and B. This is not a requirement though, you can go well with any wires. One of my friend used a garden fence made of metal as A, and the soil as B, which worked well for 50 meters :) However for 1.5Mbit, 1km you definitely need a twisted pair
Note that if you go with long wires (over 50 meter) and higher speed (over 9600 bps), you need to have line-terminator resistors. This means a simple 120 ohm resistor connected between A and B on the PC side. Another 120 ohm resistor to be connected at A and B on the MAX 485 side - so the two farthest end of the long communication wire.

Now the software side:

The USB RS485 interface will look like just a regular serial port for the PC (e.g. COM9) or Raspberry. So you can read and write the RS485 bus just like a standard com port.
On the Arduino side, you can use the Serial1 (or equal) to write data out to the MAX485, which drives the wires.
I suggest again to start with a simplex system, i.e. Arduino only writes data, the PC just reads data.
Note that you have to use exactly the same bit rate on Arduino as well as on the PC side. Watch out when you open up the terminal.

“you may prefer an Arduino supporting also Serial1”: This is only needed if you want to keep Serial for debugging. Otherwise there is no problem in using Serial for the RS-485 link: the data goes both to the USB link and the TX pin on the board. “it will be a little tricky to know exactly when to switch back to listening after writing”: That's what Serial.flush() is for. It does get tricky if you want to do it non-blocking: I would test UCSR0A & _BV(TXC0).


text:
How do I use Sound Sensor LM393 + Speaker in Arduino
I have this voice sensor:

I need to know how bytes pass through soundsensor into arduino and get this bytes and put out in a speaker.
I read on the net a Lib PCM thats converts chars in voices, but how do I extract bytes from sound sensor in analog-in?

The board you have, if the same in the image has a D0 and A0, and from powers of deduction the D0 will give you true and false according to a set trigger level. You would also probably look what that library you mention uses as a sensor or the general way people use it and also how it expects signal information from a sensor.

for an example, after coding connect a bulb,and clap then the bulb wile turn on.

Oh, the joys of buying something off the Internet with no datasheet, no part number and no clue how to use it. And then expecting somebody else to tell you how it works.
That module looks like a KY-038, made by Keyes. No guarantees, though, because I'm not telepathic.
Bytes don't "pass through the soundsensor". Bytes don't pass anywhere, in fact. That board has an analogue output, A0, which is the amplified audio sensed by the microphone. It swings between 0 and 5 volts, and is 2.5V when no sound is being picked up. The board also has a digital output, D0, which is active-low when the intensity of the sound picked up by the microphone exceeds a thershold. I have no idea what this threshold is or what volume it represents, or if it can be changed.
Have a look at the pages on AnalogRead() for information on how to convert analogue audio to a digital signal.
I don't know what you mean by "a Lib PCM thats converts chars in voices" - 'chars' as in the C-type chars or do you mean literal 'characters from a voice', i.e. speech recognition? I cannot tell if you have misunderstood something or there's an unfortunate translation coincidence which is confusing matters.

thanks for this help, now i understand. sorry for something, english not is my natural language.

I guarantee you speak English better than I can speak any other language, so there is no need to apologise. I was keen to help but I didn't know how. If you have any other questions please ask.

Thanks man, i undestood that analog reads and then i will use this to put the sound out. I will try soon. But for my project i will have to change arduino to raspberry. I will need a camera module and my uno dont have enough pins and clock power haha, but thanks you a lot.

This post was awhile ago, but I wanted to offer some more definitive info for others like myself who were trying to identify it. What you have there is the Keyes KY-037 "high-sensitivity voice sensor" module. Mine came with the Inland Arduino Uno RFID Learning Kit.
Apparently the KY-037 and the KY-038 are the same except the KY-037 has a higher sensitivity microphone. I could not find any specs to quantify what that sensitivity difference is, however. Both have a LM393 voltage comparator on the board. The same Arduino code ought to work for both.
Here are a few helpful links I found, some also showing a bunch of the other Keyes modules and how to use them:
http://linksprite.com/wiki/index.php5?title=Advanced_Sensors_Kit_for_Arduino
http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Lectures/022-Basic%20Definitions%20and%20Concepts%20Sensors%20and%20Actiators%202013-10-10.pdf  (Page/slide 40)
http://tkkrlab.nl/wiki/Arduino_37_sensors


text:
How to convert voltage to current from ACS712-20A?
I've been used the ACS712-20A to measure the current flow. Actually I used LIFA program (LabVIEW interface for Arduino).
I used this equation:
current = ((analog read)-2.5 )/ 0.1
But I am still not sure with the result.
Any suggestion?

According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.
So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula
i = (Vadc - 2.5) × 10

Or for milliamps,
i = (Vadc - 2.5) × 10000

If you are measuring a DC current that is then all well and good.  However, if you are measuring an AC current things get considerably more complex.
To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage.  To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values.  You can then subtract the minimum from the maximum to give you the peak-to-peak voltage.  That can then give you the peak-to-peak current.
From that you can then calculate the RMS current.

Wouldnt the peak voltage alone suffice?

@TisteAndii If the voltage swings precisely around 0V then yes.


text:
Arduino UNO with CD4510 Counter
I am new in Arduino but I have experience in electronics.
I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.

A display driver, like the MAX7219, can allow you to control up to eight 7-segment displays (or 64 individual LEDs) while only using two pins on the Uno.

Thanks but I only have a limited amount of budget. Can you at least send me any link or tutorial that teaches how to use Arduino UNO and CD4510 counter? :)

What do you mean by  “countdown timer” ?  Do you mean a circuit that waits for some interval to elapse?  Why do you need any displays?  (Ie just use an LED to signal when done waiting)

I need to show the time left that is why I need displays :)

What's a typical range you will count down?  What frequency do counted events occur at?  How many digits does the display need?  Please edit question with answers to those items.  You can drive (eg) four 7-segment displays by using four bits to turn on high-side power and seven bits to pull down low-side segments -- ie just need some resistors, some transistors, four displays, and Arduino -- no need for CD4510 if input frequency isn't too high.  (I was assuming, due to your fixation on CD4510, that you have some external event to count; if just timing seconds, that's even simpler.)

I can use CD4510 to make a countdown timer, I just need to connect CLOCK INPUT to the Digital IO pins located in the arduino microcontroller and use pulse with modulation (pwm) for the code

The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.
You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?

Ok, but i'm not sure if my local electronic shop has it :)) also I will use CD4511 to decode the binary and display it, i will only use the microcontroller for UP/DOWN and for CLOCKINPUT :))

@MiguelLorenzo: Why do you keep wanting to use extra chips to do what the Arduino can do on its own, or vice versa?

Because arduino uno has limited ports only and I would use multiple timers  and multiple sensors for my device :))

In that case see Is there a way to have more than 14 Output pins on arduino?


text:
Can anyone help me figure out why this buffer is overflowing? (Updated)
This should be fairly straightforward, but there must be something I'm not understanding about buffers.
I have serial data coming in to my Mega via Zigbee. I'm sending a string just like this: ~-0.6016800, where ~ is my unique starting delimiter and my end delimiter is a carriage return \n. I'm sure it's coming through the zigbee correctly, because I can see my string show up looking good in XCTU when I plug the zigbee into the PC. Here is my code:
const int numChars = 15;
char incoming[numChars];

static boolean Receiving = false;
static byte ndx = 0;
char startMarker = '~';
char endMarker = '\n';
byte K;
bool allreceived = false;

void Get() {
    memset(incoming, NULL, strlen(incoming));
    while (allreceived == false) {
        if (Serial.available() > 0) {
            K = Serial.read();
            if (Receiving == true) {
                if (K != endMarker) {
                    incoming[ndx] = K;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars-1;
                    }
                }
                else {
                    incoming[ndx] = '\0'; // terminate the string
                    Receiving = false;
                    ndx = 0;
                    allreceived = true;
                }
            }
            else if (K == startMarker) {
                Receiving = true;
                ndx = 0;
            }
        }
    }
}

So somehow my buffer is overflowing or something, no matter how big I make it. I see the array start off as I expect it for the first few characters, then it turns into unintelligible characters. I think part of the problem might be that the serial data is coming through at a different rate or something, because I can see my starting delimiter ~ on my LCD screen in the middle of my array. The way it's set up, I should never be able to see my start delimiter unless I miss my end delimiter without ending the array. (Note- I've tried different unique end delimiters too, but this seems to work just the same)
Any ideas on what might be causing this??
EDIT: NOW TRYING THIS CODE- I'm still having the buffer overflow, and I'd be really grateful if someone could take a look.
Sending code:
void PayloadSendit(void) {

Payload[0] = '~';  //1 char unique start

if (outFormat == 0) {
    Payload[1] = '0';
    Payload[2] = '$';  //spacer
    strcat(Payload, stringval); //5 char for hashmarks
}
else {
    Payload[1] = '1';
    strcat(Payload, stringvalin);  //6 char for inch
}
if (dotpos <= 99) {
    Payload[8] = '@';  //spacer
    char dotpos2[2];
    sprintf(dotpos2, "%i", dotpos);
    strcat(Payload, dotpos2);    //2 char
}
else {
    char dotpos3[3];
    sprintf(dotpos3, "%i", dotpos);
    strcat(Payload, dotpos3);   //3 char ///////////////////////////
}

Payload[11] = '0';  //1 char for "no errors" code
Payload[12] = '*';  //1 char end delimiter
Serial.println(Payload);
Serial.flush();
memset(Payload, '\0', 13);

}
Receiving code:
  void Get2() {
    memset(Payload, '\0', bufsize);
    while (allreceived == false) {
        int K = Serial.read();
        switch (K) {
        case -1: // Nothing to read
            break;

        case '~': // Starting a new string
            Receiving = true;
            break;

        default: // Any other characters.
            break;

        }
        if (Receiving) {
            for (int i = 0; i <= 10; i++) {
                Payload[i] = Serial.read();
            }
            if (Serial.read() == '*') {
                Receiving = false;
                allreceived = true;
            }
            else { memset(Payload, '\0', bufsize); }  //destroy array if end delimiter not where it should be
        }

    }
}

My guess is this line:
memset(incoming, NULL, strlen(incoming));

When "incoming" hasn't yet been cleared, what is the length of it? It's whatever it counts up until the first '\0' character - and where is that character on the first run through? Who knows.
Instead you should memset the size of the buffer, not the number of non-NULL characters in the buffer:
memset(incoming, NULL, numChars);

However, that is a pointless operation, since you are storing a C string and (should be) properly terminating it, so it really doesn't matter what is in the array to begin with since you are just overwriting it anyway. So you can completely lose that whole function call.
You might like to re-write your receiving routine to use a switch/case construct instead of ifs and elses - it'll be much easier to follow:
#define EVER ;;

const int numChars = 15;
char buffer[numChars];

void Get() {
    int pos = 0;
    bool receiving = false;

    for (EVER) {
        int K = Serial.read();
        switch(K) {
            case -1: // Nothing to read
                break;

            case '\n': // Got the end of the string.
                if (receiving) return; // We have a valid string.
                pos = 0; // Reset pointer to start of buffer
                break;

            case '~': // Starting a new string
                pos = 0;
                receiving = true;
                break;

            default: // Any other characters.
                if (receiving) {
                    if (pos < numChars-2) {
                        buffer[pos++] = K;
                        buffer[pos] = 0;
                    }
                }
                break;
        }
    }
}

I know its Friday afternoon but I'm sure you don't mean buffer[pos] = K; buffer[pos++] = 0; because that will overwrite K with 0.   pos++ should be ++pos.

@Matt Actually you are wrong :P I did mean pos++, just not in that place ;) It should have been buffer[pos++] = K; buffer[pos] = 0;

Thanks for your eyeballs, guys. @ Majenko, I totally agree with you on the memset thing. It was just something I tried on for size. And I like the switch case structure. That one is new to me. Kinda reminds me of LabView (I'm not one of those who disparages LabView).
I'm going to try out this method, but I've tried quite a few and I have my doubts. I still have a sneaking suspicion that I'm actually missing serial bytes somehow and not catching my end delimiter even though my while loop is terminating.
My main evidence is that I'm seeing bytes that only exist outside of my sent string.

@ Majenko, I implemented a version of what you shared with me. I had tailored my payload so that I always have the same number of characters, so I'm trying a for loop to collect the characters and then checking to make sure the next character is my end delimiter. I don't think I'm using any functions that add a terminating null, so I don't think that matters. However, I'm still getting a huge buffer overflow.
Again, I can verify my character array via Zigbee connected to PC. I'll post my sending code and then my receiving code in an update now.


text:
What's up with my code?
Sorry if my code isn't well written or anything because I'm new to Arduino and coding in C, but what is wrong with my code?
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val = 0)
  {
    pinMode(LED, HIGH);
  }
  else(val > 0)
  {
    pinMode(LED, LOW);
  }
}

Please help the helpers help you by asking a more specific question than "what's up..." If you need help with compiler errors, say so, and report at least some of the message and the location of it. If you're asking about run-time behavior, please state what you expected it to do and what it actually did. You can get lots of good help here but please try to direct your readers to the specific problem. The guide to asking good questions has a lot of good suggestions.

else(){} looks like bad syntax.

Your IF statement, you're using: (val = 0), and I believe you meant (val == 0).
Also, you're using else(val > 0) and else doesn't need any argument. So the fixed code should look like:
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val == LOW)
  {
    pinMode(LED, HIGH);
  }
  else
  {
    pinMode(LED, LOW);
  }
}


text:
Arduino as switch for external circuit
I am trying to use the Arduino as a switch for an external circuit.
I first thought about using a shift register, but this wont allow me to switch the external circuit. Here is a little sketch of what I want to do :
So basically I got this external circuit with a 3 position switch. And I want to replace this manual switch with an Arduino so it can be controlled by a PC, without influencing the other circuits Voltage or Amps...
Any suggestions ?

Is it important for the switch to have 3 positions? Would it matter if two contacts can be on at the same time? Why use a shift register if you only need 3 positions, you could use 3 I/O pins? What voltage/current will go through?

I will start off with three but it should be expandable to lets say 32 or more later on. Temporarily it wouldnt matter if two were on at the same time, but after some time only one has to be on. What do you mean with 3 I/O Pins ? Voltage will be max 1V at 100mA max.

Since you are only switching low voltage, you could probably use a transistor instead of a more expensive relay.

Yeah but transistors would influence the currents and th voltage in case of not being opened

Three-position makes it a little more tricky than normal.
The simplest option, though depending on what the circuit is, maybe not the safest option, is to use three relays.

Switch only one relay on and it is the same as having the three-position switch in that same state. Switch that relay off and switch another on and you have changed the switch position.
The danger is that this arrangement can have two or even three relays on at once, something that can't happen with a switch.  Also how you do the switching could be critical. Switch one relay off, then add a delay before switching the next one on, so that the previous one has a chance to switch off properly first. That way you avoid having two on at once. Of course, depending on what it is you're switching, that may or may not be an issue.
The safest option, though the hardest to create, would be to physically move the existing switch with, say, a servo motor. Without knowing a little more about the mechanics of your switch I can't really advise more on this option.

Hello, yes it needs to be at least 3... It should even be expandable to 32 later on. I tought about relays but it seems to be a hassle to get them powered and controlled by the arduino? We cant have anpther power source....

The use 5V relays and use the Arduino as the power source. Tip: buy pre-built relay modules with the driver circuit built in. They are cheap enough, and you can get them in up to 8 relays to a board.

Also about the relays being on at once isnt too bad temporarily. Te mechanical switch has to go away so no way to use a servo. This sounds like a good way to go. Do you know any prebuilt modules easily available in europe / germany?

There are plenty made in china on eBay. Cheap, easy to get, etc. SainSmart are a common maker of them. They have a good selection.

Ok perfect thanks, one more question, will the relay have an influence on the current and voltage tat flows trough my external circuit ?

No they are just the same as a switch.

Thanks ! I went for a sainsmart 8 channel relay module. It says 5V , can this be powered soley by the arduino ? There is always only one switch open at the time

Yep, that's the ideal choice.


text:
Pro Micro and LilyPad USB
Is there a difference between Pro Micro 8MHz 3.3V and LilyPad USB bootloaders?
Both are based on 32U4 running at 8 MHz.

I'm curious as to what issues you're having with them exactly...

I am not sure which one to pick for my application.

Pick whichever one has the form factor that is most appropriate, then replace the firmware with any you like.

Thank you. I learned form Sparkfun that they modified these bootloaders reset. Their document which explains this change is available from this link: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/32U4Note.pdf Where can I get a version of these bootloaders without these changes.  Thanks

http://arduino.stackexchange.com/questions/16731/how-to-change-the-usb-name-of-atmel-32u4/16736#16736


text:
Is it difficult to do high voltage parallel programming using Nick Gammon library?
I have bricked a few AT328P by invalid fuse settings.
Has anybody used the above sketches and the associated circuitry to perform high voltage programming?

above sketches? these?

I've used them, they seem to work fine, otherwise I wouldn't have posted them. What invalid fuse settings anyway? If you changed the clock you can supply an external clock and fix them up. See bootloader uploader - the part about an alternate clock source.

to be honest, I do not recall what I set the fuses to,  but since then, I can upload sketches to the chip, but it will not run the program.

I have placed the chip in an arduino uno  bored, but it still does not run.  I haven't tried a lower frequency Crystal, could this work?

Also,   in the reset circuit,   Does the  RC capacitor and  The emitter   Of  Q1  both connect to ground?

Can you clarify how "I can upload sketches to the chip" and "I have bricked a few AT328P by invalid fuse settings" work together? If it is bricked, you cannot upload sketches to it.

I suggest you run my signature detector sketch using another Arduino, to see if the first one is really bricked, and what the fuse settings are. If you can find out the settings please edit your question and post them.

Many thanks for your response. I've managed to sort it out, I used http://denki.world3.net/avr_rescue.html to set the fuse back to factory default and now your programmer software recognises it once again, yeepi. However, I am still interested in getting your High-Voltage solution working as it provides cleaner wiring. The only bit I don't fully understand in your reset circuit is does one end of C2 and emitter both go to GND?

I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.
20+ iirc
My guess is that if anything fails, it's likely to be because of a mistake in the wiring.
If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.

+1 for assuming the OP has some mental sanity in the first place.

Igor Stoppa insomnia


text:
Controlling 2 relays with IR remote, push button and bluetooth - sort of works, need help!
I'm still very new to arduino and coding and having some difficulties trying to figure out what I am doing wrong here.
This program is to have control over 2 relays, using a combination of an      IR receiver and a ir_remotecontrol with pre-programmed buttons (ir_remote buttons 1 = relay 1 toggle, button 2 = relay 2 toggle).
A master momentary hard wired switch to override changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if only 1 relay is on toggle it off with
first click of button then toggle both back on after second click of button.
The Bluetooth module and android app is to also control relays the same as the ir_remote via integers sent through the serial port.
It all sort of works at the moment...
If I just work the relays using the ir remote and the momentary switch it all works perfectly.
if I make sure the relays are in the off position using the remote switch and then use the Bluetooth it also works perfectly.
The problem only is when I use a combination of the ir remote or switch and the Bluetooth - things get weird - the Bluetooth commands seem to reverse and the relays start making a buzzing noise and the momentary switch muddles things up so basically it's all bad news! I've stared at this code for hours and tried a few different things but I just can't see what's wrong.
Let me know if I need to give a more detailed example of the errors I am having. Just thinking it is probably obvious for you pro's out there when you see my noob code!.
Any help would be greatly appreciated!
/*This program is to have control over 2 relays, using a cobination of   an IR reciever and remote control with pre programmed buttons    (ir_remote buttons 1 = relay 1 toggle, 2 = relay 2 toggle).
A master momentery hard wired switch to overide changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if 1 only relay is on toggle it off with first click of button then toggle both back on after sencond click of button.
Bluetooth module and andoid app to also control relays the same as the ir_remote.
 */
//include libaries, and initialise variables
#include <SoftwareSerial.h>
#include <IRremote.h>
#define irPin 8
#define RxD 7
#define TxD 6
#define relay1 13
#define relay2 12
#define buttonPin 2
SoftwareSerial blueTooth(RxD, TxD);
IRrecv irrecv(irPin);
decode_results results;
int comdata;
const int wait = 30;
int sensorValue = 0;
int sensorOut = 0;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState = 0;
int lastButtonState = 0;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup()
{
  blueTooth.begin(38400);                     //set bluetooth baud rate
  delay(500);
  irrecv.enableIRIn();                        //enable infrared recieve
  pinMode(relay1, OUTPUT);                    //setting relays 1 & 2 to output
  pinMode(relay2, OUTPUT);
  pinMode(buttonPin, INPUT);                  //setting momentery swith (overide) to inpt
  digitalWrite(relay1, relay1State);          //putting current status of relays into a variable
  digitalWrite(relay2, relay2State);

}

void loop()
{
  if (blueTooth.available())                  //setting a variable for bluetooth recieved serial commands
  comdata = blueTooth.read();

  if(comdata == '1'){

  digitalWrite(relay1, relay1State);          //if bluetooth receivs "1" toggle relay1state -- essentially relay 1 ON
  }
  if(comdata == '0'){
  digitalWrite(relay1, !relay1State);         //if bluetooth receivs "0" toggle relay1state -- essentially relay 1 OFF

  }
  if(comdata == '2'){
  digitalWrite(relay2, relay2State);          //if bluetooth receivs "2" toggle relay2state -- essentially relay 2 ON

  }
  if(comdata == '3'){
  digitalWrite(relay2, !relay2State);         //if bluetooth receivs "3" toggle relay2state -- essentially relay 2 OFF
  }

  if (irrecv.decode(&results)){                     //Start listing for ir commands, if set remote button code is recvived toggle the variable relay1State or relay2state
  switch (results.value){
      case 0xFF30CF:
        relay1State = !relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        relay2State = !relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
    }

  int reading = digitalRead(buttonPin);          //debounce used to help with faulse readings from momentery switch
  if (reading != lastButtonState) {
   lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

  if (reading != buttonState) {
      buttonState = reading;

  if (buttonState == HIGH) {                      //if the momentery switch is pressed toggle masterstate which is both relay 1 and relay 2 state
     masterState = !masterState;
     relay1State = masterState;
     relay2State = masterState;
      }
      }
    }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;

}

Do you want the relay pins to always match the relayStates?  If you get a "1" on the bluetooth, what do you intend to have happen?  Maybe write a "toggleRelayState(relayNumber){} and setRelayState(relayNumber,state) functions to handle all the state changes, and then invoke these identical functions from each input method.    Also, maybe add some debugging info with a Serial.print  and delay(1000) until you can diagnose what is going on.

You might also check the debouncing code.    It looks like the bracket after "lastDebounceTime = millis();" should be moved way down below "lastButtonState = reading;"

Hi Dave, thanks for taking a look at this for me. I'm sorry to be a pain, but I can't get my head around what you're asking me to do exactly. I am maybe trying to run before I can walk with all this. But I have to say I am learning quicker by just doing, rather than reading and forgetting! To answer your question - If I press 1 on the bluetooth I want it to turn on relay 1 if it is off or do nothing if it is already on.

Looking at this now I guess the blue tooth receive '2' & '3' are not necessary as I'm just setting an opposite value for their respective 'relayState's'? I've removed them for now and added:
    if(comdata == '1'){

relay1State = !relay1State;
digitalWrite(relay1, relay1State);
but still not working as I'd hoped

" If I press 1 on the bluetooth I want it to turn on relay 1 if it is off or do nothing if it is already on." -- for this I'd say "if(comdata == '1') {relay1State = 1;digitalWrite(relay1, relay1State);}" to remember the desired state in  relay1State and set the output to match.  Otherwise, the 3rd to last statement in the currently posted code will reset the output to zero, since the relayState1 was unchanged by the bluetooth command.

Re: "Looking at this now I guess the blue tooth receive '2' & '3' are not necessary" don't you want to control relay2 with the bluetooth as well?  If so, you do need some processing to control relay2.  Maybe I am being confused by your usage of 'toggle' in your post. From your comment it seems like bluetooth=='1'  implies relay1 = on, while from your post it seems like bluetooth=='1' implies relay1 = ! relay1.

Thanks again Dave, however still not working right after changing the BT statements to what you sugested. It all sort of works but for example if I now turn on relay 1 with the BT and then try to turn it off with the IR remote it just blinks off and then stays back on again.
Sorry to be confusing, I do want to control the second relay as well, What I was meaning by 2 & 3 not being necessary was that instead of having an on and an off button for each relay in the android app I could just have 1 button that would toggle the relay on or off or basically the opposite of what it is currently at.

The end goal for this little project wouuld be to have 2 LED strips controlled through the relays for my kitchen cabinets. Having a fixed button for a quick on/off, then an IR remote to toggle each on/off and bluetooth/wifi too for fun. Weather or not I actually implement that I'm not sure, but i though it a reasonable first arduino project to take, although it seems more complicated than I had initially though...maybe I need to go back to BLINK! :)

Dave my man!!! :D The updated code you posted below with the switch case functions has solved my problems! So is the switch a better method because it doesn't keep writing 1's or 0's flat out, it just does it once? Thanks so much for your help!

No, the switch is merely an alternate to the set of ifs.  Enclosing it within the "if (blueTooth.available()) {...}" statement makes it happen only once per bluetooth character, contrary to the bare if()s in your posted code, which are able to trigger each loop()   Also, since the state variables are updated to explicit 1 or 0 values, it doesn't matter if they get reset/rewritten to the same values.

ah ok, that makes perfect sense. Well then, looking at my box of random bits I wonder what else I can throw in..might try a status LED and maybe a status notification peizoelectric speaker....or... :D this is fun! Thanks again for all your help!!!  I'm sure you'll here from me soon! But I'll try not to bother you again! ;)

Looks like it could be reusing the old comdata values in the first part of loop().  Maybe make the first chunk:
   if (blueTooth.available()) {
      comdata = blueTooth.read();
      switch (comdata) {  // set state variables based on bluetooth
      case  '0':  // if bluetooth receivs "0" clear 1
          relay1State = 0;
          break;
      case  '1':  // if bluetooth receivs "1" set 1
          relay1State = 1;
          break;
      case  '2':  // if bluetooth receivs "2" set 2
          relay2State = 1;
          break;
      case  '3':  // if bluetooth receivs "1" clear2
          relay2State = 0;
          break;

      case  '4':  // if bluetooth receivs "4" toggle 1
          relay1State = !relay1State;
          break;
      case  '5':  // if bluetooth receivs "5" toggle 2
          relay2State = !relay2State;
          break;
      case  '6':  // if bluetooth receivs "6" toggle master/both
          masterState = relay1State = relay2State = !masterState;
          break;
      }  // end of switch
      // apply state variables to outputs
      // (could be left to the end of the loop() code)
      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
   } // end of bluetooth processing

   ... /// IR processing code

   // debounce button and toggle masterstate & set state vars accordingly
   // see http://arduino.stackexchange.com/questions/17443/how-to-simulate-delay-to-debounce-mechanical-button-using-millis
   //

// re-ensure output state matches the state variables.
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
}

As it is, the if() statements trigger on the state of the last read comdata, not on the whether a new command was read.
Also, maybe check whether the toggling comments match the code or the code matches the intention properly.

Stmt relay1State = relay1State; has no effect

True.  I'm not sure if the Poster wants the comdata==?? inputs to toggle or actually change the state variables or not.

Thanks for your reply. I tried the changes you suggested but to no avail..
As for my comments - they're probably very wrong as I'm really just getting to grips with arduino and coding, how I think the code works and how it probably works are usually 2 different things, but every day I think  I grasp a little more. And having you guys to guide me when I am stuck really helps too!
Thanks,
Michael

Only the button changes relay1State and relay2State. The IR and BT only change the pin using digitalWrite. But then in the last 3 lines, the pin is changed back to the value of relay1State and relay2State.
I think for the IR and BT you need to change e.g. digitalWrite(relay2, !relay2State); to relay2State=false; etc.
PS It there a pull-up/pull-down resistor on the button pin?

Thanks for the reply! I have tried making the changes you suggested but it didn't help - unless of course I am not doing it correctly (very possible!)
I tried changing the both IR statements to relay2State=false and then also the BT. I also tried changing the BT to True for the on state and false for the off state but that didn't help either?
I have a pull-down resistor on the button pin.
Thanks again.

You need to change all digitalWrites except for the last two, right?

Yeah, tried all except the last 2. I can only turn the relays on but not off.


text:
ATtiny85 + HC-05 + Oled = smart watch
I am using an ATtiny85 for making a smart watch. Bluetooth module HC-05 with ATtiny85 pins PB3->TX, PB4->RX and it works. Secondly I have connected a 0.96" OLED on PB0 (SDA) and PB2 (SCL) and this is also working perfectly. But once I combine both things, it doesn't work.

Why did you decide to use an AVR without a hardware UART?

@IgnacioVazquez-Abrams: suggest me an alternate 8 pin micro-controller with I2C and UART hardware.

@Vipin Why 8 pin?

@IgnacioVazquez-Abrams Probably because he's not aware of the excellent offerings by Microchip in 8-pin MCUs with hardware I2C and UART, such as the PIC12F1840 - though why you'd cripple yourself with just 8 pins is beyond me when you can get a PIC32 in a 28-pin QFN package that is smaller than those old fashioned chunky DIP things and about 100x more powerful...

@Majenko: to keep the size of overall device as small as possible. I just need to hook 1 oled (two pins over I2C) and 1 bluetooth module (two pins) thats it. One more thing, should be able to hold glyph( font), flash > 8kB


text:
How can I connect the MP503 to an Arduino Uno (Smoke, Alcohol Sensor)?
I don't know how I can connect an MP503 sensor to my Arduino.
Please help.

http://eleparts.co.kr/data/design/product_file/SENSOR/gas/MP503%20(Ver1.4)%20-%20Manual.pdf

link is broken, use this one: http://eleparts.co.kr/data/design/product_file/SENSOR/gas/MP503%20(Ver1.4)%20-%20Manual.pdf

you really do need to include more information: is it a raw component, part of a circuit, on a shield? What have you tried? Are you looking for how to connect to it electrically or programatically (or both)?

@frarugi87 - Your link appears to be broken as well... both links give 403 Forbidden :-( However, this one seems to work: http://eleparts.co.kr/data/design/product_file/SENSOR/gas/ZP01-MP503%20Air%20Quality%20Module%20V1.4.pdf

Ok, first of all I doubt you will be able to get a lot of measurements with that. Because... I know that kind of sensors and you will quickly get tired of it.
Anyway, you have to connect

pin 1 to +5V
pin 2 to ground
pin 3 to +5V
pin 4 to a resistor towards ground. Value has to be determined.

To chose the value, you have to try. Change resistor values until, in fresh air, the voltage you can sense across the resistor is approx 1V. I think it is arount 10k, but you'll have to try
Chosen the resistor, you have to simply attach the node between pin 4 and the resistor to an analog input and then read the voltage.
Now you have to calibrate the sensor. Put it in a fixed-concentration gas and measure the voltage: nCalib = analogRead(sensorPin);.
Then, when you need to measure the concentration, you just have to read the voltage again with nMeas = analogRead(sensorPin);. The factor Rs/Ro can be calculated with the formula
Rs_over_Ro = nCalib / (1024 - nCalib) * (1024 - nMeas) / nMeas;

Once you have the factor, look at the graph in figure 3 to get the concentration:

As I told you, I think you will quickly get tired of it, but this is how to use it.


text:
How to add SD card to store data
I'm new to Arduino and I was wondering how to add an SD card to Arduino so it can store more code and also store files such as text files.
Is there such a shield, and if so, any suggestions?

Have you asked Google? It knows about ALL the shields. But yes, there are shields. There are lots and lots and lots and lots of shields, breakout boards, dead-bug tutorials, you name it.

There are 2 things you need to know: SD-card library & https://luckyresistor.files.wordpress.com/2014/10/sd-card2.png

I'm voting to close this question as off-topic because it's more a general question...

On top of that already said, you cannot use the SD card to store code, only data

Take a look at this:
Sparkfun OpenLog

Here's a good tutorial:
https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/intro
This is from adafruit and is for the micro sd card.

authors: Дмитрий Шатаев


text:
Why doesn't my 1602A LCD display text with this code?
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myservo; // create servo object to control a servo

String read_rfid;
String ok_rfid_1 = "6722323b";
String ok_rfid_2 = "99be859e";
int posClosed = 180; // variable to store the servo position for locked
int posOpen = 0; //same for open...

/*
  Initialize.
*/
void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("Scan your card:");
  Serial.println("Scan your card:");
  //Choose which lock below:
  myservo.attach(7); // attaches the servo on pin 7 to the servo object
}

/*
  Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void open_lock() {
  //Use this routine when working with Servos.
  lcd.print("Servo Unlocking");
  myservo.write(posOpen);
  Serial.println("Servo Unlocking");
  delay(10000);
  myservo.write(posClosed);
  lcd.clear();
  lcd.print("Servo Locking");
  Serial.println("Servo Locking");
}

void loop() {
  lcd.clear();
  lcd.print("test");
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent())
    return;
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
    return;
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  if (read_rfid == ok_rfid_1) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (FRED FARMER)" + " -Access Granted");
    Serial.println(read_rfid + " (FRED FARMER)" + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  }
  if (read_rfid == ok_rfid_2) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (JOHN DOE) " + " -Access Granted");
    Serial.println(read_rfid + " (JOHN DOE) " + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  } else {
    lcd.clear();
    lcd.print(read_rfid + " -Access Denied");
    Serial.println(read_rfid + " -Access Denied");
    delay(10000);
    lcd.clear();
    lcd.print("Scan your card:");
    Serial.println("Scan your card:");
  }
}

I have tried running the Arduino library's "Hello World" example, and it successfully runs the text onto the screen. Therefore I have determined that it is not a hardware problem, rather a code problem. It occasionally does display "ff" on the LCD, but that's it.

Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.
Then your code uses lcd.clear() too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.

I use the ISCP pins, not all the digital outputs for the MFRC.

Yes, but those pins are connected to the same pins on the chip.  If you use SPI, it doesn't matter what connector you get it from, 11, 12, and 13 are off limits and 10 must be an output.

I just love it when someone gives the correct answer, and the OP says no it's not right without testing it first...


text:
Help with AlphaNumeric array
I have a Leonardo board and I want to set up my pins to input in one shot using a for loop but the problem is with the analog pins I can't see how to set up a mixed alphanumeric array it gives me some errors.
Code:

// including keyboard.h library for the keyboard functions
#include <Keyboard.h>

// setting Arrays for looping later
   int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
   int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
  int myChar2[6] = {109,110,111,112,113,114};
 myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
  int a;
  int x;
  int i;

void setup() {
  // put your setup code here, to run once:

 //Setting up Digital Pins
for (int i=0; i <= 11; i=i+a){
  pinMode(myIntPins[i],INPUT);
  }

//pinMode(2, INPUT);
//pinMode(3, INPUT);
//pinMode(4, INPUT);
//pinMode(5, INPUT);
//pinMode(6, INPUT);
//pinMode(7, INPUT);
//pinMode(8, INPUT);
//pinMode(9, INPUT);
//pinMode(10, INPUT);
//pinMode(11, INPUT);
//pinMode(12, INPUT);
//pinMode(13, INPUT);

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// setting up Analog Pins to Digital
for (int x=0; x <= 5; x=x+a){
  pinMode(myCharPins[x],INPUT);
  }
//pinMode(A0,INPUT);
//pinMode(A1,INPUT);
//pinMode(A2,INPUT);
//pinMode(A3,INPUT);
//pinMode(A4,INPUT);
//pinMode(A5,INPUT);

// starting keyboard
Keyboard.begin();

}

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

  //if pin 2 is pressed then send the a key/char
 // if (digitalRead(2) == LOW) {Keyboard.write(97);}

// instead of doing an if one by one doing a loop all in one shot
// this loop for regular digital pins
a=1;
  for (int i=0; i <= 11; i=i+a){
    if (digitalRead(myIntPins[i]) == LOW){
      Keyboard.write(myChar[i]);
      }
      }
a=1;
  // this loop for the analog pins now working as digital pins
  for (int x=0; x <= 5; x=x+a){
    if (digitalRead(myCharPins[x]) == LOW){
      Keyboard.write(myChar2[x]);
      }
      }

  delay(10);

  }

Error:
    Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

Mandar_Keyboard_Key_1:10:2: error: 'myCharPins' does not name a type

  myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

  ^

C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void setup()':

Mandar_Keyboard_Key_1:45:11: error: 'myCharPins' was not declared in this scope

   pinMode(myCharPins[x],INPUT);

           ^

C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void loop()':

Mandar_Keyboard_Key_1:77:21: error: 'myCharPins' was not declared in this scope

     if (digitalRead(myCharPins[x]) == LOW){

                     ^

exit status 1
'myCharPins' does not name a type

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

If I change my code I to this, I get a different error.
Code:
// including keyboard.h library for the keyboard functions
#include <Keyboard.h>

// setting Arrays for looping later
   int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
   int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
  int myChar2[6] = {109,110,111,112,113,114};
  char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
  int a;
  int x;
  int i;

void setup() {
  // put your setup code here, to run once:

 //Setting up Digital Pins
 a=1;
for (i=0; i <= 11; i+=a){pinMode(myIntPins[i],INPUT);}

//pinMode(2, INPUT);
//pinMode(3, INPUT);
//pinMode(4, INPUT);
//pinMode(5, INPUT);
//pinMode(6, INPUT);
//pinMode(7, INPUT);
//pinMode(8, INPUT);
//pinMode(9, INPUT);
//pinMode(10, INPUT);
//pinMode(11, INPUT);
//pinMode(12, INPUT);
//pinMode(13, INPUT);

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// setting up Analog Pins to Digital
for (x=0; x <= 5; x+=a){pinMode(myCharPins[x],INPUT);}
//pinMode(A0,INPUT);
//pinMode(A1,INPUT);
//pinMode(A2,INPUT);
//pinMode(A3,INPUT);
//pinMode(A4,INPUT);
//pinMode(A5,INPUT);

// starting keyboard
Keyboard.begin();

}

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

  //if pin 2 is pressed then send the a key/char
 // if (digitalRead(2) == LOW) {Keyboard.write(97);}

// instead of doing an if one by one doing a loop all in one shot
// this loop for regular digital pins
for (i=0; i <= 11; i+=a){if (digitalRead(myIntPins[i]) == LOW){Keyboard.write(myChar[i]);}}

  // this loop for the analog pins now working as digital pins
  for (x=0; x <= 5; x+=a){if (digitalRead(myCharPins[x]) == LOW){Keyboard.write(myChar2[x]);}}

  delay(10);

  }

Error:
    Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

Mandar_Keyboard_Key_1:10:54: error: too many initializers for 'char [6]'

   char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

                                                      ^

exit status 1
too many initializers for 'char [6]'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

If you show what the difference is between the two sets of code, it would be helpful

why did you think it should be string "A0"? you have pinMode(A0, INPUT), not pinMode("A0", INPUT)

@Juraj Idk I thought that int was for integer numbers and a mix of letters and and number would be a string that's all don't blame me I didn't go to school for programming it's just a hobby that I like and I'm learning you know

All of those "A1" "A2" pins have other numbers that go with them.  The A1 or A2 is #defined in the core to be some number.  You can just use A1 or A2 and it will work.
For example, try this line and see what it prints:
Serial.println(A0);

And for your pins, just put A0, A1, etc. in your int array and leave the quotes off.  Those symbols are being replaced by numbers because they're defined constants.
int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13, A0, A1, A2};

That worked just fine   Thanks a lot!!!