text:
1x4 Button membrane help
Im trying out this membrane from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?
UPDATE
Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on HIGH. i used Serial.println(digitalRead(one)); to verify that and the output was 1.
int two =  8;
int one = 9;
int four = 10;
int three = 11;

void setup() {
  pinMode(one, INPUT);
  pinMode(two, INPUT);
  pinMode(three, INPUT);
  pinMode(four, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(one) == LOW){
    Serial.println("One");
  }else if(digitalRead(two) == LOW){
    Serial.println("Two");
  }else if(digitalRead(three) == LOW){
    Serial.println("Three");
  }else if(digitalRead(four) == LOW){
    Serial.println("Four");
  }
}

You have the pullups enabled on the 4 pins, right?

Please show your code and wiring.

This is my setup and my code will updated

pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You must enable the pullup on the pins (and connect the common to ground) if you want correct operation.
 pinMode(one, INPUT_PULLUP);

i was not aware of such a thing, thanks! Im quite new to arduino

authors: Θεοδωρος Πετριδησογλου


text:
Can a ESP8266 and a HC-SR04 be friends?
I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.
The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.
duration = pulseIn(echoPin, HIGH);

Any idea on how I can change the pulseIn function with interrupts or something else?
Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

This may be helpful, I have come across a library - newping.h that doesn't use pulseIn (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home). The code fails to compile when I include that whole library. I just want to be able to use the part to bypasses pulseIn and haven't figured that out yet.

Can a ESP8266 and a HC-SR04 be friends? Have you tried food, wine, candles and romantic music?

pulseIn() is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.
Also, I don't know which implementation of the ESP8266 plugin you are using, but the one I use has pulseIn available.

I'm using the same version of ESP8266 plugin as you are, thanks for letting me know that pulseIn() is already supported! I didn't see any mention of it in the reference documentation - http://arduino.esp8266.com/versions/1.6.5-947-g39819f0/doc/reference.html. I was also told that my code will compile even if all the functions aren't supported.

I had trouble with pulseIn() until the proper initializing code was put in setup().
As follows:

  pinMode(TRIGGER, OUTPUT);
  digitalWrite(TRIGGER, LOW);
  delay(2);
  pinMode(ECHO, INPUT);

TRIGGER and ECHO were initially defined at top of code with other variables as follows:
  #define TRIGGER 13 // Data pin D7
  #define ECHO    12 // Data pin D6

My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.

Project was a 'Tide' reporting system. A work in progress.
Also found HC-SR04 board was  unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.

source: Stack Exchange

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

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

sort: votes


text:
Dust sensor for Arduino in open and windy environment
I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition?
Any implementation ideas are also welcome.

A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.
I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.
I mainly followed this blog's instructions for the code:
http://www.howmuchsnow.com/arduino/airquality/grovedust/
I think I read a few months ago that the next best sensors are in the $200 range.
I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.

It depends on how far you want to go.  If you are looking for something cheap, than a GP2Y1010AU0F will only cost you a few pounds.  Or you could step up to £30 GBP or even £1000GBP.
Since you are looking at using an Arduino and not a PC then I'm guessing the GP2Y1010AU0F would be a good idea.  I haven't tried it but this site should steer you the right way: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/

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


text:
Arduino: how can I stop while() when bluetooth send a data?
I have learned Arduino for a month, and I want to bulid a car with 2 modes,
Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:
char mode;

void loop()
{
    while(serial1.available())
    {
        char control = serial.read();
        if(control == 'r') mode = 'r';     // r stand for Remote Mode
        if(control == 'a') mode = 'a';     // a stand for Auto Mode

        if(mode == 'r') remoteMode(control);

        while(mode = 'a')
        {
            int IR = analogRead(A10);
            float U1cmMsec,U2cmMsec;
            long U1microsec = u1.timing();
            long U2microsec = u2.timing();
            U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
            U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

            robot(U1cmMsec, U2cmMsec,IR);

            /*
            Here is the code to stop while() that I don't know how
            to program.
            I have tried:

            if(serial1.read() != 'a') break;

            But it will stop while(), because it will waits for
            bluetooth send data to arduino board.
            And if I take this line off, it will keeps while() and
            nothing can stop it.
            So, what am I supposed to do?
            */
        }
    }
}

Your problem is with this line:
while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing = (assignment) with == (comparison).
You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.
Instead you want:
while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."
Now you just need to program in some way of changing the value of mode within your while loop.
You can read more on while loops here:

http://hacking.majenko.co.uk/the-while-loop

The while(serial1.available()) can be turned into an if: the loop function is already executed in a loop, as the name hints :-)
And unnest the inner while.
here it is at high level, which is probably easier to understand:

void loop() {
  static char mode; /*notice the "static"*/
  if (character_available())
    update_mode();
  if (mode == 'r')
    do_one_iteration_in_remote_mode();
  else if (mode == 'a')
    do_one_iteration_in_auto_mode();
}

Just make sure that you do not loop inside neither do_one_iteration_in_remote_mode() nor do_one_iteration_in_auto_mode().

I have replaced both 'mode' and 'control' (they were identical) with a single variable, btChar. At the end of setup(), wait for a transmission to be received before entering the main loop.
Once the main loop begins, a while loop executes until the serial receives a new transmission. Once it is received it is read, btChar is updated and the main loop starts again.
char btChar;

void setup()
{
/* AT THE END OF SETUP() */

// Wait in setup for first BT transmission

    while (!serial1.available())
    { /* do nothing */ }
    btChar = serial1.read();
}

void loop()
{
    while(!serial1.available())
    {
    // Program will stay in this 'while' loop until
    //    a new BT character is recv'd

        switch(btChar)
        {
            case('a'):
            {
            // do the 'auto' stuff
                break;
            }
            case('r'):
            {
            // do the 'remote' stuff
                break;
            }
            default: // this 'block' is not essential
            {
            // you end up here if neither 'a' nor 'r' was received
            }
        }
    }
    btChar = serial1.read();
}

You can adapt the setup while-loop further to make sure that the main loop doesn't begin until the a correct character is received - change the line to:
while ((!serial1.available())&&(btChar != 'a')&&(btChar != 'r'))

Using a switch-case statement within the main while-loop is not essential, and I included it out of interest more than necessity. You can use if statements instead, with one for 'a' and one for 'r'. However, in the event that you have a third or fourth (or more-th) mode then a switch-case statement, in my view, looks easier to read.


text:
Arduino wire can't send char
Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like Wire.write("blablabla"); it pass. But when in char is NRF data code crashing when go to "Wire.write".
/*
*/
#include <Wire.h>
#include <SPI.h>
#include "RF24.h"

char datar = '';

//Konfiguracja
const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
//-- Konfiguracja

void setup() {
  Serial.begin(9600);
  Serial.println("LOL");
  Wire.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1, pipes[0]);
  radio.openWritingPipe(pipes[1]);
  radio.setChannel(78);
  radio.setAutoAck(true);
  radio.startListening();
}

void loop() {

  int len;
  if(radio.available())
  {
  len = radio.getDynamicPayloadSize();
  radio.read(&datar, len);
  delay(5);
  Serial.println(datar);
  Wire.beginTransmission(7);
  Wire.write(&datar);
  Wire.endTran345smission();
  radio.printDetails();
  }
  delay(5);

}

What  are the input of the write function? Are you sure you need to pass a pointer or  a variable

Your problem is here:
char datar = '';

...

 len = radio.getDynamicPayloadSize();
 radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into datar more than one byte. This overwrites other parts of memory and the program crashes. You need to make datar larger, eg.
char datar [50];

The exact size would depend on your maximum payload size.

Absolute maximum size NRF24L01+ supports should be 32 bytes. (And it wouldn't hurt if one also updated their RF24 libraries through the IDE)

The  code crash because you pass an memory address to the write function if you look to the arduino doc you pass a variable to the function therefore just writing datar as argument will end your problem

Not really, unless the payload size is only one byte.

I think the answer is a combination of Nick and Mathieu's answers.
Like Nick said you haven't assigned any memory to datar, so this is probably causing a crash because of buffer overrun.
Now to the call to read.  Mathieu said you are passing a pointer into the function when you probably didn't mean to.  But if you put Nicks change in then you do need to pass in a pointer to the character array.  You can do this by radio.read(datar, len); because the character array is a character pointer.
You do not want to pass a pointer to a character pointer &datar because that would mean the function was able to move the memory that you have allocated.
Also, you need to prevent buffer overflows in the "new improved" code by checking that the value of len is less than or equal to the value you allocated when you declared the data buffer (i.e. 50).  Because you are using a number in two places you should declare it as a constant at the top of the file.
const int MaxBufferSize = 50;
char datar[MaxBufferSize];
...
len = radio.getDynamicPayloadSize();
if (len > MaxBufferSize)
  len = MaxBufferSize;
radio.read(datar, len);

Hope that helps.


text:
Decoding IR codes with IR sensor rather than IR receiver module
I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).
Is there a library that supports IR sensors?
A picture of the two possibilities can be seen here
EDIT: This isn't a duplicate of my previous post, it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen here

What difference does the sensor make? That is just a hardware issue. The incoming pulses will still be the same.

@NickGammon The difference is how the pulses are presented - a receiver amplifies and filters the signal, so you get a sequence of simple on-off pulses.  With a detector you get whatever IR light is coming in. It's then up to you to filter out the light that is pulsing on and off at the carrier frequency to determine when the on is and when the off is.  That could be done in software, or it could be done in hardware. Best to do it in hardware and use a matched receiver for your transmitter.

@Majenko exactly. I didn't elaborate on the problem I want to solve: I have an IR module which decodes my remote as NEC. Retransmitting it with the same library doesn't work.
Debugging a bit more shows that the remote sends pulse modulation at 830Hz. Could a 38kHz module decode this?

That's a whole different question. Better post a new question instead of adding this in the comments.

@Gerben seems too technical to be over here. Posted on electronics

Possible duplicate of A/C doesn't detect IR codes sent from Arduino

This seems related to your question about A/C doesn't detect IR codes sent from Arduino. Although in that post you seemed confident you had detected the codes. Now you are not? Please explain why you are opening another question about your air conditioner and the IR remote, without referencing your earlier question. This helps see the project in context.

This question also seems very similar to control air conditioner using arduino - in itself double-posted.

@NickGammon in the previous question I was looking for what's causing it not to work, now that I've found out (it's the frequency). The reason I found out is by using an IR sensor rather than an IR module. What I'm looking for now is an IR library that works with IR sensor and not IR module, to make sure the codes were decoded properly. See my other question in electronics.

@NickGammon also, I just answered my previous question

No, you posted a mistaken analysis of your other question.  You need to stop posting new questions and concentrate on understanding the actual problem.  This question is based on fundamentally mistaken ideas and should be deleted.

Several cars and universal remote controls have this feature of autolearning sender codes by pairng keys in the learn mode. Why not do the same?

I had a similar project a few months back and spotted this Arduino Library:
https://github.com/z3t0/Arduino-IRremote
and it is invaluable.
For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.
The wiring is easy and straight forward

An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3
and the other two Legs of the IR detector/demodulator go to the power source.

OP said he doesn't have the 3 legged module but just a raw sensor (2 legs).

IRremote (already recommended) - but to save you some time, use the IRRecvDump example to grab the raw codes you need for sendRaw(). They need to be averaged out across 10-20 reads. I log the output to a file, and use a perl script to do it for me, since it is painful to type this into a calculator a million times. The resistor you connect to the sensor affects its sensitivity - I used 330ohm, and have ~10 metres range from a 3V3 remote inside, 4-5 metres outside in sunlight. I would give you the script, but it's on my desktop. Let me know if you need it - or just use python, which is so popular nowadays (indent-or-fail... feh. what about people who don't like setting up the tab-space continuum, and don't have fancy editors...mumblemumble)
Edit: my raw codes absolutely needed to be averaged out, or they were useless. Any negative values in the array can just be made positive, don't fret.

I'm looking for a library to decode RAW IR signals from an IR sensor

AGirs includes a comprehensive library designed to work with raw IR signals. I've used GirsLite in an Arduino and IrScrutinzer in Windows to do advance IR protocol snooping.


text:
Running Arduino code for Bluefruit LE on bare ATMega328
I need to hook up Bluefruit LE Breakout (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the library provided is for Arduino.
What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.
Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.
And this is where I need help:
How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).
And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).
Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.
UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.
You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.
You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of Upload, choose Upload using Programmer (in the Sketch menu).

It is that simple then, thanks. I will check this as soon as I figure out how to adjust F_CPU and fuses in Arduino (I am using 8MHz internal clock) and decide what to do with RST pin for the BLE module.

Just download my boards definition. Just extract and place inside the hardware folder in the Arduino sketches folder (create if not yet present). The 328 @ 8mhz board should be added to the Tools->Boards menu after restarting the IDE.

The one place you will have to worry about the 328 vs 328P is in the programmer configuration - while the file will usually work between chips, the program will refuse to load it into a different one than it is expecting.

Just to confirm: I made my "board" definition (MCU, fuses, frequency), And "Upload using Programmer" definitely works: I was able to use BLE "UART"! As for refusing to load, yes, there was one warning, when I had intermediate configuration (forgot to change mcu from atmega328p to atmega328). I have not tried to change frequencies (and bootloader) on the Uno though, so switched to "bare" chip as soon as uart was understood.

A, right. In my boards from above, edit boards.txt and change atmega328-8mhz.build.mcu=atmega328p to atmega328-8mhz.build.mcu=atmega328.


text:
How to find the deferenced value of a transmit Port Register?
So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.
*reg = _transmitPortRegister
_transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D

Continuing...
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

const uint16_t PROGMEM port_to_output_PGM[] = {
    NOT_A_PORT,
    NOT_A_PORT,
    (uint16_t) &PORTB,
    (uint16_t) &PORTC,
    (uint16_t) &PORTD,
};

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.
Continuing on,
#define PORTB _SFR_IO8(0x05)
#define PORTC _SFR_IO8(0x08)
#define PORTD _SFR_IO8(0x0B)

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
#define __SFR_OFFSET 0x20

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.
LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.
// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte"
and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one?
Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No.  You're mistaking the operator.  In this context & means the address of, so it is getting the address of the variable called PORTD and casting it to an unsigned 16-bit integer, which it's then storing in the array.

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses.  The port register number is (for port D) 0x0B.  Add that to 0x20 and you get 0x2B which is the address of the register in memory.  Then comes the tricky bit:
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Expand that out with 0x2B and you get:
(*(volatile uint8_t *)(0x2B))

Now, working from the inside out we have:
(volatile uint8_t *)(0x2B)

That says this is a pointer to address 0x2B.
Then that is de-referenced to get the value from that pointer with a * operator:
*(volatile uint8_t *)(0x2B)

So you end up with "The value that is in the address 0x2B"
If we then feed that back into the first part of your question, so:
PORTD = (*(volatile uint8_t *)(0x2B))

then &PORTD would be:
&(*(volatile uint8_t *)(0x2B))

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:
(volatile uint8_t *)0x2B

Oh my, i feel so amateurish. I am so sorry. I can't believe I completely neglected the fact that the & is adress of in this case. Ok, thank you so much! So I know up the value in 0x2B is being deferenced. But are you saying 0x2B is the value that is being returned? or is it something else still?

0x2B is the value that is being returned when & is used, since that is the address that the value is stored at.  Don't sweat it, it took me years to get my head around pointers.

OOO! the value at 0x2b is being deferenced, and we're trying to find out the address of that value. which IS 0x2b. Thank you so much. Also, why would or *reg |= reg_mask send a one? If i'm using pin 1, then reg_mask equals 0b00000010. so 0b00101011 | 0b00000010 is what is being calculated. but how does that translate to a one being sent? there isn't even a digitalWrite in that block of code.

That would OR the contents of reg_mask with the contents of the address pointed to by reg.  It basically sets one bit in the register. &= inv_mask clears the same bit.

sorry, I'm not quite understanding how it sets one bit in the register because that OR statement evaluates to 0b00101011.

Also, just be setting it in the register, how does it actually transmit it? In other words, when does it actually power the pin HIGH and LOW?

It expands to *reg = *reg | reg_mask.  If *reg contains, say 0b00101001 and reg_mask contains 0b00000010 then *reg ends up as 0b00101011 and the pin goes high.  That register is more than just memory - it is actually the physical hardware of the IO pin. You're not just setting values, you're directly affecting real hardware. By setting a bit in the PORT register you are physically changing the voltage level on the pin from 0V to 5V.

Hey, O i see what you're saying. Ok, i just read up on what each register does in arduino. But here's the iffy part. *reg is 0x2b. That evaluates to 0b00101011. So ORing that with 0b00000010 just gives me back 0b00101011.

No, reg is 0x2b, *reg is whatever is at 0x2b.

Hmm, so how do I figure out what is at value 0x2b?

By looking at *reg or PORTD. Why do you need to "figure out" what is at that address anyway? You are just setting or clearing one bit in it. The rest shouldn't concern you

well i was told to figure out what exactly is the startbit. So all of this is just to figure out what startbit is being sent. So am i understanding this properly? the value 0x2b is being transmitted as the startbit?

Nonono!  There is NO VALUE 0x2B.  That is an ADDRESS in memory.  The value that is being sent is ONE of the bits within the CONTENTS of that address.  You don't need to know what the contents are, since you are only ever manipulating ONE bit within it, and you never care what it was, only what you set it to.  Forget that whole register and look at the rest of the program to determine what the bit is being set to and when. Forget the mechanics of how the bit is being set.

Oh I completely understand! ok ok. That makes more sense. Hence this piece of code in the library. And if i just had an arduino uno, the inv would read false, since most arduinos don't use inverse logic. So basically, my start bit is 0, since i'm anding it with inv_mask.
// Write the start bit
if (inv)
*reg |= reg_mask;
else
*reg &= inv_mask;
Thank you so much for your help.

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks,

The comment is: choose bit
First, variable b is the byte that is being set. Now, since async serial sends the least-significant bit first, at the start of the loop of 8 iterations, it takes the low-order bit to see if it is set or not:
  if (b & 1) // choose bit

If set, it sets the output port to HIGH (by ORing in the appropriate mask to the appropriate register), otherwise it sets the port to LOW (by ANDing in the appropriate inverted mask to the appropriate register). The inverted mask would be set to every bit but one.
Now look at this:
  b >>= 1;

That shifts the bits right one, throwing away the low-order bit. Now what was previously the second lowest-order bit is now the low-order bit. Then the loop repeats. Now the next bit is sent. And so on for 8 bits.
Imagine we were sending 0x39 (0b00111001). For the 8 iterations of the loop we would see:
00111001  --> 1 sent, then "b" shifted right one
00011100  --> 0 sent, then "b" shifted right one
00001110  --> 0 sent, then "b" shifted right one
00000111  --> 1 sent, then "b" shifted right one
00000011  --> 1 sent, then "b" shifted right one
00000001  --> 1 sent, then "b" shifted right one
00000000  --> 0 sent, then "b" shifted right one
00000000  --> 0 sent, then "b" shifted right one

You can see that the right-most bit is sent (the low-order bit) and then b is shifted right (introducing zeroes at the left), until all 8 bits are sent.


text:
2.8" tft screen arduino all pins used
I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: 2.8" TFT Touchscreen Prohibits Access to Unused Pins)
However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)
However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?
Thanks!

You're confusing the idea of using all the pins to that of plugging into all the pins.
Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.
The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.
You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


text:
Memory organisation of MIFARE 1K
I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
  programmed to allow operations such as reading, writing, increasing valueblocks,
  etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data.
  Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.

You're reading (and doing your sums) backwards.
You have 1024 bytes of data space.
That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.
Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.
48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.
Incidentally 1024 - 768 = 256, which is what you were calculating before.  What you calculated was the amount of the 1024 bytes that is reserved in total for the keys and access controls.

Thanks @Majenko...I haven't read this clearly..It's very simple.Thanks for explanation.

Divide 1024 bytes into 16 sectors -
1024 bytes / 16 sectors = 64 bytes per sector

The first 16 bytes of each sector are used for 'management' and thus reserved. This leaves -
64 - 16 = 48 bytes (per sector) for general storage

Ops..Thanks friend.I have not read this clearly.Thanks

There is also an excellent graphic of the various mifare card layouts, that someone has put together: https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png

this is a large image
https://upload.wikimedia.org/wikipedia/commons/3/39/MiFare_Byte_Layout.png


text:
Esp8266 Arduino smart connect
Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.
#include
#include
#include
#define ONE_WIRE_BUS 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define SSID "[YOUR_SSID]"
#define PASS "[YOUR_PASSWORD]"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=[THINGSPEAK_KEY]&field1=";

void setup()
{
  Serial.begin(9600);
  sensors.begin();
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  tempC = DallasTemperature::toFahrenheit(tempC);
  char buffer[10];
  String tempF = dtostrf(tempC, 4, 1, buffer);
  updateTemp(tempF);
  delay(60000);
}

void updateTemp(String tenmpF){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial.println(cmd);
  delay(2000);
  if(Serial.find("Error")){
    return;
  }
  cmd = GET;
  cmd += tenmpF;
  cmd += "\r\n";
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  if(Serial.find(">")){
    Serial.print(cmd);
  }else{
    Serial.println("AT+CIPCLOSE");
  }
}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    return true;
  }else{
    return false;
  }
}

Well you need some sort of way to input the username and password so you'll need to use a SoftwareSerial to connect to your computer through an FTDI in order to communicate the information over a COM port.

Without software serial,setting up a temporary access point for example and entering the details on a web page which will then disconnect and reconnect to the home router,is this possible ?

Yea, assuming the temp access point has the same user and pass all the time.  Just connect to that, enter the permissions through the web-portal and have the webapp send the new information to your device then connect to that.  You'll have considerably more back-end work to do though since you need to set up a little web-app/server

I have cobbled together, from the library examples, a program to log temperature and humidity to an MQTT server. The SSID/password, MQTT server and port, and the MQTT publish path can all be set at run time. Once they are set, the device will remember and re-use the settings next time it boots.
I am using the Arduino IDE to program an ESP8266-01. It, in turn, talks to a DHT11 sensor for temperature and humidity data.
The program is found at https://github.com/PabluskiNC/TempHumidityLogger
    #include <FS.h>                   //this needs to be first, or it all crashes and burns...

    #include "DHT.h"
    #define DHTPIN 2
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

    #include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

    #include <PubSubClient.h>
    WiFiClient espClient;
    PubSubClient client(espClient);
    long mqtt_lastMsg = 0;
    char mqtt_msg[50];
    int  mqtt_value = 0;

    //define your default values here, if there are different values in config.json, they are overwritten.
    char mqtt_server[40];
    char mqtt_port[6] = "1883";
    char mqtt_topic[34] = "OutTopic";

    //flag for saving data
    bool shouldSaveConfig = false;

    //callback notifying us of the need to save config
    void saveConfigCallback () {
      Serial.println("Should save config");
      shouldSaveConfig = true;
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      Serial.println();

      //clean FS, for testing
      //SPIFFS.format();

      //read configuration from FS json
      Serial.println("mounting FS...");

      if (SPIFFS.begin()) {
        Serial.println("mounted file system");
        if (SPIFFS.exists("/config.json")) {
          //file exists, reading and loading
          Serial.println("reading config file");
          File configFile = SPIFFS.open("/config.json", "r");
          if (configFile) {
            Serial.println("opened config file");
            size_t size = configFile.size();
            // Allocate a buffer to store contents of the file.
            std::unique_ptr<char[]> buf(new char[size]);

            configFile.readBytes(buf.get(), size);
            DynamicJsonBuffer jsonBuffer;
            JsonObject& json = jsonBuffer.parseObject(buf.get());
            json.printTo(Serial);
            if (json.success()) {
              Serial.println("\nparsed json");

              strcpy(mqtt_server, json["mqtt_server"]);
              strcpy(mqtt_port, json["mqtt_port"]);
              strcpy(mqtt_topic, json["mqtt_topic"]);

            } else {
              Serial.println("failed to load json config");
            }
          }
        }
      } else {
        Serial.println("failed to mount FS");
      }
      //end read

      // The extra parameters to be configured (can be either global or just in the setup)
      // After connecting, parameter.getValue() will get you the configured value
      // id/name placeholder/prompt default length
      WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
      WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
      WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32);

      //WiFiManager
      //Local intialization. Once its business is done, there is no need to keep it around
      WiFiManager wifiManager;

      //set config save notify callback
      wifiManager.setSaveConfigCallback(saveConfigCallback);

      //set static ip
      //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

      //add all your parameters here
      wifiManager.addParameter(&custom_mqtt_server);
      wifiManager.addParameter(&custom_mqtt_port);
      wifiManager.addParameter(&custom_mqtt_topic);

      //reset settings - for testing
      //wifiManager.resetSettings();

      //set minimu quality of signal so it ignores AP's under that quality
      //defaults to 8%
      //wifiManager.setMinimumSignalQuality();

      //sets timeout until configuration portal gets turned off
      //useful to make it all retry or go to sleep
      //in seconds
      //wifiManager.setTimeout(120);

      //fetches ssid and pass and tries to connect
      //if it does not connect it starts an access point with the specified name
      //here  "AutoConnectAP"
      //and goes into a blocking loop awaiting configuration
      if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
        //reset and try again, or maybe put it to deep sleep
        ESP.reset();
        delay(5000);
      }

      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");

      //read updated parameters
      strcpy(mqtt_server, custom_mqtt_server.getValue());
      strcpy(mqtt_port, custom_mqtt_port.getValue());
      strcpy(mqtt_topic, custom_mqtt_topic.getValue());

      //save the custom parameters to FS
      if (shouldSaveConfig) {
        Serial.println("saving config");
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.createObject();
        json["mqtt_server"] = mqtt_server;
        json["mqtt_port"] = mqtt_port;
        json["mqtt_topic"] = mqtt_topic;

        File configFile = SPIFFS.open("/config.json", "w");
        if (!configFile) {
          Serial.println("failed to open config file for writing");
        }

        json.printTo(Serial);
        json.printTo(configFile);
        configFile.close();
        //end save
      }

      client.setServer(mqtt_server, stringToNumber(mqtt_port));
      client.setCallback(callback);
      Serial.println("local ip");
      Serial.println(WiFi.localIP());
      dht.begin();
    }

    int stringToNumber(String thisString) {
      int i, value, length;
      length = thisString.length();
      char blah[(length + 1)];
      for (i = 0; i < length; i++) {
        blah[i] = thisString.charAt(i);
      }
      blah[i] = 0;
      value = atoi(blah);
      return value;
    }

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is acive low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        Serial.print(mqtt_server);
        Serial.print(":");
        Serial.print(mqtt_port);
        Serial.print("...");
        // Attempt to connect
        if (client.connect("ESP8266Client")) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish(mqtt_topic, "Reconnected");
          // ... and resubscribe
          //client.subscribe("inTopic");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

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

      float h = dht.readHumidity();
      float t = dht.readTemperature();
      if (isnan(t) || isnan(h)) {
        Serial.println("Failed to read from DHT");
      } else {
        Serial.print("Temp:");
        Serial.print(t);
        Serial.print( "*C  Humidity:");
        Serial.print(h);
        Serial.println("%");
        if (!client.connected()) {
          reconnect();
        }
        client.loop();

        //long now = millis();
        //if (now - mqtt_lastMsg > 2000) {
        //  lastMsg = now;
        //  ++mqtt_value;
        char temp[7];
        dtostrf(t,4,2,temp); //convert float to char
        snprintf (mqtt_msg, 50, "%s C", temp);
        //  Serial.print("Publish message: ");
        //  Serial.println(msg);
        //  client.publish(mqtt_topic, msg);
        //}
        char pub_topic[34];
        strcpy(pub_topic,mqtt_topic);
        strcat(pub_topic,"/temperature");
        client.publish( pub_topic , mqtt_msg);
        Serial.print("Publish: ");
        Serial.print(pub_topic);
        Serial.print(" , ");
        Serial.println(mqtt_msg);

        dtostrf(h,4,2,temp); //convert float to char
        snprintf (mqtt_msg, 50, "%s %", temp);

        strcpy(pub_topic,mqtt_topic);
        strcat(pub_topic,"/humidity");
        client.publish(pub_topic,mqtt_msg);
        Serial.print("Publish: ");
        Serial.print(pub_topic);
        Serial.print(" , ");
        Serial.println(mqtt_msg);
      }
      delay(5000);
    }

This is a nice piece of code.Great Job

The following code can do what you want (source), all that is needed is to combine it with the sensor code. The default behaviour is to create an access point when it can't connect to the eeprom stored WiFi station but you can modify it to trigger with a button/jumper or any other way you prefer.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

ESP8266WebServer server(80);

const char* ssid = "test";
const char* passphrase = "test";
String st;
String content;
int statusCode;

void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
    {
      esid += char(EEPROM.read(i));
    }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 32; i < 96; ++i)
    {
      epass += char(EEPROM.read(i));
    }
  Serial.print("PASS: ");
  Serial.println(epass);
  if ( esid.length() > 1 ) {
      WiFi.begin(esid.c_str(), epass.c_str());
      if (testWifi()) {
        launchWeb(0);
        return;
      }
  }
  setupAP();
}

bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; }
    delay(500);
    Serial.print(WiFi.status());
    c++;
  }
  Serial.println("");
  Serial.println("Connect timed out, opening AP");
  return false;
}

void launchWeb(int webtype) {
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());
  createWebServer(webtype);
  // Start the server
  server.begin();
  Serial.println("Server started");
}

void setupAP(void) {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
     {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
     }
  }
  Serial.println("");
  st = "
";
  for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      st += "
";
      st += WiFi.SSID(i);
      st += " (";
      st += WiFi.RSSI(i);
      st += ")";
      st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
      st += "
";
    }
  st += "
";
  delay(100);
  WiFi.softAP(ssid, passphrase, 6);
  Serial.println("softap");
  launchWeb(1);
  Serial.println("over");
}

void createWebServer(int webtype)
{
  if ( webtype == 1 ) {
    server.on("/", []() {
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
        content = "<!DOCTYPE HTML>\r\nHello from ESP8266 at ";
        content += ipStr;
        content += "
";
        content += st;
        content += "
<form method='get' action='setting'>SSID: <input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
        content += "";
        server.send(200, "text/html", content);
    });
    server.on("/setting", []() {
        String qsid = server.arg("ssid");
        String qpass = server.arg("pass");
        if (qsid.length() > 0 && qpass.length() > 0) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
          Serial.println(qsid);
          Serial.println("");
          Serial.println(qpass);
          Serial.println("");

          Serial.println("writing eeprom ssid:");
          for (int i = 0; i < qsid.length(); ++i)
            {
              EEPROM.write(i, qsid[i]);
              Serial.print("Wrote: ");
              Serial.println(qsid[i]);
            }
          Serial.println("writing eeprom pass:");
          for (int i = 0; i < qpass.length(); ++i)
            {
              EEPROM.write(32+i, qpass[i]);
              Serial.print("Wrote: ");
              Serial.println(qpass[i]);
            }
          EEPROM.commit();
          content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
          statusCode = 200;
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          Serial.println("Sending 404");
        }
        server.send(statusCode, "application/json", content);
    });
  } else if (webtype == 0) {
    server.on("/", []() {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
    });
    server.on("/cleareeprom", []() {
      content = "<!DOCTYPE HTML>\r\n";
      content += "
Clearing the EEPROM
";
      server.send(200, "text/html", content);
      Serial.println("clearing eeprom");
      for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
      EEPROM.commit();
      WiFi.disconnect();
    });
  }
}

void loop() {
  server.handleClient();
}

The configuration access point ssid and password are set in
const char* ssid = "test";
const char* passphrase = "test";

The default IP is 192.168.4.1. When you open it from a browser you see a screen which lists the available WiFi stations (ESP8266 scan result), the signal strength and an asterisk on locked stations. There are also two text boxes where you enter the ssid and password of the station you want to connect to and submit:

Note that there is a link to a similar library in the comments of the source link, that didn't work for me but you can try it.

The WifiManager is pretty good, but my own testing reveals it needs to mature a bit.  It has trouble authenticating to my WiFi; but keep your eyes on it


text:
arduino creates strange files in SD card
I'm new to Arduino and electronics. I want to make a project including SD data-logger, but I had a problem. I would appreciate if someone show me where I made a mistake.
Firstly, circuit  was set up as in picture:

I am using 8 Gb micro SDHC card with SD adapter. I formatted in FAT32. I can play audio files which are in appropriate format and read and the print contents of text files.
But when I want to create a new file, strange file is obtained in SD card as in pic:

So I reformat SD card. the code that is used while creating file is as this;
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

Somewhere I read SDHC card with more than 2 Gb capacity  is not supported in Arduino and I bought 2 Gb SD micro with SD adaptor.
But in this case aurduino does not detect SD card. please someone help me.

Please post all of your code and format it right. (Also, if you are talking about yourself (I am, I will and so on) then capitalize the "I").

I formatted with SD formatter 4.0 but did not make difference.
Probably, aurduino doesn't support some SD cards, this problem looks like some cd driver or writer doesn't detect some compact discs.
I have two micro sd one of them 8 gb micro sdhc - sandisk  - this is supported reading but not supported for writing
other one 2gb microsd- noname - this is not supported for reading and writing
is there someone tell me mark and type of sd card to be able read and write successfully.

https://www.arduino.cc/en/Tutorial/Files this is code I work on

It sounds like you tried using a card that is too big, so it didn't work. Then you bought some cheap 2GB cards that either don't work full-stop or don't have SPI support. Bite the bullet and buy cards from a reputable retailer.

instead of buying new sd card because it is hard to find good quality 2gb capacity I am considering buying microsd module http://urun.n11.com/diger/arduino-micro-sd-kart-modulu-spi-P70554983?cid=604001&gclid=CLKEgqXyjcgCFUbmwgod5XgOcA which is supporting sdhc etc.

@dursung - SDHC support mostly depends on software, so that module won't help you.

It's a long shot but check your wiring and voltage levels. I've seen similar corruption issues when writing to SD cards when the power supply to the card wasn't quite up to the job.

I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

make sure your wires are the same length and try to use short wires
make sure your power supply is sufficient, sd card readers can draw up to 150mA
format the card in either FAT16 or FAT32 and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
make sure if you're the correct BAUD rate (9600) to talk to your card
filename support is pretty old so keep them short and don't use spaces or special characters
make sure the SD card is not in "write lock" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)

Note that write protection on a SD card is dependent on the socket and host honoring it; turning it on does nothing to actually prevent the host from writing successfully to the card.

Also, SD uses SPI, not UART, so "baud rate" is irrelevant, only the serial clock speed.

I've seen this exact issue before being caused by power supply brownout. There is a current spike during writes, if the voltage drops too much you get this effect. Slower/smaller cards are less prone to it because they have a smaller spike. Improving the power supply to the card fixed it.

I have faced this problem. Try

If you are using multiple devices with SPI communication ignore the others by keeping their slave select HIGH
Never forget file.close()

If file.close() is so important wrap the file access in a class so close is always called in the destructor.


text:
Sets of Ultrasonic frequencies using arduino uno
Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in  the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

I find a shotgun or a cat works best.  The latter is greener, but the former is oh so much more fun ;)

There are three parts to this project, one of which you asked:

I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the void setup{} part of your code, and (if you don't want to do anything else), leave the void loop() {} empty. You might want to generate an audible tone for a short period first, to show that it is working.

You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.
The circuit is pretty trivial. Google piezo arduino

Efficacy:

From https://en.wikipedia.org/wiki/Electronic_pest_control#Effects_on_rodents

Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.

You can specify a frequency up to 8mhz. - that's quite low, right? (Just kidding). I am skeptical that you would reach 8 MHz because the library toggles the pin in an ISR, and an ISR would have an overhead of a couple of microseconds. I would guess that 250 kHz to 500 kHz would be the theoretical maximum. Of course, this is a lot more than the 40 kHz that the OP wants.

You could and should maybe use a lot of transistors, and that might be whit you circuit and set the MHz overload higher then expected.

What library on arduino should i use?

You don't need a library. Tone() is built into the core.  There are some example sketches that come with the environment - just click File -> Digital -> toneMultiple. Note that this example plays different tones on different speakers (connected to different pins); for your code, put one 8-ohm speaker between pin 6 and ground, then change the first parameter of the tone() to 6 for all of them.

Is it possible to create an ultrasonic frequency by simply using it?  And can i used 45678Hz as my desired frequency?

"ultrasonic" is a function of our ears, an Arduino doesn't care if we can hear it or not. tone(pin_with_piezo,45678);

I connected the output to the ultrasonic transmitter but its not working. here is the transmitter specification that i used (http://www.farnell.com/datasheets/1498178.pdf) and the circuit diagram (https://www.google.com.ph/search?q=ultrasonic+circuit&espv=2&biw=1366&bih=643&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjoivap6-fJAhUK-2MKHdFeAFwQ_AUIBigB#tbm=isch&q=ultrasonic+transmitter+circuit+diagram&imgrc=fLTfT6_BQfBMyM%3A). can anyone help me regarding this problem?

Another answer to generating ultrasonic frequencies is to ditch the Arduino altogether - use a 555 timer circuit (for lower range frequency, probably up to low mHz), or a resonator. A quick search found a 2.4 gHz resonator for less than an Arduino. 555 timers can be tuned, resonators cannot. I think you could build a 555 square-wave generator for about $1-$2.

Hi, how can I strengthen the ultrasonic frequency produced by the arduino ic's?

This should really be a separate question, but: louder sounds can be made with higher voltage (up to the voltage supported by your piezo, or it will blow), using a higher voltage piezo, or one with a frequency response more suited to your frequency. If you want to use a voltage higher than the Arduino can handle, use a transistor as a switch (google).


text:
SIM900 Shield read only sms headers without text
I enable messages about new SMS
AT+CNMI=2,2,0,0,0

OK

and when received sms, output like this.
+CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
Test

But when I read message, output only before <CR><LF>
I don't see text of message.
AT+CMGR=1

+CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

AT+CMGL="ALL"

+CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
+CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

I use following  (via SoftwareSerial) code for test this.
SMSGSM.GetSMS and SMSGSM.GetAuthorizedSMS of GSM GPRS GPS Shield Library receive only phone number without sms text.
I use this shield:

AT+GSV

SIMCOM_Ltd
SIMCOM_SIM900
Revision:1137B05SIM900M64_ST_ENHAN

This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the Serial.print()s in your code. You should look for SoftwareSerial.h in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial if you're using Win 8 and above. Or just search your PC for it. Look for this line:
    #define _SS_MAX_RX_BUFF 64

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.
You could also try this, to interact with the module:
#include <SoftwareSerial.h>

SoftwareSerial SIM900(7,8);

void setup() {
  Serial.begin(19200);
  SIM900.begin(19200);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (Serial.available() > 0){
    SIM900.write(Serial.read());
  }
  while (SIM900.available() > 0){
    Serial.write(SIM900.read());
  }
}

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.

Could you confirm that any of the commands sent over your SoftwareSerial are responding?
You probably need to add a "\n" (new line) at the end of your messages or just use println().
Also, add your code to the question so we can be of better assistance.


text:
Two Leonardos on one USB hub - not working properly
I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:
const byte SWITCH = 12;

void setup ()
  {
  Keyboard.begin();
  pinMode (SWITCH, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  if (digitalRead (SWITCH) == LOW)
    {
    Keyboard.println ("foo");
    delay (2000);
    }
  }

Now I program a second Leonardo with the same code but send "bar" rather than "foo".
Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.
However ...
If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.
Doing lsusb shows this (along with other irrelevant devices):
$ lsusb
Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

This happens in both cases (if they are both in the USB hub or not).

My question
Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).
Or, is this a bug in either:

The Leonardo USB interface?
My USB hub?

Update
Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.
Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!
Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.
Following Majenko's suggestion:

You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:
T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

Second one:
T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
/usr/bin/usb-devices: line 79: printf: (none): invalid number
I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

Tentative conclusion
Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.
Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.
Those error messages above must be relevant, but I don't know enough about it to say in what way.

What OS are you using? You could try changing the PID on one of them.

I am using Ubuntu 14.04. See updated question.

Are you using the external power for the hub or drawing power from the bus?

I was using external power on Ubuntu, but drawing from the bus on the Mac, as it was fiddly to move the power wire.

There is no reason I can think of that would stop it working as it should.
lsusb is showing both the devices, so they are being detected by the kernel.
You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:
T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=0036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=USB IO Board
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

The important bit is the I: lines - they show the individual USB interfaces and what kernel driver has been associated with them.   For the keyboard, of course, it's the last entry, which is assigned to the usbhid driver.
Another good diagnostic is dmesg -w
Run that with both Leonardos disconnected.  Plug one in and it should show it registering as a USB device.  A few moments later you should get a pair of lines like:
[ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
[ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

That is the board being associated with an input device (in this case input 2).
Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).
The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub.  It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.
USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers.  For instance my Leonardo above is identified as:
1-1.4.1

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device.  Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.

I've tried what you suggested, see amended question.


text:
TFT touch, 4bit data transfer
I followed instructions to get my TFT to work.

I want to use other pins on the Arduino Uno for other I/O, so how can I use 4-bit data transfer for the TFT touchscreen?

Hi Veno, welcome to StackExchange. Unfortunately, it is not clear what you are asking. Are you asking how to get the touch screen to work? Try TFTLCD-Library. You say that you followed instructions... Which instructions did you follow to get our TFT to work? Can you edit your post and provide a link? Also, if you have another question relating to building an "antenna analyzer", then please ask a separate question.

You read the datasheet for the chip that is on your TFT display (whatever that is) and find if it even supports a 4-bit mode.  It probably doesn't. I have a large number of TFT screens here and I don't recall any of them using parallel 4-bit.  It sounds like you actually want a TFT screen that works of SPI rather than a parallel interface.  Those are available, but by using SPI the screen updates are considerably slower.

Yes,it will be slower with ISP, I want to test 4bit code on my TFT, can u help me

@VenuGopalRaoAggress No, I can't. Not unless you tell us what your TFT is. That means the exact model number of the chip that is on the TFT screen itself (ILIxxxx, SSDxxxx, SDxxxx, XPxxxx, etc) and how the TFT screen is wired up to the Arduino (schematic of the TFT screen's carrier shield).

Chip is 7783, Tannq

Not familiar with the ST7783 ( I assume it's Sitronix). I know the ST7781 and ST7785 and as I suspected, neither support a 4 bit interface. They do have an SPI mode, but the carrier shield has to be wired right for it.  I would suggest shopping around for an SPI TFT screen.  You won't find one with a 4-bit parallel interface - they simply don't exist.  8 bit, 16 bit or 18 bit. Never 4 bit.


text:
Waiting for an AT command to complete
I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.
I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.
Function:
void ModemCommand(String command) {
  //Send command to modem
  mySerial.println(command);
  Serial.println(command);
  delay(100);
  while (!mySerial.available()) {
    //Wait for Response from modem
    Serial.println(F("No response yet"));
    delay(1000);
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
    //Print response from modem
  }
  Serial.println("");
  //Linefeed after reponse
  delay(10);
}

Code example:
ModemCommand(F("ATE0"));
//Turn on echo
ModemCommand(F("AT+CFUN=1"));
//Turn modem functions on
waitSec(8,F("turning on Modem functions"));
ModemCommand(F("AT+CGREG?"));
//GSM attached?
ModemCommand(F("AT+CSQ"));
//Signal Quality
ModemCommand(F("AT+CSTT=\"internet\""));
//Set APN
ModemCommand(F("AT+CIICR"));
//Connect to APN GPRS
waitSec(8,F("connecting to APN GPRS"));
ModemCommand(F("AT+CIFSR"));
//Get IP

Does anybody know how to do this?

You first need to understand how serial on the Arduino works.  Read this first: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use mySerial.write() to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:
#define TIMEOUT 1000

void modem_command(String command){
  mySerial.println(command);
  Serial.println(command);
  while (mySerial.available() == 0);  // wait for first char

  unsigned long lastRead = millis();   // last time a char was available
  while (millis() - lastRead < TIMEOUT){
    while (mySerial.available()){
      Serial.write(mySerial.read());
      lastRead = millis();   // update the lastRead timestamp
    }
  }
  // No need for extra line feed since most responses contain them anyways
}

Of course, you can always alter TIMEOUT based on your findings.

Just looking for a response, and not interpreting it seems like a fairly weak solution.

@ChrisStratton But thats what he's asking for: a way to send a command, wait 'efficiently' and view the response with minimum fuss. I assume he'll be monitoring the responses from the serial monitor (given his code example) so thats okay. Besides, anything extra would require a lot of parsing and there are whole libraries for that.

If the response is being monitored externally, there's no need to internally decide when it has been completely received.  Proxying between two serial devices can be entirely stateless.  Rather it sure looks like echoing back to the PC is only there for debug monitoring - the shown program automatically executes a lot of commands without waiting for any external confirmation that the echoed response is positive and not an error.  If this system is going to be actually useful, internal parsing will be required - an answer already posted last fall.

@ChrisStratton yeah...thats exactly what his code is doing. While its not the best practice, it does have a lot of simplicity especially for prototyping. If you want me to correct his mistakes though, thats something else...

Someone else already did address those mistakes, months before you posted, which is part of what makes an answer that perpetuates them less than satisfying.

@ChrisStratton I dont even know if they are mistakes. Look at his function; there are zero attempts to parse a response, though he knows its possible for a command to return an error. What does that say? He'll be monitoring everything with the serial monitor and if any errors result, he'll see them. I've used this simple sort of code for prototyping before, right before I implement a proper library when I'm done with proof-of-concept. All the other answer gives is a vague reference to a buffer and "just check whatever is the response" for parsing--not nearly enough for a beginner to work with.

You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.
When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.

Yes - though it's not actually necessary to buffer the response, as one can also compare character by character as they are received and keep a persistent count of how many matching ones have been found.  Buffering may be best for short responses like this though.


text:
Arduino due slow clock
To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?
What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?

The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip.  It can also be routed to other places when you want a low speed clock source, but the only places it is actually required are the RTC and the watchdog.
The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal.  Trying to use that for the RTC module will result in the clock drifting over time.  The watchdog won't really care if the clock isn't perfectly accurate.

So I can safely go without slow clock oscillator and my Due will work.
What about the xtal pins.
Can I leave them unconnected?
I didn't find any info about that.

Atmel datasheet says:
If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected


text:
Arduino Due native programming port
Arduino does not recommend to program the Due board via Native port  as it is not reliable:
If the MCU crashed for some reason it is likely that the soft erase procedure won't work as this procedure happens entirely in software on the SAM3X
Unfortunately Arduino doesn't say what is crash and how to solve this issue if your home made Due has only the Native port.
I have only several assumptions but not sure that they are correct.
The Arduino Due boot-loader starts only if the Flash is not programmed. If the code is programmed to the flash but is damaged the boot-loader will not
start. As the MCU is hanged it can not erase the flash.
What can be done in this situation?
Just push the erase button on the board. It will the erase the content of the memory and allow boot-loader to start.
Now the programming via the Native port should be possible.
Please correct me if I'm wrong.

The erase pin can be configured as a GPIO. In this case pressing the erase button will not erase the flash memory.
If this is the case the hardware reset will be necessary.
Don't know yet if the erase button works together with the reset.


text:
Light multiple RGB Led Strips from same 3 RGB PWM outputs
I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.
The scheme i found is this one:

And what i want is something like this:

Is this possible? What should i modify to make it work?
Thanks in advance.

You have few options:

do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.
add a logic buffer inbetween the arduino and the driver stage
use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.

That was very helpful, i was afraid about this current thing, but apparently each 1 meter uses 20mA, and a pin can output 40mA, so 2 strips would be the perfect amount.

Did you check that 20mA is the Max Value, rather than Typical?
You might have some unpleasant surprise, if you take chances and do not plan for the worst case. Same goes  for the Arduino/Atmega: is 40mA the Min Value or the Typical? You should match Min from the source vs Max from the drain and confirm that they are compatible.

That's true. But the max that the strip uses is 20mA at full bright, and the typical that arduino provides is 40mA. Since i'm never gonna use it at full bright i think it should work.

5v with a 220ohm resistor will result in about 20mA of current. Depending on the gain of the transistors and the amount of current the strips use (i.e. depending on their length) 20mA might not be enough to fully saturate the transistor. In that case the leds won't be as bright, and the transistor will get pretty hot. Using MOSFETs will prevent this problem.


text:
Arduino Analog Input Oscillating
I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.
Schematic and Breadboard-
I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.
I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A < output < B power yellow, B < output red.
The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).
It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).
I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below
I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile.
Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. no more than 2 links. AD822 op amp
Here's my code before adding if statements for the LED's. It was incorrect.
int TP=A2; // Assign Thermopile to pin A2
int val; // Declare readValue Variable
float Voltage; // Declare real world voltage variable - Float = in between variable
int ledG = 11;
int ledY = 12;
int ledR = 13;

void setup() {
 pinMode(TP,INPUT); // Declare Thermopile pin as input
 pinMode(ledG, OUTPUT);
 pinMode(ledR, OUTPUT);
 pinMode(ledY, OUTPUT);
 Serial.begin(9600); // Start your Serial Port
}

void loop() {
  val = analogRead(TP); // Read Thermopile pin and place value into readValue

  Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

Serial.println(Voltage); // Print readValue to Serial Monitor
  delay(100); // Delayed output to 1/4 a second
}

You can still workaround the limitation about pictures by combining them with some photo editing SW ;-)

To improve the precision of the calculation, I'd do
Voltage = val * 5. / 1023;

Good idea about combining images..... Updated the question.

LED in the bread board aren't expected to work.

Have you connected your circuit ground to the Arduino ground?

I haven't. Since it was being powered by a battery, I wasn't sure if that would effect the Arduino board. I'll try it out.------- Just connected a wire from board ground to Arduino Ground (while keeping battery ground to bread board) and it seems to have fixed it. Great Suggestion!

@Majenko If you want to post that as a question answer, I'll select it for you.

It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.
Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

In that diagram the red arrows (not the aerial display team I hasten to add) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.

Perfect! Thank you for the extra description! It made understanding what I was missing a lot more clearer.


text:
Is there a away to transmit sensor signal over RF without Arduino?
I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).
Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

Thank you both for very helpful solutions. I've chosen first one, because in  Aliexpress at a lot of 10 I can get all needed components for ~1 EUR and second solution at a lot of 10 costs ~1,8 EUR. Will consider all pros and cons and maybe even stick to pricier solution due its ready-made nature.

What kind of sensor? E.g. there are wireless temperature sensors that you can buy in the store, and the signal those send out can be pretty easily read by and arduino.

I've meant solution available for different sensors not only temperature. I did find wireless sensors to purchase, but these were kind of expensive.

You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

Add to that a NRF24L01 transceiver like this:

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.
So the whole thing could be done for under $10.

Something that could work for considerable duration with a small tablet like battery?

See Power saving techniques for microprocessors

So the only solution is to use NRF24L01 transceiver and barebone Arduino or ATtiny chip. There is no cheap ready-made transceiver that I could connect to sensor and a battery? If no other solutions will be given by other members, I'll select your explanation as an answer. Thanks!

I don't know of any ready-made transceivers that will happen to work with your Arduino base-station.

I would recommend investigating the ESP8266 modules.  Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.
You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.
https://github.com/esp8266/Arduino
It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.
There are many different modules available, some with more pins than others for IO.  The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.

Is it possible to have the ESP8266 run for a reasonable amount of time (>few months) on batteries? I haven't seen any projects that use batteries on the ESP8266.

There is a sleep mode available on it. I don't know how effective it is, or how you use it, but it does exist.

You can probably get it to work if you only send an update every hour or so. More frequent updates will probably drain the battery too soon. Setting up a wifi connection take quite a bit of time. Optionally you could batch upload the data.


text:
Sending and receiving different types of data via I2C in Arduino
I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.
In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.
here is the code for the master
#include <Wire.h>

const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600);  // start serial for output
}  // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
 Serial.print('\n');
   Serial.print(table[0]);
    Serial.print('\t');
   Serial.print(table[1]);
    Serial.print('\t');
   Serial.print(table[2]);
   Serial.print('\n');

delay (500);

// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}

here is the code for the slave
#include <Wire.h>
int table[]={0,0,0};
int Work=0;

void setup() {
Wire.begin(8);                // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}

void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
  table[0]=x;
  table[1]=y;
  table[2]=z;
}

void requestEvent()
{
  uint8_t Buffer[3];
  Buffer[0]=table[0];
  Buffer[1]=table[1];
  Buffer[2]=table[2];
  Wire.write(Buffer,3);
}

void receiveEvent(int howMany)
{Work = Wire.read();}

I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.
After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0
The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.
Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.
//master
#include <Wire.h>

char t[10]={};//empty array where to put the numbers comming from the slave
volatile int Val; // varaible used by the master to sent data to the slave

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

//gathers data comming from slave
int i=0; //counter for each bite as it arrives
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i=i+1;
  }

Serial.println(t);   //shows the data in the array t
delay(500); //give some time to relax

// send data to slave. here I am just sending the number 2
  Val=2;
  Wire.beginTransmission (8);
  Wire.write (Val);
  Wire.endTransmission ();
}

here the other part
    //slave
#include <Wire.h>

char t[10]; //empty array where to put the numbers going to the master
volatile int Val; // variable used by the master to sent data to the slave

void setup() {
  Wire.begin(8);                // Slave id #8
  Wire.onRequest(requestEvent); // fucntion to run when asking for data
  Wire.onReceive(receiveEvent); // what to do when receiving data
  Serial.begin(9600);  // serial for displaying data on your screen
}

void loop() {
  int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
  float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

  dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  Serial.println(Val);         // print the character
 delay(500);
}

// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}

How you request the same size (3) of string as the one you creates? where is the NULL terminator ?

Moreover your dtostrf is very wrong, how the total size of the string is 3 and you have 2 numbers after the point ? 1.2 is 3 chars, how can it have 2 chars after the point ?

This is not a good way, split the value into bytes, make it a byte array and cast it back to, for example, a float. float myFloat = *(float *)&byteArray; What it does, takes the address of the byteArray and cast the byte array (for example uint8_t byteArray[4];) to a float pointer and access it contents. You really doesn't need such expensive translation to a string.

I am 90% sure that the base library does have support for sending more datatypes than just byte. There is also be a method which takes arbitrary data and a "size" which is the number of bytes needed to send that data. See https://www.arduino.cc/en/Reference/WireWrite

I believe that for your scenario, i.e. sending different types of variables, the EasyTransfer library (by Bill Porter) would be an elegant solution. The library can be found here: https://github.com/madsci1016/Arduino-EasyTransfer. There are implementations for serial, I2C, and VirtualWire and the examples provided are pretty self-explanatory.
The handling is very easy. After including the library, you create an EasyTransfer object, define a data structure that basically represents a "container" of your data and this can consist of different variables.
struct RECEIVE_DATA_STRUCTURE{
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int blinks;
  int pause;
};

Once the "container" is filled, i.e. the variables are set on the sender side, they are sent with a simple command
  ET.sendData(I2C_SLAVE_ADDRESS);

On the receiver side, you define an identiacl data structureand receive the data by
ET.receiveData();

Hope this helps.

Thanks, that library is promising. I looked it over but could not find a tutorial to communicate via I2C. The tutorial I found was using tx/rx. is there any example you are aware of?.

I found that easy transfer does not allow slave to master transfer. the slave can receive data from master, but the master can not from the slave. the library will require some changes, that have not been outdated: http://forum.arduino.cc/index.php?topic=171682.0

The github page there is a folder EasyTransferI2C which is also included when you download the ZIP file. In that folder there is an Examples folder, in which you find the sketches for the sender (which is called EasyTransfer_TX_Example) and the other one for the receiver  (EasyTransfer_RX_Example)

I tried the exampled but it only send data from the master to the slave, it does not offer the opportunity to send from slave to master. In the arduino forum above, a person said he improved the library to have that function but it does not appear in github

Sorry, I cannot help you further on this.

I have used it only in one direction (master --> slave). Not sure if the following could work. Have you tried to define both on the master and slave side two data structures with the same content, one for receiving, and one for sending, and try to send it in both directions?

Hmm, I did not try that. I look over the library and was not obvious to me that the slave -->master communication was possible. I ended up going back to the wire library and transmitting values converted to character, which can be transferred easely via i2c. Thanks for you help.

Use the 'I2C_Anything' library, available here. I use it in all my I2C projects.  It is extremely simple and works great. Here's the entire .h file
// Written by Nick Gammon
// May 2012

#include <Arduino.h>
#include <Wire.h>

template <typename T> unsigned int I2C_writeAnything (const T& value)
  {
  Wire.write((byte *) &value, sizeof (value));
  return sizeof (value);
  }  // end of I2C_writeAnything

template <typename T> unsigned int I2C_readAnything(T& value)
  {
    byte * p = (byte*) &value;
    unsigned int i;
    for (i = 0; i < sizeof value; i++)
          *p++ = Wire.read();
    return i;
  }  // end of I2C_readAnything