text:
How to read sound sensor readings and light up sensor with water sensor if the readings is above threshold & when water is detected for 2 mins?
I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/
I have combined the coding together and this is the new code that worked with the help gotten:
    #define led 4 // led to D4
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;

void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup

void loop() {

     sound1();

} // close void loop

void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread > threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW);
  } // end else

} //end loop

//this code works and is ok to run. can adjust the timing

What "sound sensor" are you using?

Hi i am using grove sound sensor: http://wiki.seeedstudio.com/Grove-Sound_Sensor/
and grove water sensor: http://wiki.seeedstudio.com/Grove-Water_Sensor/

You set a timestamp when the sound first exceeds the threshold and only set the output high when millis() - firstDetect > 2*60*1000
//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread > threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW);
}

Hi Ratchet, thank you so much for your enlightenment! I have combine your coding together with mine (edited in original post), however there's an error message of : "exit status 1 Error compiling for board Arduino/Genuino Uno." :/ Not sure if i defined now() correctly...

@rachetfreak is confusing now() and millis().

@hmppp sorry I did indeed mix up now() and millis(). It's fixed now in the answer.

@rachetfreak and Majenko thanks both for the prompt assistance! i couldn't get the led to light up for this code after 2 mins. It was observed from the serial monitor that the data was about 270++. had adjusted my threshold to 200, however the light sensor still couldn't light up. I am using Grove base shield for this.

@rachetfreak, tried with 10s function, am able to get it uploaded and worked! thank you so much :)

This is actually a lot harder than you might at first think.
Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power.
An audio waveform goes both positive and negative:

The "peak" of the waveform can both be positive (above the line) or negative (below the line).
To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.
However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal.  Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).
If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    uint16_t maximum = 0;
    uint32_t ts = millis();
    while (millis() - ts < t) {
        uint16_t sample = analogRead(pin);
        if (sample > maximum) {
            maximum = sample;
        }
    }
    return maximum;
}

Now to get the maximum over, say, a 10ms period, you can:
uint16_t maximum = getMaximum(A0, 10);

However, if you add a DC offset it gets a little more tricky, but the results will be better:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    int16_t maximum = 0;
    int16_t minimum = 0;
    uint32_t ts = millis()
    while (millis() - ts < t) {
        // The -512 here removes the DC offset from the reading. 512 is half
        // the ADC range.
        int16_t sample = analogRead(pin) - 512;
        if (sample > maximum) {
            maximum = sample;
        }
        if (sample < minimum) {
            minimum = sample;
        }
    }

    // We now have a positive value as the maximum and a negative
    // as the minimum - or zero if none went into the max or min
    // region of the waveform.  Subtract a negative from a positive
    // is like adding a positive to a positive.  But we only want
    // a positive result, so we'll get the absolute value.
    return abs(maximum - minimum);
}

Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold.  The basic method is:

Is the sound above the threshold?

Yes: Was it above the threshold before?
No: Set a timestamp and a flag to say it's above the threshold.
Yes: Has it been above > 2 minutes?

Yes: light the LED

No: Was it above the threshold before?
Yes: Has it been above > 2 minutes?

Yes: Extinguish the LED

The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing.  A simple implementation may look like:
static uint32_t wentAbove = 0;
static bool isAbove = false;
const uint16_t threshold = 300;

uint16_t maxval = getMaximum(A0, 10);

if (maxval > threshold) {
    if (!isAbove) {
        isAbove = true;
        wentAbove = millis();
    } else {
        if (millis() - wentAbove > 120000) {
            digitalWrite(13, HIGH);
        }
    }
} else {
    if (isAbove) {
        isAbove = false;
        digitalWrite(13, LOW);
    }
}

Note: all code untested.

Hi Majenko, thank you for your detailed explanation. Sorry i am very new to programming and arduino and has some trouble understanding. Could you enlighten me what does uint32_t t in  uint16_t getMaximum(uint8_t pin, uint32_t t) do and how should i define getMaximum? :/

unsigned 32-bit integer. It's the same as "unsigned long" - but explicit.  You don't need to "define" these functions - I have defined them for you. Just copy and paste.

I tried both the codes the sample implementation give a error message that getMaximum is not declared. :/


text:
LEDs on TX/RX lines interfering with the programmig of the device
I have recently designed a shield to my Arduino Duemilanove, which has 8 LEDs, on the digital GPIO, from 0 to 7, but it won't program with the shield on because the voltage drop is too much on the RX and TX lines. My question is: can I have a LED on the TX/RX line with a minimum resistor value that allows me to program the Arduino?

how do you have the pins configured/wired? Pullups/pulldowns? Are you sinking current or providing current to the LEDs?

I have from digital pin 0(RX)-->330R-->LED-->GND, and its pretty annoying on the developing fase to be constantly taking on and off the shield.

try something in the order of 5-15k and see how that goes. If brightness becomes an issue you might have to put a transistor in as well.

I just found this reference (using ICSP for output as well as programming -- essentially the same thing), and it suggests a 4.7kOhm.
I didn't have a 4.7k handy, and used a 15k instead and it works.
In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and GND. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).
If I put the resistor in series with it, the sketch uploads without fail.
You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use Serial.[anything]. Make sure to not even initialise the port.

After trying several resistor sizes i got to the smallest possible size of 470R, now i can program whitout any problems at least for this kind of LED, it will probably change if you have an LED with a bigger voltage drop, thank you very much again for your help @Madivad :).

Oh well, that saves me from finishing this project. I was just putting together a breadboard to try different values myself. Glad I could help.

Thats some dedicated fellow :), if your interested i can show you my shield it will be shared soon on OSH Park.
Is there a way to contact people here with private messages ?

Well, I was using it as a learning experience for me as well. Which is why I answer a few XBee questions. As far as I know there is no PM system, but just below in the footer is a "chat", head over to "pin13"

source: Stack Exchange

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

sort: votes


text:
Arduino - stepper motor wrong steps number
I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.
In order to clarify, please see the image below:

The code is as follows:
#define negativeSteps -55
#define positiveSteps 55
#define Speed 7500

int motorPin1 = 11;
int motorPin2 = 10;
int motorPin3 = 9;
int motorPin4 = 8;

int steps;
unsigned int tmp2;

byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

void setup() {

  Serial.begin(115200); //Opens serial connection at 115200 baud.

  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  pinMode(3,OUTPUT);    // Enable pin motorA
  pinMode(2,OUTPUT);    // Enable pin motorB

  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
}

void loop()
{
    while (Serial.available())
    {
      char cmd = (char)Serial.read();
      if (cmd == 's')   while(1) Seek();
    }
}
void motorR(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeR[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void motorF(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeF[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void Seek() {
  steps = negativeSteps;      //Init Steps
  while (1)
  {

    while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
    {
       if (steps<0) motorF(); // if steps = 0 it will change the direction
       else motorR();

      Serial.println(steps);
      steps++;
   }
 }
}

I don't know if this is an answer, but I use a shield: Motor Shield for Arduino, is low cost and the library is very easy ti use.
I recommend you try with this module for easy drive stepper motor like the NEMA

You're driving the stepper too fast, unintentionally though.
The while loop you use to delay is likely optimized out by the compiler:
while (tmp2++<Speed);

Easiest way to fix would be to declare tmp2 as a volatile variable when you declare it up in the top of your program.  Thusly:
volatile unsigned int tmp2;

This will inform the compiler that tmp2 might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.
Better, would be to use the delay() function, to pause execution for some specified milliseconds, much like you're attempting to do with the empty while loop.
You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds.  So maybe a delay() of 3-5 milliseconds would be useful.
Basically, you're trying to step the motor too fast, and it can't keep up.  Mass, inertia and all that stuff are involved too.
Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent.  As you said, 200 steps should be 180°.
replace:
while (tmp2++<Speed);

with:
delay(Speed);

and change Speed to an appropriate value (25 or so to begin with, play with it!).
There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run.  Get THIS code working, then finesse it.

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


text:
Arduino restarts problem
I want to assign -1 to count variable again when count == 16 but when I have assigned -1 inside the if condition I have marked below in the code, the Arduino restarts.
Can anyone guess what is wrong here?
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
#define DISPLAY_WIDTH 16

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

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

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

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

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

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

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

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

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

    int keys = (int) key;

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

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

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

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

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

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

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

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

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

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

I doubt it is the count. Did you try moving it to above the serial print so that you can be sure of the report?
if (count == 16) {
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }

No problem still exists.. any other idea?

Before you must see "Counter equals 16 NOW" now with the changed code do you see "Counter equals 16 NOW"?

@ Visual Micro Ya it prints "Counter equals 16 NOW" on serial Monitor,and also I have printed the value of count and it also proved that count is -1 now. ! but why is that board restart??

What Nick has said is right. It's because ++m is never reset

Thank you very much for your contribution. problem solved.


text:
Sample average of analog of current sensor
I have two problems in the code below. This ACS712 sensor is too noisy so I am not getting the count value properly, since I need approximate reading I consider curve is linear, and calculate the slope.
My problems are:

When I take a 10 sample average, the first value it reads properly, i.e. 512 is count value, other value taking as 0. I don't why.
Once current exceeds 1A, my relay output should go low. Once it goes low it waits for 30s & again it must high the relay high. Since I am checking output in loop, it making high & low without waiting for 30s. Can someone help me how can I do this?

If you used without MStimer, the newaverage values print 512 which is my reference, but for other 9 values print newaverage as zero.
#include <MsTimer2.h>

#define RELAY1  3
#define RELAY2  4

int num_readings=10;
//int total;
int readings[10];
int index;
float CS_Value;
static float Output_Current;
float mad;
float madstd;
float lowlimit ;
float highlimit;
int count;
int total;
int reading;
static int newaverage;
unsigned long Wait_Time=30000;
unsigned long Current_Time;
static int Tripped_Flag=0;

float standard_deviation(int avg1) {
  total = 0;
  for( int i=0; i<num_readings; i++)
    total = total + pow((avg1 -readings[i]), 2);
  return sqrt(total/num_readings);
}

int  average()
{
  total = 0;
  for( int i=0; i<num_readings; i++)
  {
    total = total + readings[i];
  }
  return total/num_readings;
}

void TakeReading()
{

  reading = analogRead(A0);
  readings[index] = reading;
  index = index + 1;

  if (index >= num_readings)
  {
    index=0;
    int avg = average();
    float std = standard_deviation(avg);
    madstd = mad * std;
    lowlimit = avg - madstd;
    highlimit = avg + madstd;

    total=0;
    count=0;
    for(int i=0; i<num_readings; i++) {
      // Check if the values of the readings are within the limits.
      if(readings[i] >= lowlimit && readings[i] <= highlimit) {
        total = total + readings[i];
        count = count + 1;
      }

    }

    // compute the new average
    newaverage = total/count;
    // send it to the serial port (as ASCII digits)

    Serial.print("Newaverage:");
    Serial.println(newaverage, DEC);
    Output_Current = 0.0336666666667*newaverage - 17.17;
    //return(Output_Current);
  }

}

void setup() {
  // sets the serial port to 9600
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  pinMode(RELAY2, OUTPUT);
  Relay_Intialize();

}

void loop()
{
  MsTimer2::set(50, TakeReading); // 500ms period
  MsTimer2::start();
  //  CS_Value=  TakeReading();
  Serial.print("current is :");
  Serial.println(Output_Current);
  //if (CS_Value>0.95 && Tripped_Flag==0)
  if (Output_Current>0.95 && Tripped_Flag==0)
  {
    Serial.println("Main Activate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Activate();

  }
  else
  {

    Serial.println("Main Deactivate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Deactivate();
  }
  Serial.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
  delay(1000);

}

void Relay_Activate()
{
  for (unsigned long start = millis(); millis() - start < 10000;)
  {
    digitalWrite(RELAY1,LOW);
    digitalWrite(RELAY2,LOW);
    Serial.println("RELAY GOT TRIPPED");
    Tripped_Flag=1;
  }

}

void  Relay_Deactivate()
{
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
  Serial.println("RELAY NOT TRIPPED");
  Tripped_Flag=0;

}

void Relay_Intialize()
{
  Serial.println("RELAY GOT INTIALISE....");
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
}

Please can you write 1) clearer? I can't understand.

@lesto which point you are not clear about.

" first value it reads properlyi.e 512 is count value other value taking as 0.I don't why." I cant understand what you expect andvwhatvyoubget

Instead of posting output screenshot, could you copy it here as a text? Screenshot is hard to read and impossible to copy.

I didn't have a look at your item 2, but regarding item 1:
Please consider that in function TakeReading(), if the condition is never true, count is 0 when you come to newaverage = total/count;!
I don't know what the Arduino does in case 0/0, but -1 may be a proper return value.

The result of dividing by zero is undefined. It doesn't throw an exception, but will return invalid data. you need to check for and avoid dividing by zero to avoid bad data.


text:
Analog angle conversion from +70° to -70°
I am using below sensor (accelerometer) .My application is a solar tracker, where I wanted to convert the sensor output into +70° to -70° format.
My question is how can I convert the angle?
#define ADC_ref 2.56
#define zero_x 1.569
#define zero_y 1.569
#define zero_z 1.569
#define sensitivity_x 0.3
#define sensitivity_y 0.3
#define sensitivity_z 0.3

unsigned int value_x;
unsigned int value_y;
unsigned int value_z;

float xv;
float yv;
float zv;

float angle_x;
float angle_y;
float angle_z;

void setup() {
  //analogReference(INTERNAL2V56);
  Serial.begin(9600);
}

void loop() {
  value_x = analogRead(A0);

//  value_y = analogRead(A1);
  //value_z = analogRead(A2);

  Serial.print("voltage  of x");
  Serial.println(value_x);
  /*Serial.print("voltage  of y");
   Serial.println(value_y);
   Serial.print("voltage  of z");
   Serial.println(value_z);
   */
  //xv=(value_x/1024.0*2.5)/sensitivity_x;
/*  zv=(value_z/1024.0*ADC_ref-zero_z)/sensitivity_z;
  yv=(value_y/1024.0*ADC_ref-zero_y)/sensitivity_y;
  xv=(0.0032226562499999998*value_x)/sensitivity_x;
  angle_x =atan2(-yv,-zv)*57.2957795+90;

  Serial.print ("x= ");
  Serial.println (xv);
  Serial.print("x_degree= ");
  Serial.print(angle_x);
  Serial.println(" deg");

  /*Serial.print(" g ");

   Serial.print ("y= ");
   Serial.print (yv);
   Serial.print(" g ");

   Serial.print ("z= ");
   Serial.print (zv);
   Serial.print(" g ");

   Serial.print("\n");

   Serial.print("Rotation ");

   Serial.print("x= ");

   angle_x =atan2(-yv,-zv)*57.2957795+180;

   Serial.print(angle_x);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("y= ");

   angle_y =atan2(-xv,-zv)*57.2957795+180;

   Serial.print(angle_y);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("z= ");

   angle_z =atan2(-yv,-xv)*57.2957795+180;

   Serial.print(angle_z);
   Serial.print(" deg");
   Serial.print("\n");
   */
  delay(1000);
  //delay(1000);
}

Description
Datasheet of ADXL335

I have inclinometer off the shelf its Vout is 0~5 V and angle measure from -70° to 70°, and I calculated as below.
void calcPos()
{
  Sensor_Value=analogRead(A3);
  voltage = Sensor_Value * ARDUINO_ANALOG_SCALING;
  tracker_actual_pos=(30*voltage)-75;
}

If you are using a multi-axis accelerometer such as you linked to measure angles, then you probably need to take an inverse tangent of the ratio between two axis.  If that proves too painful to calculate, you can make a lookup table of tangents for each degree or so, and search it for the closest value.

Wait... what is wrong with calcPos()?

CORDIC may be a suitable method as a replacement for trigonometric functions.

@CharlieHanson: Would you really use CORDIC on a CPU that does have a hardware multiplier? Have you ever tried?

With a question like this, first consider why you need an angle in degrees.  If it's to transmit to some other system, it may be possible to transmit in measurement units, and have the other system take the arctangent.  Or if it is for a display of limited resolution, a lookup table may be an option.  Likely if you are doing little else, your Arduino can calculate the arctangent by any of several methods, but in a more burdened system thinking about the nature of the problem can lead to better solutions.

So atan2(y,x) gives the angle CCW from the x axis in radians, limited to [-pi,pi].
If you want it converted to degrees CW from the Y axis, you would do
azimuth=90.0-atan2(y,x)*57.295779;

If you need to constrain it to -70,70 then:
azimuth_constrained=constrain(azimuth,-70,70);


text:
Controlling Dynamixel Ax-12 With Arduino Mega
I want to controll two dynamixel ax-12 servos using a arduino mega and I don`t know the commands that I should send to them using Serial.
Could anyone help me with this?
(And please keep in mind that I don`t want any more hardware. Just arduino board)

I believe that that site might help you;
http://support.robotis.com/en/techsupport_eng.htm#product/dynamixel/ax_series/dxl_ax_actuator.htm
On the left menu, seek that menu path:
Home > Software Help > Software development kit > Controller Embedded C

how to read position, and the hardware configuration ? pls help me

With Dynamixel library you can use servo this easily:
#include <DynamixelSerial.h>

void setup(){
   Dynamixel.begin(1000000,2);  // Inicialize the servo at 1Mbps and Pin Control 2
}

void loop(){
    Dynamixel.move(1,0);
    delay(2000);
    Dynamixel.move(1,500);
    delay(2000);
    Dynamixel.move(1,1000);
    delay(2000);
}

Example moves servo and makes pauses of 2 sec.
Installation is easy:

Installation:
Copy the files from DynamixeSerial to your IDE libraries folder.

DynamixelSerial folder can be found here: https://sourceforge.net/projects/dynamixelforarduino/files/?source=navbar

But how to connect the arduino and servo?The servo requires half-duplex serial port,but arduino is uart.I want to control the servo and also read the data from it.

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


text:
Powering 4 servos with an external source
I am powering 4 tower pro sg90's and I NEED them to run at maximum torque for at least a few minutes, so 4.8volts. I am wondering how many AA batteries I will need to power all 4 servos at maximum torque for a short amount of time (like 5minutes type of thing). The servos are basically lifting different 3d printed objects.

Well, theoretically that should work, so what is the problem? You want something mobile? You'll most likely need batteries or an accu-pack.

@Paul Oh there isnt really a problem, just looking for other suggestions :) Havent bought the 4x AA holders yet, as its easter! Happy easter by the way!!

Okay, (Arduino) StackExchange is aimed on helping people who run into problems. We prefer questions that can be answered and that aren't to broad. Your question should give more of a clue on what you're trying to achieve etc. You could/should also do some research yourself.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

When choosing a power source, you'll have to consider a few requirements:

Required max amperage (max draw of power)
Required voltages (AC or DC, and available voltages)
Does it have to be mobile?

How long does it have to be powered? (how to recharge/refuel?)

Also see this tutorial it explains that you need a certain voltage for a device to work, too high voltage can result in permanent damage. For amperage, you need to have at least the minimal required, too much is no problem.
Since you don't really have a problem to fix, I can only tell you what I've worked with or what I've liked.
Bench supplies
Bench supplies are great while prototyping, they don't run out (like batteries) and can have a large range of voltage and supply a lot of power. I've looked around to get a nice bench power supply, but I found that they're quite expensive. If you want a variable supply that can do up to 5A, it'll cost you some real money (though it usually is well worth it).
Though my setup has always worked great for me, I use:

converted PSU (PC power supply)
Adjustable step down module

For the PSU, you could also add indicator LED's, they're great because they can supply very much power at very convenient voltages (12v, 5v, 3.3v, -12v). Also since it's a PSU it has overcurrent protection and thus is reasonably safe.
I've also bought the "adjustable step down module" from E-bay, you can power it from a 24V or 19V source like a laptop charger. You can set the output voltage and output max amperage. You can even see when the supply is limiting on power or on amperage. (So you can check if your device is taking more current than set)
"Moving" projects
The easiest thing here is (multiple) batteries, check the tutorial of sparkfun again. If you put them in series, you will sum up the voltage. If you put them in parallel, you will sum up the capacity.
I think batteries are the easiest way to power your device. You can check different types of batteries, they have different voltages and "ampere hours". Battery holders are cheap and you can easily replace them if they run out.
On the subject of rechargeables, I would go with an Ni-Mh pack. I've got a Ni-Mh pack for airsoft and it's very reliable and easy to charge. Li-Ion requires much more care in handling and charging.
Other options can be solar-cells or other harvestable energy, but these often aren't really viable.
Extra
When starting to move, a servo can suddenly pull a lot of power. Not all supplies can handle this well. So the other servo's may "jiggle". Often, it's good to have a capacitor that can act as a "reservoir" or for smoothing. Same goes with devices that reset in some scenario's.
*I hope this gives you an idea on some possibilities, I haven't highlighted all options (there are too many), you should check tutorials/video's and see what works for you.
For example, check this instructable that focusses on some (analog) points that I didn't mention.*

Thanks for replying, i am following the sparkfun article; The batteries i am using are 2100mAh so 2.1A for one hour (which is enough for my project), and the battery supplies 1.5V. This gives a total power of 3.15W for one battery. The servos I am using have a stall current of 600mA and a stall torque of 4.8V, which = 2.88W and11.52W for all 4 servos. so 11.52W/3.15W = 3.67, so does this mean that it should be sufficient to use 4 of my AA batteries to power my servos

You'll need 3x batteries in series, to get the 4.5V. If the batteries can discharge at 1C (2,1A) and 4x 0,6 = 2,4A you really are on the low end. Maybe two rows of three in series. But a lot of accupacks are made for RC applications and fall inbetween the min/max of servo's and can deliver enough power. (If it's on a table next to your 3D printer, why not use a 5V adapter?)


text:
Why are the Do While loops not stopping?
Ive been staring at this for a while now and I am going cross-eyed.  I am writing a simply program to change colors of a 3 color LED.  It is working, but then I noticed the LED would sometimes flash.  I did a variety of tests and eventually, using the serial monitor, found out the issue.  The brightness should count down to a brightness level of 0 and up to a level of 255.  However, sometimes it counts below 0 to -1 and sometimes it continues infinitely past 255.  I cant figure out why.  Below is the code and the serial monitor outputs.  The only way I can stop is by manually setting the value outside the loop.  You can see those lines commented out to allow for the error.
int randLeg;  // var to pick a random leg

// set all 3 legs to max brightness at start
int legThreeBrightness = 255;
int legFiveBrightness = 255;
int legSixBrightness = 255;
int delayTime = 15;
int increment = 1;

void setup() {

    Serial.begin(9600);

    // set pins as output
    pinMode(3, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);

    // turn all the LEDs on
    analogWrite(3, legThreeBrightness);
    analogWrite(5, legFiveBrightness);
    analogWrite(6, legSixBrightness);

    randomSeed(analogRead(0));  // seed rand num generator

}

void loop() {

    randLeg = random(4, 7);  // pick a random leg

    switch (randLeg) {
    case 4:  //-1 for pin 3
        if (legThreeBrightness == 255){
          do {
                Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness - increment;
             } while (legThreeBrightness >= 0);
             //legThreeBrightness = 0;
        }
        else {
         do {
                Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness + increment;
             } while (legThreeBrightness <= 255);
             //legThreeBrightness = 255;
        }
      break;

    case 5:
        if (legFiveBrightness == 255){
          do {
                ////Serial.println(legFiveBrightness);
                analogWrite(5, legFiveBrightness);
                delay(delayTime);
                legFiveBrightness = legFiveBrightness - increment;
             } while (legFiveBrightness >= 0);
             //legFiveBrightness = 0;
        }
        else {
         do {
                ////Serial.println(legFiveBrightness);
                analogWrite(5, legFiveBrightness);
                delay(delayTime);
                legFiveBrightness = legFiveBrightness + increment;
             } while (legFiveBrightness <= 255);
             //legFiveBrightness = 255;
        }
      break;
    case 6:
        if (legSixBrightness == 255){
          do {
                ////Serial.println(legSixBrightness);
                analogWrite(6, legSixBrightness);
                delay(delayTime);
                legSixBrightness = legSixBrightness - increment;
             } while (legSixBrightness >= 0);
             //legSixBrightness = 0;
        }
        else {
         do {
                ////Serial.println(legSixBrightness);
                analogWrite(6, legSixBrightness);
                delay(delayTime);
                legSixBrightness = legSixBrightness + increment;
             } while (legSixBrightness <= 255);
             //legSixBrightness = 255;
        }
      break;
   }

}

10 9 8 7 6 5 4 3 2 1 0 -1

and

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

you can remove 2/3 of the code if you use arrays

@jsotola that is probably true, but doesnt change the error I am having,

first do loop counts to -1 ... the second do loop prints the -1 and counts to 256 ... second do loop keeps counting from 256  because do-while always runs at least once ... use if (legThreeBrightness > 255){

Seems to be the question title should changed slightly, such as "Why are the do while loops stopping later than I expect?"

change >= and <= to > and < respectively.
You want it to stop at 0, but your do-while will do another round, since 0>=0 is true. So your code only stops at -1 and 256.
When legThreeBrightness is 256 it should be counting down, but your if (legThreeBrightness == 255){ doesn't detect this, so the code will continue counting up. I'd probably change this line to if (legThreeBrightness >= 255){ to prevent this from ever happening (which it shouldn't, but still).

Honestly, I think I actually tried this last night, but I will try it again.  It also doesnt explain why in only happens sometimes.  I will report back.

It's definitely this - you can see in the output it go out of bounds, and just keeps going. e.g. from one part of a run: 252 253 254 255 256 256 257 256 258 257 257 259 258 259 258 260 259 260 260 261 262 263 261 262 263 264 265 261 264 265 266 267 262 263
Another way to prevent the value going out of bounds is to not use a do while loop, which runs the loop BEFORE it tests the value. But you will still need to use < or > for the comparison as you don't want the value decremented/incremented past when you have reached the boundary of your range.

this fixed the issue

You have two issues related to bounds checking. For the sake of brevity, since all there LED branches of the switch statement are the same, I will refer to legNumBrightness instead of the individual legThreeBrightness, legFiveBrightness, legSixBrightness variables since this applies to all three (individually).
Because do while loops always run once before testing the condition, you have an issue with the value of legNumBrightness going out of bounds. i.e. when it is equal to 255, it decrements by one, until it is zero, and then because 0>=0 is still true (0 is equal to 0, after all), it decrements once more, so legNumBrightness is now -1. So on the next visit of that legNumBrightness = 255, the increments up by one branch is taken, until it reaches 255 <= 255, which is again true, and hence will go to 256. As the if bounds test used is only that of legNumBrightness == 255, it will only decrement if the value is  exactly 255. Thus if it is not 255, it will keep incrementing until the maximum value of an int is reached (32767), overflow to -32768, and probably keep toggling between -32768 and 32767.
So to fix this, you need to change the if (legNumBrightness == 255) bound checking to
if (legNumBrightness >= 255). Now, because of the do while loop, legNumBrightness will still sometimes go to -1 and 256, but can no longer overrun past 256. To fix the -1 and 256 overrun, remove the = from the do while tests so they become while (legNumBrightness > 0) and while (legNumBrightness < 255) and thus will not try to increment or decrement when the boundary has been reached.
I would also recommend using a while() loop in preference to a do while() loop, so the condition is checked before running the loop content, but it does not appear necessary from brief testing of this logic.
e.g. for legThreeBrightness
 case 4:  //-1 for pin 3
        if (legThreeBrightness >= 255){
          do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness - increment;
             } while (legThreeBrightness > 0);
             //legThreeBrightness = 0;
        }
        else {
         do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness + increment;
             } while (legThreeBrightness < 255);
             //legThreeBrightness = 255;
        }
      break;

I agree with @Gerben that you need to change >= and <= to > and < respectively, for the do-while loop check.
Secondly, your if statement expects legThreeBrightness (et al) to be 255 in order to decrement the brightness. Because of your while statement is over-running 255 because of  <= 255, the if statement will always execute the else part and because it is a do-while it will execute the loop once, incrementing legThreeBrightness.
To fix this, change the if statement to check for a value above 250:
case 4:  //-1 for pin 3
    if (legThreeBrightness > 250){  // <---- Notice the > 250
      do {
            //Serial.println(legThreeBrightness);
            analogWrite(3, legThreeBrightness);
            delay(delayTime);
            legThreeBrightness = legThreeBrightness - increment;
         } while (legThreeBrightness > 0);
         //legThreeBrightness = 0;
    }
    else {
     do {
            //Serial.println(legThreeBrightness);
            analogWrite(3, legThreeBrightness);
            delay(delayTime);
            legThreeBrightness = legThreeBrightness + increment;
         } while (legThreeBrightness < 255);
         //legThreeBrightness = 255;
    }
  break;

This is easy to check and you should see the problem disappear straight away.

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


text:
How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up
I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water_Sensor/.
I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

int isWater;
bool wasWater = false;
//bool isWater, wasWater = false;    // true => currently we are not seeing water
uint32_t waterstart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
   // Is there water?
 isWater = digitalRead(watersensor);     // read sensor
 Serial.println(isWater);

   if( isWater ){
      if( wasWater ) {
      waterstart_ms = millis();  // First water: note the time
      }
        if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
            digitalWrite(led, HIGH);
        }//end if
            wasWater = true;
   } // end first if
   else {
      wasWater = false; // No water; LED off
      digitalWrite(led, LOW);
   }
}

It's exactly the same as how you do it for sound - just using the presence of water instead of the maximum value of sound.

Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true => currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}

void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) >= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}

Update:
Added wasWater = true; at line 27. The delay(300) at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.

Hi JRobert! Thanks for your guidance. I have made some minor amendments to the code. But the sensor only lights up without the presence of water. when i change the if ( !wasWater) to if (wasWater), the light lights up randomly.
Not sure where went wrong..
Had updated the new amended code in my question!


text:
MKR1000 and DS18B20 temperature sensor
I am new to Arduino and electronics in general and I can't get my MKR1000 to read correct data from a DS18B20 temperature sensor.
Here is the tutorial I followed.
The issue is: I always get the same readings from the sensor: -127.00.
I should mention I have tried 2 different sensors and get the same readings.
From the sensor, GND goes directly to GND on the board, and I have the 4.7kΩ resistor in between the data and power wires.
According to the sensor manufacturer, output leads: Yellow (VCC), Red (DATA), Black (GND).
Data line is connected to the pin ~2 on the MKR1000.
/********************************************************************/
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/********************************************************************/
void setup(void)
{
 // start serial port
 Serial.begin(9600);
 Serial.println("Dallas Temperature IC Control Library Demo");
 // Start up the library
 sensors.begin();
}
void loop(void)
{
 // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
/********************************************************************/
 Serial.print(" Requesting temperatures...");
 sensors.requestTemperatures(); // Send the command to get temperature readings
 Serial.println("DONE");
/********************************************************************/
 Serial.print("Temperature is: ");
 Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
   // You can have more than one DS18B20 on the same bus.
   // 0 refers to the first IC on the wire
   delay(1000);
}

Any idea what I am doing wrong?

In addition to the photos, do you have a schematic for the circuit to upload?  It would be more helpful than looking at the bunch of wires to figure out what is going on.

Thanks @MichaelT - This question has been answered already. Sensor manufacturer messed up their documentation so I had the power going to the data and vice-versa.

Looks like you have it wired wrong.  A schematic would really help but it looks like you've got 5V going directly into the sensors data line (yellow wire) it's connected on your breadboard to the orange wire +5V.  The power wire of your temperature sensor (red wire) is running through a 4.7K resistor which is not likely what you wanted here either.

According to the sensor manufacturer: Output leads: Yellow (VCC), Red (DATA), Black (GND)

May be a typo in their documentation.  I've found similar sensors on Ebay and:  Output lead: red (VCC), yellow(DATA) , black(GND)

The schema I am trying to achieve can be found on the link I posted earlier: https://create.arduino.cc/projecthub/TheGadgetBoy/ds18b20-digital-temperature-sensor-and-arduino-9cc806#toc-step-4--build-simple-circuit-3

OMG! Okay... you were right, they managed to get their schemas wrong! Red is VCC and yellow is DATA! I thought about many possible causes but not that one... ;) Thanks for your help.

The only thing worse than no documentation is errant documentation.


text:
TCS230 Low Pulse Length with Arduino
My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.
Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.
Our Wiring
S0  - GND
 S1  - 5V
 OE  - No Connection (Tried GND)
 GND - GND
 S2  - D8
 S3  - D7
 OUT - D4
 VCC - 5V
Our Code:
int S2 = 8;
int S3 = 7;
int OUT = 4;

void setup() {

Serial.begin(9600);
pinMode (S2, OUTPUT);
pinMode (S3, OUTPUT);
pinMode (OUT, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int red , green, blue;

  red = getRed();
  Serial.print("Red : "); Serial.println(red);
  Serial.println("**********************");
  Serial.println();

  blue = getBlue();
  Serial.print("Blue : "); Serial.println(blue);
  Serial.println("**********************");
  Serial.println();

  green = getGreen();
  Serial.print("Green : "); Serial.println(green);
  Serial.println("**********************");
  Serial.println();

  delay(3000);

}

int getRed(void){ return getColor(0, 0, 19000, 24000); }

int getGreen(void){return getColor(1, 1, 13600, 19200);}

int getBlue(void){return getColor (0, 1, 16400, 21600);}

int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

  long divideForScale = typicalPulseWidth / 255 ;

  digitalWrite(S2, s2Value);
  digitalWrite(S3, s3Value);

  unsigned int pulseWidth = pulseIn(OUT,LOW);

  Serial.print("Pulse Width : "); Serial.println(pulseWidth);

  unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
  Serial.print("Response Color - Inverted : "); Serial.println(rColor);

  rColor = 255 - rColor ;
  Serial.print("Response Color - Final : "); Serial.println(rColor);

  delay(500);

  return rColor ;

}

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.
I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.
http://www.unihedron.com/projects/darksky/tcs230-e33.pdf
Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.
Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.
Output from Measuring a Blue RFID Keyfob:
    divideForScale : 74
    Pulse Width : 673
    Response Color - Inverted : 9
    Respponse Color - Final : 246
    Red : 246
    **********************
divideForScale : 64
Pulse Width : 376
Response Color - Inverted : 5
Respponse Color - Final : 250
Blue : 250
**********************

divideForScale : 53
Pulse Width : 737
Response Color - Inverted : 13
Respponse Color - Final : 242
Green : 242
**********************

Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.
Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).

I tried increasing the resolution but the pulse width decreases as the resolution increases. S0 - Low and S1 - High for 2% resolution provides the longest pulses.

I'm not really following, but the fact that you tried different S0, S1 combinations, means this isn't the solution. Maybe someone else knows. Best of luck.

The  reading from pulseIn was about 30 - 50 when S0 and S1 were both set to High. Perhaps resolution is not the correct word, but a higher output frequency seems to require a shorter pulse rate. The 2000 reading from pulseIn at 2% is the longest pulse we were able to get back from the unit.

From the project page (a comment by Marius David) it seems some integer datatypes may not be the same on different platforms. If he is correct, you may be working with a 16 bit pulseWidth while 32 bits are needed.
Try using an unsigned long for the pulseWidth variable.

Good idea but no such luck. Issue persisted after changing pulseWidth type to unsigned long


text:
ir sender detecting receiver and display
I am in a pickle and want to know if you can help me. I have an IR sensor and receiver and want a program that makes a light bulb flash or detect whenever the IR receiver is in range.
So whenever the IR sender detects the receiver, it should print "detect". This will be done using the Arduino program. And it is an Arduino Nano I am using.
These are the things I use:
http://www.dx.com/p/keyestudio-digital-ir-receiver-module-for-arduino-black-429206#.V5gcpzYko-U
http://www.dx.com/p/38khz-ir-infrared-transmitter-module-for-arduino-135040#.V5gcpjYko-U
How should this program look like? Anyone have the code for this?
Never mind the LED blinking, I just want the program to know whenever the receiver is detected and probably display it somehow. My plan is to send the number of times the transmitter detects the receiver to an Android app in the end.

Assuming you got receiver and transmitter mixed up, then its simple. Otherwise, its not as simple. As @duskwuff points out, simple IR is one-way. The Transmitter here is just an IR Led. That's it. The Receiver is a Remote Control type IR Receiver, looks for a 38khz modulated IR signal, and removes the 38khz carrier wave, passing on the data to be read by the other end.
For a IR beacon type setup, in either simple or two way mode, you'd need two micro controllers.
Simple:

Microcontroller A is the Transmitter. All it does is repeatedly send out an IR modulated code. The Arduino IRLib library can do this.
Microcontroller B is the Receiver. It looks for that specific code, and if found, does X, which could be print to serial, or send over bluetooth to a phone.

Complex, both receive and send:

Microcontroller A is the main part. It sends a code then switches to receive mode for X seconds. If it receives a confirmation or its own code back, it tells the phone/pc it has been found or flashes a different LED.
Microcontroller B is a beacon/repeater. It waits to receive the code above, then switches to transmit mode, and sends the same code or a different code back. That's all it does. A Basic IR Remote Control Repeater.

This tutorial at Adafruit explains it all, with code examples.

Yes, How would I do this? I have 2 arduino nanos. How would I program the 1 to be a receiver and the other 1 to be a transmitter? Is there code anywhere of someone that did this? I have an IR emitter and receiver. Should I use 1 emitter on the 1 arduino and 1 receiver on the other?


text:
Arduino weird bluetooth module
Recently I bought a BT module from eBay which was very cheap. I didn't really noticed the image and I just bought it. When it came I couldn't find any holes to solder the headers. Also the specific module is pretty rare and I couldn't find anything.
Here is an image:

How do I wire up this chip?

Are you able to post a clearer photo? If your camera has a close-up or 'macro' mode then it may help.

You at least post a link to the item on ebay; the blur pict you linked to is totally useless currently.

@jfpoilpret Not exactly useless, but it definitely needs improvement.

From the picture you posted, i was able to google and find something called a BC04-B Bluetooth serial module. It looks almost exactly like yours, and I found a diagram on how to hook it up.

I also believe that these are the serial commands you can use with it...

It could be HC-06 or HC-05 but they operate quite similarly.

These Bluetooth modules are typically mounted onto another substrate, either the product board or a small PCB backplane which provides the pinouts and any additional circuitry like the pairing LED, and power- & signal-level management.
They are readily available as HC-05 (master/slave) or HC-06 (slave only) with signals brought to through-holes or pins at the edge of the backplane.


text:
I2C TinyWireS SEND: How to convert unsigned long to uint8_t array?
How do you convert an unsigned long to a uint8_t array? I am interested in sending an unsigned long integer from an ATTiny85 to an Arduino Uno via I2C. The issue is with TinyWireS.Send() which can only send a var of type uint8_t. I believe the solution would be to use TinyWireS.Send() in an array?

This might not be politically correct code, but it is pretty simple to just cast a pointer to uint8_t like this:
long data = 5;
uint8_t *rx = (uint8_t*) &data;

You can still use array subscripts even though its a pointer, and you can pass it to a function like an array. Just don't go past rx[3].
Alternately, you could also make a union like this:
union{ long data; uint8_t bytes[4]; } convert;
convert.data = 5;

And then use convert.bytes as your array to send.

I do exactly this with an ATtiny You have 32 bit long that needs to be broken up into 4 8-bit chunks. You need to some simple bit shifting to accomplish this.
volatile unsigned long Data1;//this is the data you are sending
volatile byte SendCount;
volatile uint8_t sendByte;

void requestEvent()
{

  SendCount++; //increment this
  switch (SendCount)
  {
    case 1:
      Data1 = GetMyData();
      //Data1 = 55555;
      sendByte = Data1 & 0xFF;
      break;
    case 2:
      sendByte = Data1 >> 8;
      break;
    case 3:
      sendByte = Data1 >> 16;
      break;
    case 4:
      sendByte = Data1 >> 24;
      SendCount=0;
      break;
  }

  TinyWireS.send(sendByte);
}

You need to initialize SendCount = 0; in your Setup method.
You will need to recompose the 4 bits back into a 32 bit long on the Master device too.


text:
Arduino RFID Mifare Classic dump info
I have my Arduino uno setup with RC522 reader. I am able to dump the data that is held on my test card supplied with the reader but I wish to read the data blocks held within another card I have. The reader shows this as a Mifare classic but Does not dump the blocks.
This is with miguelbalboa library
Card UID: EE 67 29 8D
Card SAK: 08
PICC type: MIFARE 1KB
Sector Block   0  1  2  3   4  5  6  7   8  9 10 11  12 13 14 15  AccessBits
  15     63  PCD_Authenticate() failed: Timeout in communication.
  14     59  PCD_Authenticate() failed: Timeout in communication.
  13     55  PCD_Authenticate() failed: Timeout in communication.
  12     51  PCD_Authenticate() failed: Timeout in communication.
  11     47  PCD_Authenticate() failed: Timeout in communication.
  10     43  PCD_Authenticate() failed: Timeout in communication.
   9     39  PCD_Authenticate() failed: Timeout in communication.
   8     35  PCD_Authenticate() failed: Timeout in communication.
   7     31  PCD_Authenticate() failed: Timeout in communication.
   6     27  PCD_Authenticate() failed: Timeout in communication.
   5     23  PCD_Authenticate() failed: Timeout in communication.
   4     19  PCD_Authenticate() failed: Timeout in communication.
   3     15  PCD_Authenticate() failed: Timeout in communication.
   2     11  PCD_Authenticate() failed: Timeout in communication.
   1      7  PCD_Authenticate() failed: Timeout in communication.
   0      3  PCD_Authenticate() failed: Timeout in communication.

I have also tried using these examples https://github.com/BoolLi/RC522_RFID_NFC_Utilities
But they fail to compile for me. All I want to do is dump the data blocks from a university card I have for a project, I don't need to be able to write to the card yet.

Failed authentication probably means you're using incorrect secret keys and there's a good chance that you've locked yourself out permanently. Your test card is a blank card from the manufacturer, with the default access conditions still in place. Where's the second card from?

second card is a uni card I have, it's only use is to allow entry to certain areas ie library and stuff, I have permission to be messing around with it for comp sci project. The card still works after trying this, how would I go about reading with secret keys and such? or even something I could read that covers this.

My bad. Since authentication failed and you never got to actually accessing the data, I doubt you hurt anything. There's an example in your library (rfid_default_keys) that brute-forces authentication with a bunch of known keys. If those dont work, trying out all 2^48 possibilities is not an option; would take millenia. You can try googling for MIFARE hacks.

The person who issues the card would know what the SO-PIN is.  When the factory ships the cards they have a Factory SO-PIN which will be published somewhere and then the Uni's card issuance system will(should) change the SO-PIN to something unique to the Uni so it can't be accessed by anyone without this PIN.  I recommend against trying to hack the card, because you only have a certain number of attempts (3 usually) before you irreparably damage the card (I have done many).


text:
Arduino and Processing Call and response not working
I have been trying to develop a connection from the arduino IDE to Processing so I can send data measured on the arduino Pins to processing to display.
I first packaged the 10-bit integers I was receiving from the arduino into characters each with their own byte. For example, 1023 was a 10-bit integer which i packaged into 4 8-bit characters, 1, 0, 2 and 3. These could then be sent over the serial port and were reconstructed on the other end by processing.
However, I have been trying to make a call and response relationship between the two where after one program is done receiving and processing the data, it asks the other to send the next set.
I used the example code given on the arduino website which works fine on its own. But when i try and implement the character packaging to it, it stops working. The output in processing always miss out the first couple of characters.
Whats more is that i deleted the myPort.print('A') from the processing code, and arduino was still sending data repeatedly, despite processing not sending it's response back.
It is a vague question, but where have i gone wrong when implementing the packaging code? and why does the arduino keep sending data regardless of whether processing responds.
Thanks a lot
===================================
Arduino Code:
int inByte = 0;

//void establishContact();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  establishContact();
}

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

  if (Serial.available() > 0) {
    // get incoming byte:
    //inByte = Serial.read();

      int MzValue = analogRead(A0);
      int FzValue = analogRead(A1);
      int FyValue = analogRead(A2);

      char Mz_Str[10];
      char Fz_Str[10];
      char Fy_Str[10];

      sprintf(Mz_Str, "%d", MzValue);
      sprintf(Fz_Str, "%d", FzValue);
      sprintf(Fy_Str, "%d", FyValue);
      // Now str contains the integer as characters

      Serial.write(Mz_Str);
      Serial.write(",");
      Serial.write(Fz_Str);
      Serial.write(",");
      Serial.write(Fy_Str);
      Serial.write(",");
      Serial.write("\n");

      delay(20);
  }
  else {
    delay(20);
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.print('A');   // send a capital A
    delay(1000);
  }
}

===================================
Processing Code:
import processing.serial.*;

  Serial myPort;                       // The serial port
  boolean firstContact = false;        // Whether we've heard from the microcontroller
  String val;     // Data received from the serial port
  int numValues = 3;
  float[] values = new float[numValues];
  int inByte = 0;

  void setup() {
    size(256, 256);  // Stage size
    noStroke();      // No border on the next thing drawn

    // Print a list of the serial ports for debugging purposes
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // I know that the first port in the serial list on my Mac is always my FTDI
    // adaptor, so I open Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[0];
    myPort = new Serial(this, portName, 9600);
  }

  void draw() {
    // read a byte from the serial port:
    if ( myPort.available() > 0) {
    inByte = myPort.read();
    }
    //print(inByte);
    // if this is the first byte received, and it's an A, clear the serial
    // buffer and note that you've had first contact from the microcontroller.
    // Otherwise, add the incoming byte to the array:
    if (firstContact == false) {
      if (inByte == 'A') {
        myPort.clear();          // clear the serial port buffer
        firstContact = true;     // you've had first contact from the microcontroller
        myPort.write('A');       // ask for more
        println(inByte);
      }
    }
    else {
        val = myPort.readStringUntil('\n');         // read it and store it in val
        println(val); //print it out in the console
        values = float(splitTokens(val, ","));

        myPort.write('A');
        delay(20);
      }
    }

Serial.print(MzValue); will do the same as your 'character packaging'

you don't read the available character, so it is remains available

Processing + Firmata is also a potential solution.

Why not just send all the data at once, in a comma separated list, with a \n char as a "end of message" delimiter?
Here are 2 test sketches. The Arduino sketch sends the A0 to A2 values to serial every 500ms, and the Processing sketch displays the received data. Parsing the received data into an integer array is more of a Java question, not an Arduino one, so I'll leave that up to you.
Arduino
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2416 bytes.
char data[20];
char buffer[6];

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

void loop(){
  itoa(analogRead(A0), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A1), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A2), buffer, 10);
  strcat(data, buffer);
  strcat(data, "\n");
  Serial.write(data);
  memset(data, 0, sizeof(data));
  delay(500);
}

Processing
// Display the data received from the serial port, sent every
// 500 ms from the Arduino. The values sent are from A0, A1
// and A2, and were sent concatenated together, as a comma
// separated list, followed by a \n char.
import processing.serial.*;
import java.awt.TextArea;
Serial myPort;
TextArea myTextArea;
String input;

void setup(){

  try{
    myPort = new Serial(this, Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }

  myTextArea = new TextArea("", 23, 49, 1);
  this.add(myTextArea);

  size(500, 380);

}

void draw(){

  if(myPort.available() > 0){
    input = myPort.readStringUntil('\n');
    myTextArea.append(input);
  }

}

EDIT
As Juraj mentions in his comments, I could have just used Serial.print() 6 times instead of the char arrays. Here is a second Arduino sketch that uses Serial.print(). Before you use it, be aware that it's compile size is 288 bytes more than the char array method. Imagine that :)
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2704 bytes.
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.print(analogRead(A0));
  Serial.print(",");
  Serial.print(analogRead(A1));
  Serial.print(",");
  Serial.print(analogRead(A2));
  Serial.print("\n");
  delay(500);
}

Why not print the data to Serial as Serial.print(analogRead(A0)); Serial.print(',');...?

@Juraj That would work too :)

it would be 6 simple lines. no buffers, no C functions. and why memset again?

you need only buffer[0] = 0; at the start of the loop to 'clear' the string

I know. I like using memset() to set the entire array to 0's. How about this: memset(data, 0, 1); It results in the same compile size as buffer[0] = 0; and does the same thing. Of course, no one is forcing you to use memset().


text:
Convert normal keyboard into Bluetooth Keyboard
I am very new to the Arduino world, I am trying to convert my wired keyboard into a bluetooth keyboard. I have a few layman questions:

Is it possible to add an audio jack adapter(like PS4 joystick has), so that I can plugin my headphones to my keyboard itself to listen to the music.
Is it possible to achieve this(bluetooth keyboard + audio jack) on Arduino or do I need to use Rasberry-pi?
Is there a way to keep my current USB wire? so that I can keep working even if the battery runs out.
I want to keep all the apparatus in the keyboard casing itself, can you please suggest smallest Arduino board that will work for my use case.
I am not sure if I need a special kind of bluetooth breakout board for this(that can receive audio as input and send keystrokes to my system). Can you please guide what will be the best fit board.

Thanks in advance.

I want to keep all the apparatus in the keyboard casing itself - can you be specific about how much room you have in your keyboard casing - because if it's anything like mine, you won't find anything that will fit

@JaromandaX It's a custom made keyboard, I can fit at least something of iPhone7's height and half of it's width in my casing.


text:
Arduino Nano Midi to cv convertor interesting issue
I created the circuit in this schematic on protoboard,

and the code,
https://github.com/elkayem/midi2cv
I use a dual opamp and a single dac, because i only need note and velocity.
The opto i use is, H11L1
It works but has a strange issue that i can not figure out.
The author says the code supports midi notes from 21 to 108.
When I send midi notes to test the device,
(Arduino powered with +12, TL082 Opamp powered with +15 to GND )
The notes <= 36 gives +15V in the output of the opamp.
The note 37 gives +3.43V
The note 38 gives +1.7V
.
.
.then it increments as expected until note 108 which gives +7.52 V
Also to add I have +1.5V DC offset on the both outputs of the opamp.
(This, i can live with but i would love it not to happen. )
I would be very happy if you help me on this, thank you.

Find out what voltages are output by the DAC, and what voltages the opamp can handle.

I changed the opamp to LM358 and all problems solved it works perfectly!
If you have enough motivation and time please explain me why, but i will research and learn anyway.


text:
Routing Matrix with a large number of I/O
Lets say that i would like to make a 128x128 routing matrix with an arduino uno,
Since i am unexperienced i think of using two 4051’s for 8x8 patching and because i want to persist the patch, controlling them with two quad d type flip flops, then repeat the circuit to reach 128x128 patching capibility. Then my output count would be sufficent in arduino uno.
I think this would work but sounds unelegant to me.
Do you have another advice for me to achieve this task?
Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

That is 128*128 = 16384 junctions! Can you tell what it is for? Is it for analog signals in both directions? Can all inputs be active at the same time? Please update you question with more information. This is the arduino section, I think your question will be moved to the electronics section.

Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

Can you draw a circuit with two 4051's for a 8x8 matrix? They have a single common pin, they are not a matrix. The cd4066 has 4 analog switches, then you need 16384/4 = 4096 of those chips.

I think it can be done with 2304 74HC4067 chips ((1+8)*256). Who can reduce the amount of chips that are needed further?

Ah you are right, I thought terribly wrong, this way they can not be patched at the same time. Rudy’s advice for ad 75019 explains the situation. Sorry a bit confused now.

But isn’t there a way to go for this task not using amazing amount of chips?

I think that there is not a single chip for 128x128. A small module for 8x8 or 16x16 can not easily be scaled up, because it is a two-dimensional matrix. You need a large amount of chips.

I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.
Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html
They are more expensive but cost should not be the primary factor. Getting a design to work is more important.
Do a search for "Crosspoint Switch Array" for more chips like this.

Wow thank you i will immediately chack all of those. What are your concerns about practical implementation?

Anything that large is a problem. Physical implementation. Noise issues.  What is your application?

I edited the question to include my purpose.

OK that's more doable. I was worried you were trying to take signals in from the real world. Good luck.

20 dollars per ad75019. How many will be needed?

Well, since this is the case I can live with 6 of them. Maybe 96x96 is big enough.

Six ad75019 make a matrix of 16x96. I think you need 36.

Ah you are right, but these were quite informational for me thank you both. Now I get the picture better I would research according to that. Well maybe in the future this would not be a bad investment for such a large patch bay. Do you think there will be other problems that i can not think of right now in such a large project? Like rudy mensioned, distortion, noise?

Anything that complex will be difficult. It will certainly be a learning experience. (problems that need to be solved) I suggest starting small. Also look to see how other people have done something similar.

This one is 100$ and I think can keep me busy for a long time, thanks again.
32x32 Analog Switch Matrix,ADV3200.
https://www.analog.com/media/en/technical-documentation/data-sheets/ADV3200_ADV3201.pdf

Of course you would need to make a custom circuit board. 0.5mm pitch is hard to solder. I hate fine pitched components. I do some, but I tend to leave most of it to the production department at work.


text:
What's wrong with my keypad and time program?
I really need help here. I'm a total noob in Arduino and this is my first Arduino project. I've been trying to get the keypad to be able to input time for my alarm clock project but I only managed to get the welcome part of the program. But then the display stuck at the welcome part only. I want to set alarm time by using the keypad only, and if the alarm time is the same as the time display, the buzzer should ring.
Plus, the deadline is in two days. I'm certain that there's no problem with hardware since all of the components (16x2 LCD, RTC DS1307, buzzer, 4x4 keypad) work properly when I use some basic tutorial coding for the components.
Please check what could be wrong in my code? I've tried to replace some of the codes but it had no change; the display's still stuck at the welcome part.
[Edit]I've added the "milli" code at the timedate() part. But I'm not sure, how to improve the alarm() part of this code? I can't input any key to insert the alarm time at this part.
If there's any update on what I've edit to my code later, I will edit this question's body. Thank you in advance.
#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
char buffer[3];
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {6, 7, 8, 9};
byte colPins[COLS]= {10, 11, 12, 13};
Keypad keypad= Keypad(makeKeymap(keys),rowPins, colPins, ROWS, COLS);

unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
Wire.begin();
rtc.begin();
pinMode(buz, OUTPUT);
lcd.begin(16, 2);
welcome();

rtc.setDOW(TUESDAY); //Set Day-of-Week to SUNDAY
rtc.setTime(18, 20, 00); //Set the time to 12:00:00     (24hr format)
rtc.setDate(18, 12, 2018); //Day, Month, Year
}

void loop() {
t = rtc.getTime();
Hor = t.hour;
Min = t.min;
Sec = t.sec;
tim = rtc.getTimeStr();
dat = rtc.getDateStr();
char key = keypad.getKey();

if(key == 'A'){
alarm();
}

if (key == 'C'){
digitalWrite(buz, LOW);
EEPROM.write(2, ASCII+6);
EEPROM.write(3, ASCII);
}
changealarm();
checkalarm();
timedate();
}

void checkalarm(){
if( Hor == h && Min == m)
{
delay(3000);
lcd.setCursor(0,1);
lcd.print("Hold C");
digitalWrite(buz, HIGH);
delay(3000);
}
}

void changealarm(){
buffer[2] = 0;
buffer[0] = EEPROM.read(0);
buffer[1] = EEPROM.read(1);
h = atoi(buffer);
buffer[0] = EEPROM.read(2);
buffer[1] = EEPROM.read(3);
m = atoi(buffer);
buffer[0] = EEPROM.read(4);
buffer[1] = EEPROM.read(5);
s = atoi(buffer);
}

void timedate(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Date: ");
lcd.print(rtc.getDateStr());

lcd.setCursor(0,1);
lcd.print("Time: ");
lcd.print(rtc.getTimeStr());
delay(3000);
lcd.setCursor(0,1);
lcd.print("Alarm: ");
lcd.print(h);
lcd.print(":");
lcd.print(m);
lcd.print(":");
lcd.print(s);
}
}

void welcome(){
lcd.setCursor(0,0);
lcd.print("Welcome");

lcd.setCursor(0,1);
lcd.print("To");
delay(2000);

lcd.setCursor(0,1);
lcd.print("TIMe Project");
delay(2000);
}

void alarm()
{
int j=0;
char key = keypad.getKey();
lcd.clear();
lcd.print("Enter Alarm Time: ");
lcd.setCursor(0,1);
while(j<4)
{
lcd.print(h);
lcd.print(":");
lcd.print(key);
lcd.print(m);
lcd.print(":");
lcd.print(key);
lcd.print(s);
lcd.print(key);
key=0;
}
delay(500);
}

Your function timedate() is called every time through loop() and it has a total of 6000ms of delay. During a delay, NOTHING can happen, not even checking for a keypress.
So, you would have to hold the desired key down until the key = keypad.getKey() statement is executed, which is a minimum of every 6 seconds.
Use of delay() for an interactive program in which user input can happen any time is not desired. Instead, there is a popular example Arduino sketch called "BlinkWithoutDelay" which us used as an explanation of how to avoid using delay() by letting your loop() function run at very high speed and only taking the desired action if the desired time has elapsed since some initiating action.
The more generic concept is called a "State Machine" and there are numerous websites that attempt to teach it, such as this one.
Be prepared to make significant changes to the structure of your program, however, as moving from delay() usage to state machine usage means a re-thinking of your loop() function -- you have to consider it running tens of thousands of times per second, and most of those times it doesn't do anything but check if something needs to be done -- most often the answer is "no, nothing needs to be done this time."

Thank you sir, I'll try to understand the concept first. I've edited the question as I'm quite not sure regarding the alarm() code part.

No, your alarm() function has an infinite loop, where you loop while j<4, but never adjust j.


text:
Cannot access SD card on WINC1500
I have a WINC1500 shield and have the Wi-Fi side working fine. I want to do some datalogging to the SD card and am having trouble getting it running. I have bought a 16 GB Sandisk card and inserted it. I have added the SD library, SD.h is included. However SD.begin() fails. I have a Mega2560 card (from Elegoo) so should be able to run the SD and wifi at the same time? Do I need to pass a parameter to SD.begin()?
The code below always prints "Card failed to initialise, or not present".
if(!SD.begin())
{
    Serial.println("Card failed to initialise, or not present");
}
else
{
    Serial.println("Card initialised ok");
}

https://www.arduino.cc/en/Guide/ArduinoWiFiShield#toc9

as @Juraj obliquely pointed out try 'SD.begin(4)'

and set pin 53 to output and set pin 10 high if you don't begin() the WiFi library

Do I need to pass a parameter to SD.begin()?

Yes, you need to pass the Chip-Select (CS/SS) pin number. What number depends on how you have it hooked up, the default is 10. (yours might be 4)
n.b. according to the docs a standard arduino can't use the WiFi, and the SD at the same time; presumably the mega has enough memory.

these docs

Thanks. It does need to be 4 for the WINC1500 with no jumpers cut. And yes the mega has enough memory for both.


text:
MFRC522: Firmware Unknown
Can someone help me what is the meaning of this sketch? It always outputs in the serial monitor:
Firmware Version: 0x1C = (unknown)
Scan PICC to see UID, SAK, type, and data blocks...

This is the code of the MFRC522 library I use:
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;          // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

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
   mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
   Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
   // Look for new cards
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
     return;
   }

   // Select one of the cards
   if ( ! mfrc522.PICC_ReadCardSerial()) {
     return;
   }

   // Dump debug info about the card; PICC_HaltA() is automatically called
   mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

The code is quite well commented, what don't you understand?  The outputFirmware Version: line is obviously output by PCD_DumpVersionToSerial(). Do you get any other output other than that? You should also see Scan PICC to see.... Are you not seeing that? Please be more explicit, and include a few more lines of output, to illustrate any repetition of output.

yes it also output but reader does not read the rfid card nor the rfid key , that is why I assumed that was the error

Try running the firmware_check example. In that sketch, it does say that only known versions are supported (Serial.println(F("Only known versions supported"));), so your first output line doesn't bode well

Please add a link to your post, to the library that you are using. Is it this one: https://github.com/miguelbalboa/rfid?

yes, thats the one I use.

The mention of unknown in the output line:
Firmware Version: 0x1C = (unknown)

isn't a good sign.
Run the firmware_check example to verify that first, before trying to run other code.
The unknown is output by line 1302 of MFRC522.cpp:
    default:   Serial.println(F(" = (unknown)"));

The firmware_check example states on line 49:
  Serial.println(F("Only known versions supported"));

So, your hardware (i.e. the reader) may not be supported.
The only thing I can suggest is try another reader. Also, read the README, there maybe some thing there, or contact the author and/or raise an issue to see if you can get support for your version of the firmware (0x1C) added.

Put a delay(5) after
mfrc522.PCD_Init();   // Init MFRC522

and it will show the correct firmware version.


text:
Arduino Uno Motor control using 2 Relays, 2 Limit switches and Bluetooth. Forward Reverse Stop
Modified existing project from this link:  Problem : Trigger limit switch to stop DC motor
I modified this code to control two relays which are wired to motor poles for Forward or Reverse movements until they physically reach a limit switch on either side.

Serial input of 'A' turns on one relay. If Limitswitch1 is pressed, this relay switches off.
It detects the current state of the system and awaits the Serial input of 'B' which then turns on the second relay. If Limitswitch2 is pressed, this relay switches off.

The issues are:

Please help with code - I require option where the two relays switch off on the serial input of letter 'S' and to add the corresponding state machine. Essentially to add a Stop function.
The limit switches work intermittently, sometimes they respond flawlessly, sometimes not at all. I have bought three different brands of switches to test but all have the same behaviour. I have pulled switches up and down with resistors in vain. I have performed button count test using code from this forum and confirm that the switch also behaves erratically. Can changes to code improve switch feedback?

Suggestions will be greatly appreciated.
const byte RELAY1 = 2;
const byte RELAY2 = 3;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;

const byte State_Idle = 0;
const byte State_Forward = 1;
const byte State_Reverse = 2;
byte currentState;

void setup(){
pinMode(RELAY1,OUTPUT);
pinMode(RELAY2,OUTPUT);

pinMode(LimitSwitch1, INPUT);
pinMode(LimitSwitch2, INPUT);

Serial.begin(9600);
currentState = 0xFF; // Force a change to enter the idle state
 }

void loop(){
// Check if we need to change state
byte nextState = currentState;
switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

// If there was a change, switch state and trigger enter condition
if (nextState != currentState)
{
    currentState = nextState; // Move in the new state
    switch (currentState)
    { // Entering the new state
    case State_Idle:
        // Switch both Relays OFF
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Forward:
        // Move Forward
        digitalWrite(RELAY1, LOW);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Reverse:
        // Move Reverse
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, LOW);
        break;
    }
}
}

It is not completely clear, what your problem is. I think you should try to debounce the switches. You can google this, there are many tutorials and even full libraries for this.

I would like to add a function to switch off the relays after letter 'S' is typed on serial monitor.  also Case_Stop to detect the state after being stopped.

@SB since this question was bumped to the homepage a lot of times, please complete it or close it. If you think the answer below fully answers your question, mark it as accepted (green tick on its left). If it does not solve it, please comment why so that you can receive further support

Here I am again for another exciting episode of "Fun with StateMachines".. ;)
Ok, basically you modified the code well, but you thought of the modification in the wrong way.
First of all describe what you want to do in simple words. Let's say you want that

When I'm moving in one direction and I receive the letter 'S', I immediately stop without waiting for the endstop

Consequently, you know that

you will have to add something when you are moving in one direction
this "something" will top you, which is what the endstop does

So, to implement this, you can do something like this:
switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

Now, your second problem is a bit harder to understand. When I read it, I immediately thought what chrisl already pointed out, which is switch bounces. But when I was halfway into completing this part of the answer I found out that.. no, the bounces are not what can give problems here, unless you are constantly writing 'A' or 'B' on the serial. So for the second part of the question please post your schematic and/or photos of the setup, so we can see if there is something not normal


text:
Best Arduino board to play sound
I'm looking to purchase an Arduino for a little robot I'm going to make.  The reason I've chosen Arduino is because it's much easier to use with servos and LEDs than a Raspberry Pi, but a nice little touch would be to have it play some sounds (voice recordings and mechanical SFX).  I was just wondering (now I'm not after opinions here, but looking more at how each of the boards have been designed) what the best Arduino board for playing sound is, or if they are all pretty much the same in this regard.
(Note 'pins' was the best tag I could find for this post for lack of a 'sound' or 'speakers' one.  If you want to edit it to something more appropriate please do)

(Sorry, I can't add this as a comment) If you're looking for a good audio processing chip then I would recommend you the VLSI VS1003 chip. It costs $2.30 (standalone) or $7 as a module (on eBay today) and it's able to play MP3 (even VBR), WMA, WAV (ADPCM) and even MIDI. Also it can record sound from mic or line in and encode it as ADPCM WAV. Supports streaming and has other powerful features, like filters and bass boost and is well documented (see the datasheet). You would need some data source for it, so either a st

If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.

I believe Due had proper DAC's. It also has a fair bit more muscle to do some processing besides playing the sound.

The Due has dual 12-bit DACs, and runs a 32-bit ARM core at 84MHz versus the 8-bit AVR core at 16MHz of most other Arduinos.


text:
Unusual behaviour when moving data to PROGMEM
I've got some working code with a definition that looks like this:
const unsigned char DynTextPositions[10][4][4] = {
    ...
};

Which is defined / referenced via a header:
#include <avr/pgmspace.h>
#ifndef DYNTEXTPOS_H
#define DYNTEXTPOS_H

extern const unsigned char DynTextPositions[10][4][4];

#endif

This data is being fed into a rendering function which draws lines based on the given positions. The data is read as follows:
float deltas[4][4];
// ...
deltas[n][k] = float(DynTextPositions[c+1][n][k] - DynTextPositions[c][n][k]) / 32.0;

As-is, this works just fine, as long as I've got my other scenes commented out. When I uncomment them, the combined data size seems to overflow the data segment. This is expected, because there's a fair bit of data, so I'm trying to move the DynTextPositions data into PROGMEM.
I've got PROGMEM working with some bitmaps, but it doesn't seem to work here. An example definition for a working bitmap is as follows:
PROGMEM const unsigned char ArduinoLogo[] = { ... };

However, as soon as I apply the PROGMEM attribute to DynTextPositions the rendering code seems to freak out - the positions appear to be all off-screen and completely wrong.
The only thing I can think of is that, for some reason, the data is either being considered signed rather than unsigned, or is getting corrupted along the way. Either that or the nested array is somehow being treated as a set of pointers.
Any idea why this might be?

Did you remember to change your code to read it from flash?

@IgnacioVazquez-Abrams I wasn't aware that I had to - I thought it was just memory-mapped elsewhere and the compiler took care of it. This may be the reason!

Not with PROGMEM. With __flash sure, but that isn't usable from C++.

I tried the solution pgm_read_byte(&DynTextPositions[c,l,k]) but still seem to be getting garbage values. Am I missing something?

Commas are almost certainly not what you want to use there.

Sorry, typo. I worked it out anyway. I'd reverted the PROGMEM and forgot to put it back when I switched read solutions! All working, in PROGMEM now :)

@IgnacioVazquez-Abrams If you want to add an answer explaining why it needs to be referenced differently, I'll accept it. Thanks for the pointers!

Including <avr/pgmspace.h> and using the PROGMEM qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various pgm_read_*() macros or *_P*() functions defined in avr/pgmspace.h. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.
Under GCC 4.7 or higher when writing C code, the __flash named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the others) available.


text:
Read battery voltage from battery which is powering arduino
I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?
I also use a lipo charging module to charge the battery.
Thanks for helping!

You can read the Arduino's supply voltage see here How to measure the supply voltage of Arduino without using an analog pin Alternatively use the internal 1.1V reference and a suitable voltage divider to read the lipo's voltage

I was just thinking if I use a step up module wouldn't the supply voltage be alwast 5V so I could use a analog pin without problems?

Yes, if the output of said module is always 5V, best would be to use one of those charger boards with over-current and over-discharge protection. Or use a reference design.

Do you recommand a specific charger?

Because I don't know any, I've never seen or used them.

You could use https://arduino.stackexchange.com/a/50771/521 trick to calibrate the supply voltage, then measure the LIPO voltage on an analog pin and scale it appropriately.

Yes, you should use a boost converter to convert the 3.7V from your battery to the 5V that the Arduino requires.
As I understand it, measuring voltage to determine charge level does not work well with lithium chemistry batteries since they hold a nearly constant voltage until they are almost completely depleted. Generally lithium batteries include a chip that measures current in and out and lets you query their charge level.

I don't think my battery has it. I bought this battery https://www.banggood.com/nl/Mobius-2-Camera-3_7V-820mAh-1S-LiPo-Battery-p-1105886.html?rmmds=myorder&cur_warehouse=CN and this charging module https://www.banggood.com/nl/TP4056-1A-Lipo-Battery-Charging-Board-Charger-Module-Mini-USB-Interface-p-1027027.html?rmmds=myorder&cur_warehouse=CN. I was thinking to buy this converter https://banggood.com/DC-DC-Step-Up-Step-Down-Module-2_5V-15V-To-3_3V-5V-Output-For-RC-Drone-FPV-Racing-Multi-Rotor-p-1303385.html?rmmds=wishlist

Yeah, you need a smart charging module then, as Paul says in a comment on the other answer.

What do you mean?

I mean that you should not use a dumb charger to charge a lipo battery. You need an intelligent charge controller.

I'm sorry but what has the charger to do with reading the lipo's voltage with the arduino?

What do you hope to accomplish by reading the battery voltage? It won't change until the battery is dead.

I will connect a screen where I want to display the battery level so I can seen when I need to recharge it. I thought I could do this by comparing the battery voltage to its minimal (3.7V) and it's maximal (4.3V).

That's the problem. It's my understanding that lithium chemistry batteries maintain a nearly constant voltage until they are almost completely exhausted, so measuring the voltage is not useful for gauging charge level.

On this website the show the percentage of capacity in function of the voltage read from the lipo so it should be possible? https://www.google.com/amp/s/blog.ampow.com/lipo-voltage-chart/