text:
How can I light one led from two different sensors?
I want to light one led with two sensors, the first one is a PIR and the other one is a Photocell sensor.
The idea is to turn on the led if the PIR sensor detects movement, and also to turn the led on if the room gets darker(detected by the photocell).
I managed to make a code, but with TWO led's, a different one for every sensor.
int ledPin = 13;
int ledPin1=12;
const int ldrPin = A0;
int inputPin = 2;
int pirState = LOW;
int val = 0;

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

void loop() {

  int ldrStatus=analogRead(ldrPin);
   if(ldrStatus<=400)
 {
    digitalWrite(ledPin, HIGH);
    delay(500);
    Serial.println("LED ON");
 }
   else digitalWrite(ledPin, LOW);
    val = digitalRead(inputPin);
      if (val == HIGH) {
        digitalWrite(ledPin1, HIGH);
          if (pirState == LOW) {
            Serial.println("Motion detected!");
            pirState = HIGH;
         }
      } else {
          delay(5000);
          digitalWrite(ledPin1, LOW);
            if (pirState == HIGH){
             Serial.println("Motion ended!");
             pirState = LOW;
           }
     }
  }

Where does pirState come from? It hasn't been defined or initialized. And what signal is on inputPin? The general logic for doing something depending on either of two conditions is if( condition1 || condition2 ){ // do something here }

To make it easier you could add two boolean variables 'dark' and 'motion'. Make it true if it is dark and false for light and the other one true for motion and false for no motion from the PIR sensor. Then you can do the if-statement as @JRobert wrote about.

pirState is from the PIR Sensor, i was thinking that it should always be on low if there is no movement, I don't know if its the right way to do that but for now works. And the inputPin is also from the pir sensor.

your problem is that you do not have the program clear in your mind ... you do not want I want to light one led with two sensors .... you want monitor two sensors and light one LED .... you said that you have done it with two LEDs, so just modify your code so that both sensors have to satisfy a goal before the LED is activated

int ledPin = 13;

int ldrPin = A0;

int PIR_Pin = 2;

void setup()

{

    Serial.begin(115200);

    pinMode(ledPin, OUTPUT);

    pinMode(PIR_Pin, INPUT);

    Serial.println("Started Monitoring!");
}

void loop()
{

    boolean lightStatus = ( analogRead(ldrPin) <= 400 ) ;
    digitalWrite(ledPin,  lightStatus);

    if(lightStatus) Serial.println("Light Triggered!");

    if(digitalRead(PIR_Pin) == LOW)
    {
         Serial.println("Motion Triggered!");
         digitalWrite(ledPin, HIGH);
         delay(5000);
         digitalWrite(ledPin, LOW);
     }
}

To keep it simple serial code is removed, if needed can be added easily that should not be a big issue.
Still this can be done in much more efficient way. This is just one solution.
Note: haven't complied/error checked the code as i am writing this on a phone. Hope it should work as intended, errors if any, shall be minor ones.  Comment below if any issues.
Update 1: added code to send triggered status over serial comm.
Update 2: corrected "Boolean" to be as "boolean"

Yes, it works. Now I just need to print some messages so I can figure out which sensor turned the led on, because I will have 8 sensors in total, 4 of each. Thank you for the help!

@gollum updated answer with code for serial comm. Do compile n test.

I got an error: "Boolean was not declared in this scope". @25mhz

Try "bool" it should work

That should be "boolean" my bad, dint check that.


text:
Strange behavior on bitwise operation
i am trying to write a simple program that writes the outputs of an accelerometer (which comes down to 3 analog inputs) onto an SD-Card.
I got the hole thing working fine (sending the values as simple strings), however i wanted to increase the frequency at wich the data is taken and therefore tried to send the data to the SD card encoded in binary, and therefore i am doing some bitwise manipulation.
Unfortunately some (as i think) strange things happen. When i add a simple bitwise manipulation the data on the SD card is pretty messed up. (I was unable to detect a pattern but it seems some Bytes are missing or or are there twice without any regularity):
Here is an example of a working version:
// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = (byte) (rawX>>2);
byte b2 = (byte) (rawY>>4);
b2 = b2 + (byte) (rawX<<6);
byte b3 = (byte) (rawZ>>6);
b3 = b3 + (byte) (rawY<<4);
byte b4 = (byte) (rawZ);
b4 = (byte)b4*4;
//b4 = (byte)b4<<2;

// get pressure
//temp = BMP180_getTemp();
//float a = 0;
//float a = pressure.altitude(BMP180_getPressure(), baseline);

unsigned long t = millis();

byte writeB[] ={
    b1,
    b2,
    (byte) (rawZ>>6), //replacing this with '(byte) ((rawZ>>6)|(0b11110000 & rawY))' will cause the error
//also replacing with b3 creates the error as well
    b4,
    (byte) (t>>16),
    (byte) (t>>8),
    (byte)t, (byte)0};

dataFile.write(writeB,8);

dataFile.flush();

As mentioned as a comment in the code changing the way the byte is calculated messes up my data on the SD card. I tried several other things however it seems that the following operations are causing the error: | & << >>  (However i am using some of them to calculate e.g. b2)
What i don't get is how changing how a byte is calculated affect the data output.
Maybe (probably) i overlooked some easy mistake but i cant figure out what is happening. Any help would be greatly appreciated since im working on this since quite a while.
(I am aware that the program does currently not transmit all necessary data but i startet from scratch and programmed step by step to locate/identify the error)

Please include a minimal program that compiles and demonstrates your problem. Ideally include actual and expected output.

It is unclear what you do with the code. If you try to use the whole memory by sharing the bits of a byte,you cannot use the arithmetic + operator. Instead use the | (bitwise or) operator

i indeed try to share the bits of a byte. i tried the bitwise or operator as well. However why can i not use add (in case e.g. i know the 4 last bits are filled with 0 and the first 4 i could add this to another byte from wich i know the first 4 bits are zeros.)

why can i not use add .... how do you know that you cannot? .... you have not shown the data, so it is impossible to guess what it happening

Your computation of b3 seems sane to me. “the data [...] is pretty messed up” is not a useful description of the problem. Please, edit your question to add: 1. the values of rawX, rawY and rawZ, 2. the values of b1, b2, b3 and b4 you would expect, and 3. the values of b1, b2, b3 and b4 you get instead.

Sorry for being unclear about how the data is messed up. The problem was not the computation of the values. I did not even checked them. I saw the data was not as expected because i was expecting a 0x00 every 8th byte, which was not there or only sometimes. To me it seemed as if some Bytes where lost or interchanged. Since the problem did vanish once i tried to send dummy values (eg every byte 0x11) i was unable to figure out how the data is mixed up.

Your way of sharing the bits between the three values seems a bit confusing. Your code for saving the bits is correct in the meaning of that you save all relevant information. Your bytes are shared in this way (H means high portion of value, L is the low portion of value):
     ____HX_____
b1: | 0000 0000 |
     _LX_ ___HY___
b2: | 00 | 000000 |
     __HZ__ __LY__
b3: | 0000 | 0000 |
     __LZ____
b4: | 000000 | XX |

This is a rather complex way of dividing the space. Also, since you are not using the remaining 2 bits of b4 you don't have to shift there.
When you are getting garbled values from your SD card, it wildly depends on how you are reading the bytes (you haven't shown us the code for that). As a suggestion I will explain how I would do it.

We have 3 values from analogRead(), which each have 10 bits. So in total we have 30 bits, which can be transmitted in 4 bytes (or 32 bits). When adding bits from another value, I think you can use the + operator (opposing to my comment) if the bits of the different values don't overlay (which should be anyway). For my part I like to use the bitwise or | to show more clearly, what is done there and to easier check for errors in alignment (easy to see in binary representation). Do as you like. I will use the | operator for now.
// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = rawX & 0xFF;
byte b2 = rawY & 0xFF;
byte b3 = rawZ & 0xFF;
byte b4 = (rawX & 0x0300) >> 2
          | (rawY & 0x0300) >> 4
          | (rawZ & 0x0300) >> 6;

The low portion of the values are saved in the bytes b1 to b3. The upper 2 bits of every value is saved left-aligned to b4 (The & 0x0300 isolates the upper portion, bit 9 and 10, in the values.).
You can read these values in this way:
rawX = b1 | (( b4 & 0b11000000) << 2);
rawY = b2 | (( b4 & 0b00110000) << 4);
rawZ = b3 | (( b4 & 0b00001100) << 6);

b1 to b3 are the start for our retrieved raw values. Then we add the other 2 bits to the raw values. For this we first isolate the bits from b4 from the positions we used in the upper code. Then we shift them to the left, until they are directly above the 8 bits of the start values.

Thanks for the detailed description! I am reading the data by opening the datafile with notepad++ using the HEX-Editor. The reason why i am sure the data is wring is simply because the 8th byte should always be 0x00. This is however not the case. I agree that using the | operator is more readable and i normally use it. Since it seemed to cause the error i tried to avoid it. I like your way of storing the data since the pattern is easier to understand. I tried your solution and it worked! Thanks a lot. I am still a little bit curious to why my code did behave so strange.

source: Stack Exchange

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

sort: votes


text:
Ethernet connection - how to send data from interrupt
I have question similar to old topic here Any way to pass EthernetClient to function outside of loop automatically?
I have in the main loop opening of the TCP server which is just maintaining the connection, but I need to send data from the interrupt rutine.
Can anybody tel me how to declare the connection globaly to be able to reference from event rutine and not from main loop only?
Thank you

That's probably a bad idea - this is far too involved and lengthy a task to safely perform in an ISR.  What you should do is set a volatile flag in the ISR to indicate to the main program loop that it would be appropriate to send some data.

use globals to store the data to be sent, and a flag that indicates data is ready, then check the global in loop() and response accordingly; it won't take a lot of extra time...

I need to stream data as much synchronous as possible so I'm looking for a way how to send it from ISR directly. Thanks anyway.

@jantkany - then you shouldn't be using TCP to begin with.   Doing this in an ISR is not going to work, and the delay of doing it in the main loop will be well within the norms of TCP traffic, if your program is well structured.

No surgery in the dr's office, you get the diagnosis and schedule an appt with a surgeon.

You don't, instead you set a volatile flag in the interrupt routine and/or append to a circular buffer and handle the actual sending the next time through in your main loop.
The time delay from deferring action from the ISR to the main loop code will be on the order of milliseconds, if that.

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


text:
Making profit from Arduino
I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

The Arduino itself is open, and you can use it to make commercial products.
Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.
Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


text:
Controlling motors and servo with L298N
I'm using an L298N to control the two motors of a robot car, and I also have a servo controlling the HC-SR04. The motors and sensor work fine together, and the servo and sensor work fine together. But when I put them in the code together, only the servo works. Code is
#include <Servo.h>

// motor one
int enA = 9;    //enable PWM for right motor
int rightFwd = 7;    //right forward
int rightBack = 6;    //right backward
// motor two
int enB = 10;   //enable PWM for left motor
int leftFwd = 5;    //left forward
int leftBack = 4;    //left backward

//ultrasonic sensor
int trig = 2;
int echo = 3;

//servo for looking left and right
//int servoPin = 8;

int runSpeed = 255;
int distance;
int leftDistance;
int rightDistance;
//int servoCenter = 100;
//int lookAngle = 60;

//Servo servoMotor;

void setup()
{
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(rightFwd, OUTPUT);
  pinMode(rightBack, OUTPUT);
  pinMode(leftFwd, OUTPUT);
  pinMode(leftBack, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
//  pinMode(servoPin, OUTPUT);

//  servoMotor.attach(servoPin);
//  servoMotor.write(servoCenter);
}

void loop()
{
  test();
}

void goForward()
{
  Serial.println("Going forward");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,HIGH);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,HIGH);
}

void goBackward()
{
  Serial.println("Going backward");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,HIGH);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,HIGH);
  digitalWrite(rightFwd,LOW);
}

void turnLeft()
{
  Serial.println("Turning left");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,HIGH);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,HIGH);
}

void turnRight()
{
  Serial.println("Turning right");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,HIGH);
  digitalWrite(rightBack,HIGH);
  digitalWrite(rightFwd,LOW);
}

void allStop()
{
  Serial.println("Stopping");
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,LOW);
}

int getDistance()
{
  //  Getting the distance from the sensor
  long duration, distance;
  digitalWrite(trig,HIGH);
  delayMicroseconds(1000);
  digitalWrite(trig, LOW);
  duration=pulseIn(echo, HIGH);
  distance =(duration/2)/29.1;
  Serial.print(distance);
  Serial.println("CM");
  delay(10);
  return distance;
}

//int lookRight()
//{
//  Serial.println("Looking right\n");
//  servoMotor.write(50);
//  delay(500);
//  int distance = getDistance();
//  delay(100);
//  servoMotor.write(servoCenter - lookAngle);
//  delay(100);
//  servoMotor.write(servoCenter);
//  return distance;
//}
//
//int lookLeft()
//{
//  Serial.println("Looking left\n");
//  servoMotor.write(servoCenter + lookAngle);
//  delay(500);
//  int distance = getDistance();
//  delay(100);
//  servoMotor.write(servoCenter);
//  return distance;
//  delay(100);
//}

void test()
{
  getDistance();
  goForward();
  delay(1000);
  allStop();
  delay(1000);
  goBackward();
  delay(1000);
  allStop();
  delay(1000);
  turnLeft();
  delay(1000);
  allStop();
  delay(1000);
  turnRight();
  delay(1000);
  allStop();
  delay(1000);
//  lookLeft();
//  lookRight();
}

I've commented out the servo parts; as it is, the motors and the sensor perform the test perfectly. Uncommenting the servo parts makes the servo and sensor work, but the motors stop.
I see from here that

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

I'm using 9 and 10 as the enA and enB pins respectively for the PWM of the motors, and the servo is on pin 8.
I built up the code from scratch, testing each function as I went, and it's all good apart from this problem. How can I fix this?

The comment you have found which is also on the Servo library page https://www.arduino.cc/en/Reference/servo and is the core of your problem.
On an Uno, you will have to change the PWM pins to 3,5,6 or 11 as the timer which provides the PWM for pins 9 and 10 is now being used for the Servo library.
This is probably the easiest option, especially if you are using an L298 module, as you should be able to just swap the leads.
Alternatively, there may be an alternative Servo library available which does not use that timer (a quick Google showed some candidates, but I have not tested).

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


text:
Motor shield leaves no pins accessible
I just bought a motor shield for my UNO, in the pic below:

Plugging it into the uno leaves no pins accessible on the board. I’d like to use it to build a robot car, but there’s nowhere to plug in the ultrasonic sensors. Do I need to solder some pins to the row at the top of the pic, or to the through-board holes on the right labelled A0-5?

According to tutorial, the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.
All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.
You can use analog pins as digital pins to connect the ultrasonic sensor.
Connection of I2C devices is possible on A4 and A5 pins.
The shield doesn't alow to stack a next shield, because it heats up.

You can use a "Screw shield" between the motor shield and the Uno to make access to the unused pins easier.

yes. you can solder pin headers or contact wires directly to the shield. if use pinheaders it is easier to use the pins for other purposes.
In the case of using ultrasonic sensor you should have to use digital pins along with the 5v and ground pins of the shield.

Just avoid using already-used pins...

yes for sure @frarugi87


text:
How to process 20-bit sensor data
I have an acceleration sensor (ADXL355) that returns 20-bit data in three bytes, formatted as 2s complement :

acc3 (bits 19-12) in byte register 3 (mapped to bits 7-0)
acc2 (bits 11-4) in byte register 2 (mapped to bits 7-0)
acc1 (bits 3-0) in byte register 1 (mapped to bits 7-4 while 3-0 are unused)

the acceleration value is taken as a signed 32 bit integer from the above 3 registers as follows :
int32_t acc32 = ((uint32_t)acc3 << 12) | ((uint16_t)acc2 << 4) | (acc1 >> 4);

if (acc32 & (1UL << 19)) acc32 -= 1UL << 20;

Then, I am doing some statistical analysis on acceleration values to calculate an offset trim as a signed 32 bit integer.
int32 off32;

This offset has to be written back to sensor as a 16 bit 2s complement value as follows :

offset high byte (bits 15-8)
offset low byte (bits 7-0)

The datasheet says that "The significance of offset bits 15-0 matches the significance of acceleration bits 19-4".
I found this rather tricky so I am asking how to convert this signed 32 bit offset integer to a 16 bit offset integer that follows the above specification.
I had this idea but don't know whether it is correct :
int16_t off16[i] = (int16_t)(off32[i] / 16);

sendSPI((uint8_t)(off16 >> 8));
sendSPI((uint8_t)off16);

Any comment should be greatly appreciated !

Other than the subscript [i], which looks suspicious, what you did
seems perfectly correct to me. Now, if I go nitpicking, I may suggest:

use a bit shift, as it is way cheaper than a division
round to nearest, rather than towards zero or minus infinity.

This gives:
int16_t off16 = (off32 + 8) >> 4;

Note that the bit shift behaves like a division that rounds towards −∞
(regular division rounds towards zero). Adding 8 achieves
round-to-nearest, with ties rounded up.

Thanks a lot for your answer ! Yes, subscript [i] shouldn't be there !
As far as the bitshift is concerned, I wasn't sure whether it works as a division in signed integers, that's why I chose a division instead.

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


text:
ESP8266 Wemos D1 min pro - how to change TCP_SND_BUF?
Is there any way to change the TCP send buffer size (TCP_SND_BUF) on this module ?
Now it is equal to TCP_SND_BUF = 2 * TCP_MSS = 2 * 1460 = 2920.
Editing lwipopts.h doesn't make any difference.
The same question applies to ΤCP_MSS, TCP_WND etc.
I am using v2 Higher Bandwidth variant. Platform is Microchip Studio with vMicro Arduino addon.

I finally figured it out the hard way :
https://github.com/esp8266/Arduino/discussions/8616

Install Git for windows (https://git-scm.com/download/win)
Install MinGW for windows (https://sourceforge.net/projects/mingw)
In MinGW installation manager, enable:

mingw-developer-toolkit
mingw32-base
mingw32-gcc-g++
msys-base

(not sure if all are necessary but just in case)
put C:\MinGW\bin in Windows PATH (check this https://www.rapidee.com)
reboot PC
rename C:\MinGW\bin\mingw32-make.exe to C:\MinGW\bin\make.exe
open bash terminal (just type bash in run)
(from now on assume that hardware files are in \Documents\Arduino\hardware\esp8266com\esp8266)
go to \tools\sdk\lwip2
optional: change lwip options in \tools\sdk\lwip2\builder\glue-lwip\arduino\lwipopts.h
(caution : NOT \tools\sdk\lwip2\include\lwipopts.h, this will be overwritten !)
type in bash: make install to build libraries in \esp8266com\esp8266\tools\sdk\lwip2\builder
type in bash: make clean to clean \esp8266com\esp8266\tools\sdk\lwip2\builder
finally copy new libraries to \esp8266com\esp8266\tools\sdk\lib

May all richnesses of the world reach you, my friend, for I have been going crazy the entire day yesterday trying to figure this out!

No, you can't.
The macro you are trying to tweak is for reference only and does not control the size of the buffer.
On the ESP8266 the IP stack (and much of the rest of the system) is precompiled as .a libraries. Changing things like the TCP_SND_BUF macro will never change what has been compiled into those libraries. Instead all it will do is cause problems of buffer overruns and corrupted data as other code is then given incorrect information about the size of the buffer.


text:
Waking Arduino from sleep with an ultrasonic sensor
I have a parking guide using an ultrasonic sensor (HC-SR04), based on the instructions here. I'm trying to modify the code so that the Arduino goes to sleep after a certain period of inactivity (say, 30 seconds), and wake again when the sensor 'sees' a car drive into the garage. The code here shows how to wake it with a solar panel.
However, the way I understand it, the solar panel is able to wake the Arduino because it doesn't need external power to work (because it's a solar panel). Would it be possible to do the same with an ultrasonic sensor (HC-SR04), which does need power?
It'll be running off mains power, but I don't want it to be drawing power when it's not needed.

In order to make the ultrasonic sensor work, the Arduino has to run some code to control it.  So it won't do anything while the Arduino is asleep.
What you can do is have the Arduino sleep for some reasonable amount of time, wake up and read the sensor, and then go back to sleep.  Maybe wake it up once every few seconds.  Do you really need to react to a car in the lot the millisecond it pulls in?


text:
Cycling through switch states
I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

Here's the code I've come up with:
#include <FastLED.h>

#define strip_pin     7
#define NUM_LEDS    15

CRGB leds[NUM_LEDS];
int distance;
int brightness;
int brightnesspin = 2;
int pin_switch = 3;

// variables to hold the new and old switch states
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
byte state = 0;

void setup()
{
  Serial.begin(9600);
  FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
}

void loop()
{
  delay(500);
//  Colour control
//##############################################
    newSwitchState1 = digitalRead(pin_switch);
    delay(1);
    newSwitchState2 = digitalRead(pin_switch);
    delay(1);
    newSwitchState3 = digitalRead(pin_switch);
    // if all 3 values are the same we can continue
    if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
    {

        if ( newSwitchState1 != oldSwitchState )
        {

           // has the button switch been closed?
           if ( newSwitchState1 == HIGH )
           {
                // increase the value of state
                state++;
                if (state > 3) { state = 0; }
                for (int i = 0; i < NUM_LEDS; i++)
                {
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                }
                FastLED.show();
            }
           oldSwitchState = newSwitchState1;
        }

//    Brightness control
//##############################################
  brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
    for (int i = 0; i<NUM_LEDS; i++)
      {
        FastLED.setBrightness(brightness);
      }
  FastLED.show();
  Serial.print("Brightness: ");
  Serial.println(brightness);
    }
}

The brightness control works fine, and the switch cycles through the colours once, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

The problem lies in your for cycle.

If (state == 1) you are switching the red colour ON.
If (state == 2) you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
If (state == 3), you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
Then you go back to (state == 1). All colours are already activated, so from this moment you get only white...

Solution:
for (int i = 0; i < NUM_LEDS; i++) {
  if (state == 1) {
    leds[i].red = 100;
    leds[i].blue = 0;
    leds[i].green = 0;
    Serial.println("Red");
  }
  if (state == 2) {
    leds[i].red = 0;
    leds[i].blue = 100;
    leds[i].green = 0;
    Serial.println("Blue");
  }
  if (state == 3) {
    leds[i].red = 100;
    leds[i].blue = 100;
    leds[i].green = 100;
    Serial.println("White");
  }
}

In your lines:
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}

The LEDs are set on, but are never turned off.
Sequence is:
1: Red leds turn on; strip appears red.
2: Blue leds turn on (the leds will probably actually look purple rather than blue here as the red leds are still on)
3: Green leds turn on (red and blue leds are already on); strip appears white
back to start:
1,2,3: nothing changes as all leds are already on, strip remains white.
I'd suggest adding:
leds[i].green = 0; leds[i].blue = 0;

to the state == 1 condition and
leds[i].green = 0; leds[i].red = 0

to the state == 2 condition.


text:
How do I get multiple readings(binary) based on my arduino output?
I am new to arduino and therefore not much experience in handling codes, please be forgiving and help me!
For my school project, make use of arduino to make 4 capacitive sensors (which has already been successful). Now I am trying to make use of the 4 sensors to be shown in a table format(one for each output) so that I can use that data to be plotted into either Excel or Matlab. Hence I would like to ask how do I group up my data into different columns? Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?
My arduino code is here:
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);
void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1 - just as an example
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);
 Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);

Serial.println(sensor1);  // print sensor output
    Serial.print("\t");
    Serial.println(sensor2);
    Serial.print("\t");
    Serial.println(sensor3);
    Serial.print("\t");
    Serial.println(sensor4);
 if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
  else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }

   }

And with that code above the output I receive when I use the serial monitor is:

Serial.println(sensor1);  // print sensor output
Serial.print("\t");
Serial.println(sensor2);
Serial.print("\t");
Serial.println(sensor3);
Serial.print("\t");
Serial.println(sensor4);

If you want 4 columns don't use println for each number, as that starts a new line.

Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?

Yes it's possible however I don't see how that makes anything easier.

Changing the println function really worked for me thank you! I prefer to change the codes into binary so that it could help with my data plotting (possibly graph). What kind of code could I use to change it into binary?


text:
Changing Arduino Outputs into Binary
I am new to Arduino so please give me some advice on this really simple problem. I am currently using an Arduino Mega in a school project to make 4 capacitive sensors which are supposed to receive an input when you touch the sensors, and I have programmed the arduino such that you will light up an LED upon touching the sensors.
Now the problem is after I light up the LEDs the serial data monitor gives me many different numbers when I am touching the sensors. Is it actually possible for me to tweak my program such that outputs of my sensor will show up as a single line of '0' when the sensor is not being touched and '1' when the sensor is being touched? This would really help me in the quantifying of some of the data I would wish to collect from my experiments with the sensors.
My code is
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);

void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);

   Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);
Serial.print("\t");
Serial.println(sensor1, BIN);  // print sensor output
Serial.print("\t");
Serial.print(sensor2, BIN);
Serial.print("\t");
Serial.print(sensor3, BIN);
Serial.print("\t");
Serial.print(sensor4, BIN);

    if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
   else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }
   }

and the output that I end up receiving is

Hence it would be really great if I could tweak my code such that the output on the serial monitor would be '0' when there is no output(Not touching sensor) and '1' when there is an output (touching sensor)
Thanks a lot for the help once again!

It sounds like what you want isn't really "binary", nor the bit-to-characters expansion of the touch readings.
Rather it sounds like what you want to do is to print the character '0' or '1' for the state of each button.  You already have the decisioning code for your outputs, so you can simply extend it for the serial prints:
if(sensor1 >= 1000) {
   digitalWrite(3,HIGH);
   Serial.print("1");
} else{
   digitalWrite(3,LOW);
   Serial.print("0");
}

and so on, with the next set having tabs and the last a newline.
Worth noting, intermixing the printing and digital outputs will put some time delay between the outputs (potentially quite a bit if the evaluation gets ahead of the serial buffers), so another option could to do all the outputs and then all the prints, or store the decisions in a bit mask for later printins, etc.

capacitiveSensor returns an analog value so you need to set a threshold for the point where 0 (AKA false) becomes 1 (AKA true):
long touchThreshold = 123;  // Adjust this according to your application

...
boolean sensor1 = (cs_2_4.capacitiveSensor(50) > touchThreshold) ? true : false;

If you don't recognize that syntax, it's the conditional operator but you could just as well use if.


text:
About Corrupted LM35 IC and Arduino port problem
I have one Arduino Uno which was working fine by below circuit(link):

But when I have connected the new bought the LM35 Ic by the below connection:

The Arduino UNO don't be recognized by the my Ubuntu OS as you can see below:

And by removing the LM35 connections, the Arduino don't be recognized again. I have damaged two Arduino Uno board by this mistake and ...
So I don't know why this happened and for repairing the damaged circuits I hope find out which part of the Arduino circuit are probably damaged?
Thanks.

Ttyusb? Sounds like you're using cheap Chinese clones. Good luck with that...

Can you be specific regarding which LM35 variant and which pin you connected it to? Have you tried a standalone circuit?

@Dave_Newton, I can see the ??cxz LM35 DZ on the IC which i don't know what is the two ?? character on the IC, but I googled it and i guess it is this kind, I found the all lm35 DZ types pins are the same and my circuit connections is right ( based of this datasheet).

@Dave_Newton,  For the third part of your question, I used the LM35 DZ type on the main circuit with this shematic (like the above)

@sosa FYI if you use @ somebody with something other than what the autocomplete provides there's no notification. This isn't a schematic--I can't tell what pin you've hooked the LM35 to. It's unlikely the issue is caused by the LM35 itself; have you tried a circuit with just the LM35 as a sanity check?


text:
avrdude: stk500_recv(): programmer is not responding Arduino LCD_I2C Upload problem ( port not found and ...)
i have problem to upload the LCD I2c Example program to Arduino UNo. the code are shown below:
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.init();
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(3,0);
  lcd.print("Hello, world!");
  lcd.setCursor(2,1);
  lcd.print("Ywrobot Arduino!");
   lcd.setCursor(0,2);
  lcd.print("Arduino LCM IIC 2004");
   lcd.setCursor(2,3);
  lcd.print("Power By Ec-yuan!");
}

void loop()
{
}

the schematic is like the below photo:

but i get this error:
Sketch uses 3382 bytes (10%) of program storage space. Maximum is 32256 bytes.
Global variables use 327 bytes (15%) of dynamic memory, leaving 1721 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thank.

try uploading some other sketch ... you will find that it is not problem to upload the LCD I2c Example program, it is problem uploading any program

Thanks @chrisl, the avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program helped me, the problem was solved by changing the USB Cable and removing the I2C pins from the Arduino Pins ( SCL & SDA Pins : A4 and A5).

@jsotola, the Problem was only with upload the LCD I2c Example program, and solved by the above solution (  changing the USB Cable and removing the I2C pins from the Arduino Pins )

@sosa are you saying that other programs would load correctly without changing the USB cable and removing I2C pins?

@jsotola, if i have not removed the SCL and SCA pints, Yes.


text:
Serial communication between NodeMCU and Arduino doesn't work when I try to use the DC jack or Vin
I have a unidirectional communication from NodeMCU (ESP8266) -> Arduino UNO. The communication works when I power both the devices to my computer. Note that since it is from NodeMCU to Arduino only, I don't use a voltage regulator. However, when I use a battery supply 9V and connect to DC jack or 9V battery, the serial communication doesn't work. I tried even with the voltage regulator.
It is mentioned that I use something between 9V-12V in the spec. Is it not working because 3.3V/5v from NodeMCU is not sufficient? How do I fix this problem?

Currently for the voltage regulator "high", I am supplying 5V from
Arduino. Should I provide another supply to pass 9v?
Does it power on if I provide 5V to DC jack or Vin?

Please rephrase you question into something understanteble

9V "transistor" (PP3) batteries are very weak. They barely provide enough current to power the Arduino, let alone a power hungry device like an ESP8266.
You're basically trying to tow a caravan with a skateboard.

What should I use? 9V is sufficient to power arduino for a simple blink program

AA batteries or Lithium ion.


text:
Uni-directional communication between NodeMCU and Arduino spits out garbage
I am sending data from ESP8266 (NodeMCU) to Arduino using serial and 9600 baud rate on both sides. Since it is uni-directional and from NodeMCU to Arduino, I am not using a voltage regulator and I have connected tx (Software Serial) of NodeMcu to Rx of Arduino. I've connected the usb of nodeMCU to my computer. I've done the same thing to power Arduino.
Here is some sample code on NodeMCU:
#define Arduino_RX 4 // D2
#define Arduino_TX 5 // D1
SoftwareSerial ArduinoSerial(Arduino_RX, Arduino_TX); // RX | TX

void setup() {
  Serial.begin(115200);
  ArduinoSerial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");
}

void loop()
{
    ArduinoSerial.println("hi");
    Serial.println("hi");
    delay(1);
}

Code on Arduino
#define ESP8266_RX   2
#define ESP8266_TX   3
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(ESP8266_RX, ESP8266_TX); // RX | TX

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);     // communication with the host computer
    ESPserial.begin(9600);
    Serial.println("Ready");

}

void loop() {
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }
}

Thank you for your question. Could you please edit it and really make your question clear. For example, what do you expect to receive and what do you actually receive?

Software serial doesn't always work to well at 9600. Try 56k. Also consider the esp is 3.3v and the Arduino is 5v.

many ESP8266 modules default to 74880 baud rate

Tried with all the possible baud rate without avail. One thing to note is this worked couple of days ago and I started seeing garbage recently.

Why dont you try to use the default Rx and Tx pins on of nodeMCU.
or in the Arduino code why not change the baud rate to 115200.

Have you tried extending the delay on the ESP so it has chance to clear the buffer before sending more data?

https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
Do you GND them via your PC USB? Try connecting their GND as well.
External power could be an issue as well, I am not aware of power consumption of ESP when they do stuff with their WiFi.


text:
Help with 1-Wire to I2C translate
Please, someone.
I want to use a temperature sensor (DS18B20) in an I2C only shield (Tentacle Mini), but this sensor is One Wire only. Can I write an I2C code to change the 1-Wire to I2C for this sensor? I think to use the (DS2482-800) bridge, but I don't know how to do...
Thanks!

Can't you connect the one-wire device (and if needed pullup resistor) to some other pin at the header rather than through the shield?

I recently wrote a Cosa TWI device driver for the DS2482. The example sketch actually uses a DS18B20. For further details please see https://github.com/mikaelpatel/Cosa/tree/master/libraries/DS2482.

An alternative is to use the I2C SDA pin to both I2C and 1-Wire.

As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the  DS28E17, a module that could translate the the 2 methods of communication. It should work but I havent tested it.

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.
Hope I helped you.

authors: Фёдор Татару


text:
What's the problem with program , continously beeping buzzer
I have used PIR motion sensor with arduino Uno r3, alongwith one piezo buzzer. and the program is as
 /*
 * PIR sensor tester
 */

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;
int piezoPin = 11;
// variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);
  pinMode(piezoPin, OUTPUT);
  Serial.begin(9600);
  // declare sensor as input

}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);
    tone(piezoPin,300,160);
    delay(150);

    // turn LED ON
    if (pirState == LOW) {
      // we have just turned on

      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW);
    tone(piezoPin,0,0);
    delay(300);

    // turn LED OFF
    if (pirState == HIGH){
      // we have just turned of

      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}

but it supposed to ring buzzer at the time of pir motion sensor getting signal. But buzzer continuously ringing and at the time of pir sensor getting signal, it just ring louder. What is the problem in program``

Do you have a "buzzer" or a "transducer"? One makes sound by itself when provided with power, and the other needs an audio signal. Your code is for the latter. If you have the former it won't work right.


text:
Pin change interrupt does not work properly to wake up arduino from sleep mode
I am building a timer circuit using Arduino Pro Mini Atmega168p 5v 16MHz (which later supposed to be become to adjustable one).
Here is the current breadboard view.

(I am supposed to use SS relay at place of that green thing. I am not sure if that item is correct SS relay in Fritzing)
Here is the program code I wrote.
#include <PinChangeInterrupt.h>
#include <PinChangeInterruptBoards.h>
#include <PinChangeInterruptPins.h>
#include <PinChangeInterruptSettings.h>

#include <avr/sleep.h>

// LED to indicate timer is active.
const int ON_LED = 5;
// It should be high when timer is active.
// Connect to relay.
const int PUMP_SWITCH = 6;

// Button to start timer running.
const int START_BUTTON = 8;
// Button to stop timer forcefully.
const int STOP_BUTTON = 9;

volatile boolean timer_running;
volatile int timer_start_time;

// TODO: Make it volatile once timer has mdified as configurable.
volatile unsigned long timer_time = 0;

void enter_sleep_mode() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sei();
  sleep_mode();
}

/**
 * Activate timer.
 */
void start_timer() {
  if (!timer_running) {
    // Time period in milliseconds.
    timer_time = 30000ul; // 30 seconds

    timer_running = true;
    timer_start_time = millis();
  }
}

/**
 * Stop timer.
 */
void stop_timer() {
  timer_running = false;
  timer_start_time = 0;
}

void setup() {
  timer_running = false;
  timer_start_time = 0;

  // Configure output pins.
  pinMode(ON_LED, OUTPUT);
  pinMode(PUMP_SWITCH, OUTPUT);

  // Configure pins for input push buttons.
  pinMode(START_BUTTON, INPUT_PULLUP);
  pinMode(STOP_BUTTON, INPUT_PULLUP);

  // Attach interrupt handlers
  // Buttons are with pull up resistors so listening for 'falling' (voltage).
  attachPCINT(digitalPinToPCINT(START_BUTTON), start_timer, FALLING);
  attachPCINT(digitalPinToPCINT(STOP_BUTTON), stop_timer, FALLING);
}

void loop() {
  if (timer_running) {
    digitalWrite(ON_LED, HIGH);
    digitalWrite(PUMP_SWITCH, HIGH);
    // TODO: Handle the case when return value of millis() goes back to start from zero
    if ( (millis() - timer_start_time) >= timer_time ) {
      // Timer elapsed the required time period.
      // So, stop the timer.
      stop_timer();
    }
  }
  else {
    digitalWrite(ON_LED, LOW);
    digitalWrite(PUMP_SWITCH, LOW);
    // Nothing to do If timer is not running.
    // Save power!!
    enter_sleep_mode();

    sleep_disable();
  }
}

The problem is timer does not work when pressing START button starting from third click. Two initial clicks works OK and timer functions as it should be. I think it does not wake up properly from sleep mode. However, wondering why it works for two initial clicks??
Please help me to identify the problem.
I don't have much experience in writing Arduino code.
Thanks

Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.

@MikaelPatel That is great! You are right. I found my mistake. I was wrongly declaring volatile int timer_start_time; where timer_start_time variable is supposed to hold return value from millis()
Now I declared it as volatile unsigned long timer_start_time; and it worked! :)
Could you please make it an answer so I can select?
Thanks

Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.
The declaration of timer_start_time should be paid special attention.
Good luck with your project!

I could identify my problem and fixed it by declaring timer_start_time and   as unsigned long. It should be wide enough to hold return values from millis(). Thanks!

Please help me to identify the problem.

it is always very easy to solve this type of problems, if you just follow some common sense.
1) decompose your functionality  into manageable blocks. for example, one is PCINT - can you blink an led with it - and another is going into sleep - can you put the mcu into sleep - and the next is to walk up from sleep - does your mcu support that? what has to be true for that to happen? ...
2) test individual blocks on their own.
3) integrate them into one functional program.
don't co-mingle them day 1. tackle only what you can manage. no more and no less.


text:
Using an IR sensor from another manufacturer
I am currently trying to create a line tracing robot with my Arduino Uno.
I have an IR Sensor (http://support.robotis.com/en/product/auxdevice/sensor/irsensor_manual.htm) but I am not sure if I can use this for my Arduino.
Can someone please tell me if I can? Thanks in advance.

You can use anything you can write code for.

Yes, you will need to connect the sensor ADC line to an ADC input on the Arduino and calculate the range from the analogread result.  You should be able to use one of the Sharp sensor libraries, although you may need to apply a correction factor to the distance results.

Would the ADC input be the analog in bit of the arduino (i.e. A0, A1...)?

You are correct, any of the A# analog pins.


text:
Getting current epoch time in seconds and milliseconds
Using Arduino Yun.
My code:
time_t today;
time_t now;
...
void setup() {
  time(now);
...
  Serial.println( asctime(gmtime(&now)));

What I get is:

Sat Jan 01 00:00:00 2000

I am expecting something like this:

1507572195.825

How do I get the number of seconds and milliseconds since the Linux Epoch?

I think that what you are looking for is the function now(); which returns the current time as seconds since 1 Jan 1970. Read more about the Arduino Time Library .

This may be of more interest - how to get the time from the Linux processor (which if you are online should be correct) rather than some random number the Arduino defaults to...

now(); is giving me the number of seconds from when the script started running rather than from Jan 1970.

Majenko - Getting very close. Using:
if (!date.running()) {
date.begin("date");
date.addParameter("%s");
date.run();
}
I get seconds. How would I get seconds and a partial second like :1507586961.159

You may try +%s.%N as a parameter. On a standard Linux distro this gives seconds and nanoseconds. I have no Yun to test that though.

@Edgar Bonet:
Unfortunately %N does not return nanoseconds on the Yun. It just gets echoed back like it is text %N. Using +%s.%N get me 1234567890.%N


text:
Main loop delay behaviour with interupt
This question is not for a project, I am just trying to understand what happens and why.
The sketch below works as expected as long as the ISR trigger is FALLING. The red led in the main loop is blinking, apparently without any disturbance from the interrupts.
The question is what goes wrong, and why, when the ISR trigger is set to LOW.
int sensorPin3=3;
int ledPinGreen=12;
int ledPinRed=11;
int sensorStatus;
byte ledGreenStatus;

void setup() {
pinMode(ledPinGreen,OUTPUT);
pinMode(ledPinRed,OUTPUT);
pinMode(sensorPin3,INPUT_PULLUP);
ledGreenStatus=HIGH ;
Serial.begin(9600);
}

void loop() {

attachInterrupt(digitalPinToInterrupt(sensorPin3), sensorOn, LOW);
digitalWrite(ledPinRed,HIGH);
delay (5000);
digitalWrite(ledPinRed,LOW);
delay (5000);
}

void sensorOn()
{
static unsigned long lastInterruptTime=0;
unsigned long interruptTime=millis();
if(interruptTime-lastInterruptTime>100)
{
digitalWrite(ledPinGreen,ledGreenStatus);
ledGreenStatus =! ledGreenStatus;
lastInterruptTime=interruptTime;
}
}

If the sensor is activated and the signal on interrupt pin 3 is LOW, sensorOn will be executed. What happens if the ISR has been executed once? Does the program return to the main loop to the place where the interrupt was initiated and then right back to the ISR, or does it stay in the ISR without getting back to the mainloop for as long as the signal stays LOW?
If the sensor is activated for a couple of seconds:
1) if the program keeps running the ISR, I would not expect activity from the red led (main loop), but that led is blinking, with delay of about 2 seconds (without the interrupt that should be 5 seconds).
This way it looks to me that the program returns to the main loop, but the delay time is wrong, so it doesn’t return to the right place, or the timing is not correct anymore. Why doesn’t this happen with the ISR trigger set to FALLING? Is the amount of interrupts disturbing the timing of the main loop delay?
2) if the program keeps executing the ISR but returns to the main loop every time in between, I would expect the millis() to be updated every time. In that case I would also expect the green led to blink because of the debouncing time. However the green led is not bliking. This makes me think that the program stays in the ISR so the millis() are not updated and the green led won’t blink.
But that doesn’t match with the red led behaviour.
3) if the sensor is only activated for a short amount of time, the red led turns on or off the moment the signal on the interrupt pin is no longer LOW. No visible delay. I don’t understand why a longer LOW time on the interrupt pin makes a blink with about 2 seconds delay and a short LOW time makes no delay at all.
Thank you in advance for your help!

The question is what goes wrong, and why, when the ISR trigger is set to LOW.

edge vs. level triggered interrupts.
Read the datasheet.


text:
Timer STM32 #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting
I have installed the library of TimerInterrupt_Generic for ArduinoSTM32 module via Arduino IDE, so i have tried to test the example of library as you can see below:

and i have gotten this error:

TimerInterruptLEDDemo:45:4: error: #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
   #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
    ^
In file included from /home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/examples/STM32/TimerInterruptLEDDemo/TimerInterruptLEDDemo.ino:64:0:
/home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/src/TimerInterrupt_Generic.h:86:4: error: #error Unsupported Board! Please check your Tools->Board setting.
   #error Unsupported Board! Please check your Tools->Board setting.
    ^
exit status 1
#error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.

Also, This question is asked here:
https://github.com/khoih-prog/TimerInterrupt_Generic/issues/2

The Roger Clark's STM32 core  you're using is not currently supported. I don't know in the future if I can add that core into the supported list.
You have to use this Arduino_Core_STM32.
Convert to new core by following the intructions in Getting Started

I have not installed the rogerclarkmelbourne, my STM32 Module is stm32duino, but your suggestion for changing the STM32 board module is working and solved the TimerInterrupt_Generic, problem.


text:
ESP32 programing error (A fatal error occurred: Timed out waiting for packet content )
I am trying to find the proper model of my esp32 MCU and find out the reason for below errors:
esptool.py v3.1-dev
Serial port /dev/ttyUSB0
Connecting........__
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 30:ae:a4:26:6f:44
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...

A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content

My ESP32 type and the board setting are shown below (link) :

Thanks.

In case where the upload procedure with esptool.py starts successfully but fails as soon as the baud rate is set to the high baud rate selected in Tools menu, select a lower baud rate in Tools menu.

This can also be caused by how certain pins are wired, if pin 12 is high at boot, programming will also fail with this message.


text:
ESP8266 SPIFFS file not found
I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.
In the set up, I refer to the following function to read the file:
String readTemplatefile(){
  String retval ="";
  File fr = SPIFFS.open("/templatecfg.htm", "r");

  if(!SPIFFS.exists("/templatecfg.htm")){

    Serial.println("Template file not available ");
    }
    while (fr.available()){
        retval += char(fr.read());
      }

fr.close();
Serial.println("Template file = ");
Serial.println(retval);
return retval;
}

I always get 'Template file not found'. I have
SPIFFS.begin();

at the beginning of the setup function
My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.
Thanks in advance to any help.

Is the file there?  Is the media formatted in the right format (FAT? rather than NTFS which Windows will default to)

Did you mount the filesystem with SPIFFS.begin()?  Have you tried opening the "/" directory and listing the files, so you can confirm what your sketch sees as the available files?

@CodeGorilla: SPIFFS, not SD ;)

run the included FS browser example sketch and see how it works. yes, your flash settings can affect SPIFFS, if they are wrong. make sure the IDE size (ESP.getFlashChipSize()) and the physical sizes (ESP.getFlashChipRealSize()) match up. google the esp lib functions for docs

SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.

@dandavis Yes, I had SPIFFS.begin() in my setup routine.
I ran a sample sketch and was able to see the a file on the device, so I routed round the code some more and found than an included library was ending SPIFFS after it had performed a file read. This was the issue. Thanks all for your consideration, but the code I had was fine, just the included library was mis-behaving.

what library? so we learn


text:
softwareserial between arduino uno and esp8266
I have an Arduino UNO and HUZZAH ESP8266  module.  I need to send data between Arduino UNO and ESP module via Software Serial.  Right now I have the ESP module write data and Arduino UNO display data, but not working. When I run the Arduino UNO  and open its Serial Monitor, nothing is printed using below source code.

ESP8266 RX PIN connected to Arduino UNO PIN 2.
ESP8266 TX PIN connected to Arduino UNO PIN 3.
Using the FTDI cable that came with HUZZAH ESP8266 to power this module.  I just individually connected the RX and TX pins to the ARDUINO PIN 2 and 3 as mentioned above.

Any ideas what why not working? Below is code for both modules. Thanks,
Arduino UNO
#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start hardware Serial communication
  Serial.begin(115200);

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

}

void loop(void){

if (ESPserial.available()){
  Serial.println("ESP available!!!");
  Serial.println(ESPserial.read());
}

}

HUZZAH ESP8266
#include <ESP8266WiFi.h>

#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start the software serial for communication with the Arduino UNO component
  ESPserial.begin(57600);

  //TODO: setup Wifi
}

void loop(void){
   ESPserial.write("This message generated by ESP module.");
   delay(500);
}

Make sure that:

RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.

Adding to the above answer. UNO's TX is at 5V , while ESP8266 's RX is at 3.3V, as it is a 3.3V module. So its better to use a resistive divider to bring UNO' TX to 3.3V and then feed to ESP's RX, instead of directly connecting them eachother.

And conversely, the 3.3V TX pin of the ESP8266 is usually enough to drive the Uno's 5V RX pin.

//ESP
#include "SoftwareSerial.h"

SoftwareSerial ArduinoUno(D2,D3); //Rx, Tx

void setup() {

Serial.begin(9600);

ArduinoUno.begin(4800);

pinMode(D2, INPUT);

pinMode(D3, OUTPUT);

}

void loop() {

}

/******************************************************************************/

//UNO
#include "SoftwareSerial.h"

SoftwareSerial ArduinoUno(3,2); //Rx, Tx

void setup() {

Serial.begin(9600);

ArduinoUno.begin(4800);

}

void loop() {

  if(ArduinoUno.available() > 0){

    //float val = ArduinoUno.parseFloat();

    Serial.println(ArduinoUno.read());

  }

  delay(30);

}

format your code properly (CTRL+K)


text:
convert byte and float to char
I am trying to send sensor values to internet via enc28j60 module and web client example.
My problem is that i chose byte and float form for some sensors i can't convert these values to char form.
Code example below
UVSensorValue = analogRead(A0);               // UVSensorValue is in byte form
concentration = 1.1*pow(duration,3)-3.8*p...  // concentration is in float form

I want to store them in a char variable like this:

param = "uv=5&temp=23.2&dust=0.62..."

And send them here:
ether.browseUrl(PSTR("/measures?"), param, website, browseUrlCallback);

I tried strcpy function or String convention but nothing worked. I know its a silly question however i stuck and cant find solution.
If someone could help me i would be pleased. Thanks in advance!

You want dtostrf()...


text:
Arduino Video player?
I want to play video from SD card   by using arduino mega 2560 and TFT 3.2" touch screen is it possible ?
if yes please tell me.
thanks in adavance

No, it is not possible.

@Majenko is it possible to play video from mobile via USB cable

You mean watch a video on your phone? Sure. Plug the SD card into your phone and open the video.

No ,is it possible to play video from mobile  on arduino  display via USB cable

If you can't play it from a local card then what makes you think you can play it from a remote connection?

It is not possible to play video on an Arduino from any source. The closest you could get would be to cycle through a set of images somewhat slowly.

The easiest way to understand why this is not possible is to "do the numbers", i.e. calculate the max frame rate for the TFT and image read from SD when using an Arduino. Even simply trying to read a file without decompression and writing to the TFT with give a very low frame rate.

An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.
The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.
We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/
On the same link you'll find also the youtube links for a video guide.


text:
door protector arduino program
Please check the arduino program given below and help me to find out error.
The program is for following hardware.
GSM 800 module
Arduino Uno board
Limit switch(2)
We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.
We run this program & it run but it sends the massage repeatedly after some time.
Please help me to find out error..
my ARDUINO code is
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;
bool i = true;
bool j = true;
bool k = true;
bool l = true;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {

  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void loop() {
  buttonState1 = digitalRead(Main);
  if (buttonState1 == HIGH && i == true ) {
    digitalWrite(Main_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Main Door is closed");
    Serial.write(0x1A);
    delay(5000);
    i = false;
    j = true;
  }
  else
  { if (buttonState1 == LOW && j == true )

    { digitalWrite(Main_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91---------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Main Door is open");
      Serial.write(0x1A);
      delay(5000);
      i = true;
      j = false;
    }
  }

  buttonState2 = digitalRead(Store);
  if (buttonState2 == HIGH && k == true) {

    digitalWrite(Store_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(5000);
    k = false;
    l = true;
  }
  else
  { if (buttonState2 == LOW && l == true)
    {
      digitalWrite(Store_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91------------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Store room is Open");
      Serial.write(0x1A);
      delay(5000);
      k = true;
      l = false;
    }
  }
}

it sends the massage repeatedly after some time Which message? How long is some time is it after a certain number of button presses? after 5 minutes of nothing happening?

it is not depends on time but when switch is close(Door closed)(NC) it not repeated but when switch is open(door open)(NO) it send message repeatedly

@OlinLathrop Are you telling a grown man to be ashamed of himself? The code is readable enough. +1 to OP because this isn't a forum for shame.

I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}

I want to send Same message on two numbers how should I done

You should probably post another question giving enough detail to answer it. I want to send Same message on two numbers What numbers? In what situation?


text:
door protector using arduino uno and GSM sim800 module
Please check the arduino program given below and help me to find out error. The program is for following hardware. GSM 800 module Arduino Uno board Limit switch(2)
We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.
We run this program & it run but it sends the massage repeatedly after some time. Please help me to find out error..
    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;
    bool i = false;
    bool j = false;
    bool k = false;
    bool l = false;
    int buttonState1 = 0;
    int buttonState2 = 0;
    void setup() {

      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void loop() {
      buttonState1 = digitalRead(Main);
      if (buttonState1 == HIGH && i == false ) {
        digitalWrite(Main_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Main Door is closed");
        Serial.write(0x1A);
        delay(5000);
        i = true;
        j = false;
      }
      else
      { if (buttonState1 == LOW && j == false )

        { digitalWrite(Main_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91---------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Main Door is open");
          Serial.write(0x1A);
          delay(5000);
          i = false;
          j = true;
        }
      }

      buttonState2 = digitalRead(Store);
      if (buttonState2 == HIGH && k == false) {

        digitalWrite(Store_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(5000);
        k = true;
        l = false;
      }
      else
      { if (buttonState2 == LOW && l == false)
        {
          digitalWrite(Store_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91------------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Store room is Open");
          Serial.write(0x1A);
          delay(5000);
          k = false;
          l = true;
        }
      }
    }

To avoid duplication of effort here's a link the exact same question posted on the electronics site: http://electronics.stackexchange.com/questions/290062/door-protector-arduino-program

what if the door is open less than 11.5 seconds?

@dandavis  message does not repeated .


text:
Reading Multiple switch inputs
I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?

You could use all your Uno pins, but none would be left for the output. Or you could use a parallel in serial out shift register.

Using a matrix is probably the best route - just like a keypad. 5x4 (9 pins) gives you 20 buttons with no extra hardware needed.

You could use a MCP23017 or similar.  Its an IC that provides 16 IO ports via I2C, I think you can have 4 of them so that should be enough for both hands.
Or you could use resistors.  All the buttons are connected to a single analogue port.  The resistors are chosen so that when you press any combination of buttons you will get a unique reading at the port. So if you press button one and get a reading of 100, press 2 and get 150, press 3 and get 200, etc.  So buttons 1+2 give you 250, 2+3 gives you 350 and 1+2+3 gives you 450.  The problem with this is the maths get out of hand very quickly and the IC is < $1.

I'd second the use of the MCP23017, have used this chip in several projects with good results, you can connect 8 of them together which gives 128 I/O pins.
Off the SDA/SCL pins UNO R3
Link Adafruit MCP23017
Also on Ebay from other suppliers.


text:
How can I record a push button sequence and store it in an array
I have 3 push buttons and I want to record the sequence in which they are pressed in array of size 10,i.e, I want to record 10 values for example {1,1,2,2,3,3,1,1,1,3}. I want to blink an array of 3 LED in the same pattern in which the buttons were pressed. I have two extra push buttons for putting the arduino in record and play modes respectively. If any one can suggest how I can store the values in the array I will really be very thankful. I am also facing the problem because it's very difficult to manage the bouncing of the buttons simultaneously.

is it possible to show your wiring pattern?

You can create an array like this, make it global to easy access it:
int states[10];

And the current index:
int index_state = 0;

And initialize the array (in setup):
for (int n = 0; n < 10; n++)
{
    states[n] = 0; // Unpressed
}

When a new button press should be stored:
states[index_state] = state;

And add one to the index state, if 10 is reached, start over (this means the last 10 are stored).
index_state = (index_state + 1) % 10;

And to check the states you just iterate from index_state.
Hope this helps you get going.
Note this is called a ring buffer.

thanks a lot. It helped me store the button sequence. If you can please suggest me how can I blink the LEDs in same sequence as stored in the array with an delay of 500 millisecond. I am posting my code in the answer section please have a look.

The delay of 500 ms might be tricky. That means that for every button you press, you also have to store the time. So you can check if 500 ms have been passed since that press and blink the corresponding LED. Maybe it helps do create the program first for one button and one LED (with 500 ms delay) and than add more buttons/LEDs. Mostly it's better to gradually extend the program instead of going directly to the end goal.

this is my code that stores the button sequence but it will be great if someone can help me blink the LED sequence an put the micro-controller in play or record mode when desired. Also this code faces some issue as some times it fails to take inputs or takes two inputs at a time:
int arr[10];
boolean previous = LOW;
unsigned long time1 = 0;
int debounce = 200;
unsigned long time2 = 0;
int index_state = 0;
void setup()
{
 for(int i = 3;i<6 ;i++)
  pinMode(i,INPUT);
 for(int n=0;n<10;n++) arr[n] = 0;//initialisition
 Serial.begin(9600);
}

void loop(){
 boolean mode = digitalRead(3) || digitalRead(4) || digitalRead(5);
 while(mode == LOW) mode = digitalRead(3) || digitalRead(4) || digitalRead(5);//wait here till one of the pushbutton goes high;
 //Serial.println("value");
 if( mode == HIGH && previous == LOW && millis() - time1 > debounce){
 //find out which one is high and store that value in array;
 if(digitalRead(3)) arr[index_state] = 3;
 else if(digitalRead(4)) arr[index_state] = 4;
 else if(digitalRead(5)) arr[index_state] = 5;
 else ;
 //print the value and the index;
 Serial.print(arr[index_state]);
 Serial.print(" Stored in index: ");
 Serial.println(index_state);
 index_state = (index_state + 1) % 10;
 //update value of time1 for button debouncing
 time1 =  millis();
}

  //update the value of previous button state
  previous = digitalRead(3) || digitalRead(4) || digitalRead(5);

  }


text:
Switch on/off LED 24V using a MOSFET
I try to switch on/off IKEA Ledberg LEDs which are powered with 24 V using the setup from this tutorial video: https://www.youtube.com/watch?v=sVyi7yWuXxs
I use a IRLB8721PBF MOSFET. When I switch the output from HIGH to LOW the LEDs shine a little less brighter. When the pin is set to HIGH I can measure 23,4 V at the LEDs and when it's set to LOW I measure 22,9 V.
So the MOSFET is not really switching off but why? I also tried to put a 100 kOhm resistor between Gate and Source which also did not help.
Do you have any hints for me?
Cheers,
Oliver

Maybe you wired the MOSFET wrong. Please show your wiring and schematic (a video that you "followed" is not good enough).

You should not treat a MOSFET like a relay.  That is, the video shows a working 12 volt circuit but you are going for 24 volts.  The amount of possible current from drain to source is dependent on the voltage of the gate with respect to the drain.  You simply doubled the drain voltage but are still using the same 5 volt swing on the gate.  If you do not want to study the MOSFET Characteristics Curves, that's fine.  But then you should consider using a solid state relay instead.  (Essentially, you are asking how to build a solid state relay.)

Heya, first of all, let me thank you for your answers. As you can see my knowledge is quite basic. The question is not whether I want or do not want to study MOSFET characteristics curves. I simply wouldn't know how to interpret them at the moment. It's like: googling is easy when you know what you are looking for...
Anyway, I think using a relay would be more suitable in this case. I'll give it a try.
Thanks again! :-)


text:
attachInterrupt() corrupting Serial buffer requiring Serial restart
I am working on a proof-of-concept ADC to "explode" what's inside of an ADC chip for teaching purposes.
Currently, I have a sketch that uses a push-button to act as a clock-pulse that counts up (1, 2, 3, 4, ...) for every positive edge using the attachInterrupt() function.
The sketch works great to view the data in the serial monitor.
I am pairing the Arduino (Teensy 3.2) with a Raspberry Pi configured to read data off the Serial line to a text box.
After a good bit of troubleshooting it appears that the attachInterrupt() function corrupts the Serial buffer with garbage for every interrupt. For instance, if I use
Serial1.flush();
Serial1.begin(115200);

immediately after the interrupt and then send out my data using Serial.println() I get my expected decimal value at my output. However, without these lines I just get unicode garbage at my Serial output. See full "fixed" sketch code below:
My question is: why is this happening? I should not need to restart Serial every iteration of the clock.
#define HWSERIAL Serial1

const int numBits = 12;             //Number of bits in ADC (resolution)
const int comparatorPin = 14;       //Pin number of comparator out
const int clockPin = 15;            //Pin number of external clock (square wave) input; expecting clock with 50% duty-cycle
volatile int comparatorState = 0;   //Is comparator high or low?
volatile bool clockState = 0;       //Is clock high or low?
volatile int masterCount = 0;       //Our master count
volatile bool isSameVal = false;    //Is the value of the master count the same value as last cycle?

int outVal = 0;

int masterBinCount[12];     //Array to store binary value of the master count
byte outputPins[12];        //Array to store the numbers associated with the output pin numbers
int maxValue = 0;           //Initialize max counter value to zero

void setup() {
  Serial.begin(115200);       //Begin Serial transmission
  HWSERIAL.begin(115200, SERIAL_8N1);
  HWSERIAL.flush();
  delay(2000);

  defineOutPins(outputPins);  //Assign pin numbers for output pins

  pinMode(14, INPUT);   //Comparator Pin
  pinMode(15, INPUT);   //Clock-in pin

  maxValue = pow(2, numBits);   //Set max counter value to max bit resolution. Ex. for 12 bits --> 4096
}

void loop() {
  attachInterrupt(clockPin, doOnClock, RISING);   //When clock is on a positive-edge execute doOnClock function

  HWSERIAL.flush();
  HWSERIAL.begin(115200);

  if(isSameVal == false) {    //If the master count is NOT the same as the last cycle
    convertDecToBin();        //Convert the master count (dec) to binary
    binaryToPins();           //Send the binary value (via digitalWrite) to output pins
  }
  else {
    //Do nothing
  }
  delay(1000);
}

void defineOutPins(byte pinNos[]) {   //Assign pin numbers to parallel binary out: Teensy 3.2 pin #0 --> #11
  for(byte i = 0; i < numBits; i++) {
    pinNos[i] = {i};      //Assign current pin this value
    pinMode(i, OUTPUT);   //Define pins as outputs
  }
}

void doOnClock() {
  comparatorState = digitalRead(comparatorPin);   //Check comparator state

  if(comparatorState >= 0.5) {            //Check if positive clock pulse
    if(masterCount == (maxValue - 1)) {   //Check if current count value is at "ceiling"
      //Do nothing
    }
    else {            //Else increment count up
      masterCount++;
    }
  }
  else if(comparatorState < 0.5) {    //Check if negative clock pulse
    if(masterCount == 0) {            //Check if current count value is at "floor"
      //Do nothing
    }
    else {
      masterCount--;    //Else decrment count down
    }
  }

  isSameVal = false;    //Set "finished" counting for this clock-pulse
}

void convertDecToBin() {
  for(int j = 0; j < numBits; j++) {
    int tempCnt = bitRead(masterCount, j);
    masterBinCount[numBits - (j+1)] = tempCnt;    //Populate the master binary count array in "reverse" order starting with the LSB at the highest array index
  }
}

void binaryToPins() {
  for(int e = 0; e < numBits; e++) {
    //digitalWrite(outputPins[e], masterBinCount[e]);   //Write our master binary value to output pins
    //Serial.print(masterBinCount[e]);                    //THIS LINE IS FOR TROUBLESHOOTING!!
  }
  isSameVal = true;       //Tell program we wrote the master count to the pins for this clock cycle

  outVal = masterCount;

  Serial.println(outVal);
  HWSERIAL.println(outVal);

  //Serial.print(" decimal: ");   //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.print(masterCount);    //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.println("");           //THIS LINE IS FOR TROUBLESHOOTING!!
}

not related to your problem .... the attachInterrupt() should be in setup()

I believe your issue is with initializing HWSERIAL.begin(115200); in void loop. I created this simple sketch to verify this. Firstly, I commented out the second initialization of Serial.begin, and you can see I was getting a perfect output to the serial monitor. Then I uncommented the line, re-uploaded the code to the Arduino, and you can see it didn't even make it through one print before it sent a bunch of garbled junk and effectively froze my serial port.
Remove HWSERIAL.begin(115200); from void loop and only set it in void setup.
Hope this helps!
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  Serial.begin(115200);
  Serial.print("Test");
  Serial.print(" - ");
  Serial.println(millis());
}

Thank you! I think that sorted things out.


text:
How to speed up writing a file to a WifiClient?
I'm working with a Realtek Ameba IoT RTL8195 board that's compatible to Arduino.
I have a text file on an SD card that I want to send via HTTP over wifi, with the Ameba acting as a server.
I combined the SD card example with the web server example. There's no LED involved here.
Upon request from a client, I want to shove the whole content of the text file into a text/plain response as quickly as possible. At the moment i have a 18.7KB dummy file that takes 6.3s to download in the broswer total. That's rather slow.
My code looks essentially like this:
while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

Where file is declared as SdFatFile file = fs.open(absolute_filename); and client is WiFiClient client = server.available();. Which are both classes that come with the Ameba Arduino SDK.
Both of them extend Stream. I wonder if reading and writing both streams byte by byte causes a bottleneck. is there a way to simply write "the whole thing" to client?

You may try if doing it line by line is faster. Or in chunks of 500bytes (or whatever amount of RAM you have available)

Paul's suggestion from the comment worked. Increasing the buffer reduced the overall time to a couple hundred ms.


text:
Reverse engineering of a bluetooth sensor
I have a problem.
I'm trying to trigger some events with Arduino using some bluetooth LE sensor by a chinese manufacturer, Kaipule. I buy this sensor on Alibaba and I'm trying to understand how can I interface them in my sketch.
They are magnetic contact sensors and I know that they have just the BLE broadcasting mode (no GATT, profile etc): they send information when I open the contact or I close the contact.
I try to scan them with a BLE scanner and this is the log
kCBAdvDataIsConnectable : 0
Local Name : iSensor
Manufacturer Data : <beca2c02 4602f9f7>

I know that:
1) the scanner can see the sensor just when I open/close the contact to save battery, so the sensor broadcast data just when it need.
2) every hour the sensor send a status signal
3) every time I open and close the contact the code change a little. Here is a sequence
<beca2c02 46025856> - > open
<beca2c02 46005955> - > close
<beca2c02 46025a58> - > open
<beca2c02 46005b57> - > close
<beca2c02 46025c5a> - > open
<beca2c02 46005d59> - > close
<beca2c02 46025e5c> - > open
<beca2c02 46005f5b> - > close

etc
4) The first part of the code is the identification of the sensor.

3) From the changing code I assume that 2 is the status open, 0 is the status close and I see also a pattern for other bytes but I cannot understand why for example there is a rolling code.
I have the paper the company send to me, but I cannot find any useful reference.
Wireless sensor 1
Wireless sensor 2

The rolling code at the end could be a time indication.

I'm wondering what the next number would be. It could be that the second last hex-digit is the high byte of the counter. So that would mean the next number would be 4602506_. My guess for the last digit is that it is a checksum, as it's increment by 1, minus the 0/2 for open/close. Anyways, it seems like you already have all the information you need to use these sensors.

@Gerben yes I know, but according to the first pdf I attached is there also a code for the battery status, and this could be useful if I want also to trig an alarm when the battery is at the end. I cannot decode their document

Looking at the datasheet, I interpreted it as:
Byte 1 - 0x46
Indicating this is a unidirectional device (bit7=0) that uses fixed time sending (bit 6=1 which doesn't seem correct) and it is of type 'door contact' (bits 0-5=0x06)
Byte 2 - 0x00/0x02
Indicating that the door is open or closed (bit 1 = 0 or 1). I also think that it indicates there is 'enough battery power' (bit 2 = 0), and the 'anti-tamper' has not been activated (bit 0 = 0)
Byte 3 - 0xXX
This is the 'Frame ID' - counting up for 0x40, to 0x5F then looping ?
Byte 4 - 0xXX
Checksum.
I'd do three things to test this theory:

Run the battery down a lot and see if the battery power indicator changes (byte 2, bit 2).
Open the case and see if the 'anti-tamper' bit changes (byte 2, bit 0)
Do sufficient switching to determine if byte 3 loops around as expected.

This these don't work out then you're likely looking at a different model.

Actually as you say that the sensor sends a signal every hour also, that makes the first byte being 0x46 correct and expected.


text:
Blank.txt at the End of Transmission
I'm using my HC-05 (Master) to receive strings from a sensor (Slave), each string is suppose to have 7 items divided by ',' like so "a,b,c,d,e,f,g". I also have to write these strings in a .txt file in the SD card, being that I receive the strings and save them in a string array to later be written to a file. For some reason I can't receive it and write it to a file simultaneously, it alters the string. So the best way would be an array but when i open the file it's blank and when I print it on screen it starts correctly then prints only the first char of what would be the string. I tried it with 80 strings and it works correctly, so I can only guess it would be insufficient memory, But wouldn't it still write to the file since there is something in the strings.
PS:I'm using Arduino Mega
#include <SD.h>

const int tam=480;
char aux;
File myFile;

void setup() {
  Serial1.begin(115200);
  Serial.begin(115200);
  Capture();
}

void openSD()
{
  SD.begin(4);
  if( SD.exists("test.txt") )
  {
    Serial.println("O arquivo de amostras sera removido");
    SD.remove("test.txt");
      if( !SD.exists("test.txt") )
        Serial.println("Arquivo removido com sucesso!");
  }
  myFile = SD.open("test.txt", FILE_WRITE);
}

void Capture()
{
  String test[tam];
  openSD();
  Serial.println("BEGIN");
  for(int i=0;i<tam;i++)
  {
    test[i]="";
    do
    {
      while(!Serial1.available());
      aux=Serial1.read();
      test[i]+=aux;
      Serial.print(aux);
    }while(aux!='\n');
  }
  Serial.println("END");
  for(int i=0;i<tam;i++)
    myFile.print(test[i]);
  myFile.close();
}

void loop() {

}

Your strings should barely fit in memory if each item is a single character.

Rules of sequential file is : It's saved when its closed, which mean if the file not closed properly, anything written before will not saved, and you'll get blank file.
so, if you get a blank file while you are sure that the data is received, the only possibility is your program doesn't reach
myFile.close();

one of the possibility is the received data not fit into your memory, so the '\n' is undetected.