text:
Easy bipolar motor control?
Is here some easy way to control bipolar motor
 without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise  and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

It depends on the motor but is quite unlikely for most motors due to the limited current (and voltage) the Arduino's GPIO pins can provide.

I have 4 wire motor

Please give us more details.  It will attract better answers.

Welcome to Arduino SE.  Be sure to take the tour to see how things work here:  https://arduino.stackexchange.com/Tour

Please edit your question (click the edit button, etc) and tell what you mean by control – ie, turning the motor on/off, or changing direction or speed, etc.  Also list motor model number or specs  – a low-voltage micromotor might not need external parts, but most motors will.  If you improve the question people may vote it up.

No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.
You need a motor driver (or at least some transistors and diodes etc) to control the motor.

Taking a guess here, the current this motor requires will be exceeding the safe operation limits of the Arduino's GPIO pins. Furthermore without a flyback diode the voltage spike across the motor (an inductive load) when the current is reduced/switched off might kill the GPIO pin.
You will need a motor driver or transistor with flyback diodes to operate it.
This is a nice tutorial that has it sorted out for a CD ROM brushless motor.

It's not just about the current - back EMF from the motor's coils will do nasty things to the Arduino.


text:
Avoid blocking from bluetooth callbacks
I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffer.push(a);
}

void loop(){
    if buffer.isFull() {
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffer.getData());
        myFile.close();
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    int freeSpace = SD.vwd()->fileSize();
    // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace);
}

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.
What is the recommended technique to make sure that data collection process will not be affected?
UPDATE:
The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?

Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.
Then the main problem - RF - I would bet, that the on_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)
So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.
So more like this (did not tested it, just idea):
volatile buffs[2];
volatile actBuff;
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffs[actBuff].push(a);
}

volatile int freeSpace;
void loop(){
    if buffs[actBuff].isFull() {
        int fullBuff=actBuff;
        cli();             // disable global interrupts
        actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
        sei();// enable global interrupts
        // ISR have nice free buffer to fill, we will write and empty the old one
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffs[fullBuff].getData());
        myFile.close();
        buffs[fullBuff].empty()
        int tempval = SD.vwd()->fileSize();
        cli();             // disable global interrupts
        freeSpace = tempval;
        sei();// enable global interrupts:
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    // int freeSpace = SD.vwd()->fileSize();
    // do the same trick here // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace); // use the value from loop
}

source: Stack Exchange

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

sort: votes


text:
How to find the pin map for the LCD 1602 I2C adapter module?
I'm working with I2C to work with my LCD 1602 and the I2C adapter.
This module has 16 pins and I don't know how to communicate with it.
I2C sends 8-bit packets. What are the commands to deal with this module, because it has 16 pins?
This is my current code:
void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x20);
  I2C_TWSR_Check();
}

void loop() {
  uint8_t i;

  for (i = 0; i < 5; i++)
  {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1 << TWEN);
}

void I2C_start(void) {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));
}

void I2C_stop(void) {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1 << TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch (Status)   {
    case 0x08:    // start OK
      Serial.println("Start is OK");
      break;
    case 0x10:    // Re start
      Serial.println("Re start");
      break;
    case 0x18:        // SLA+W OK ACK
      Serial.println("SLA+W OK ACK");
      break;
    case 0x20:        // SLA+W no ACK
      Serial.println("SLA+W no ACK");
      break;
    case 0x28:        // data OK ACK
      Serial.println("data OK ACK");
      break;
    case 0x30:        // data OK no ACK
      Serial.println("data OK no ACK");
      break;
    case 0x38:        // arbitration lost in SLA+W or data TX
      Serial.println("arbitration lost in SLA+W or data TX");
      break;
    default:
      Serial.println("Error");
      break;
  }
}

I don't know I get first case working all the time. I can't proceed to sending the data.
This is the most I got from google images:
PCF8574 I2C backpacks for HD44780 Compatible LCD Module Arduino Raspberry

Re all the strings in I2C_TWSR_Check(), surround them with F() to store the strings in PROGMEM rather than also in RAM.  Re the “first case working” issue, you might need to describe at more length what happens.

The ￼tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino (with material that also appears in an instructable) includes a sketch that most likely will work with that backpack.
Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at arduino.cc's LCDi2c Library page and at arduino.cc's LCD API 1.0 page will apply.
The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:
#include <LiquidCrystal_I2C.h>
...
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal_I2C.h:
@param      lcd_Addr[in] I2C address of the IO expansion module. [...]
@param      En[in] LCD En (Enable) pin connected to the IO extender module
@param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
@param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
@param      d4[in] LCD data 0 pin map on IO extender module
@param      d5[in] LCD data 1 pin map on IO extender module
@param      d6[in] LCD data 2 pin map on IO extender module
@param      d7[in] LCD data 3 pin map on IO extender module

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack.  Note, if your backpack has a PCF8574A, its address is 0x3F.
The other seven numbers describe which PCF8574 output pin is connected for each designated purpose.  Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

Edit 1: If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the LCD API mentioned earlier.  By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface.  In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.
In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.
LCD:  Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring.  With the wiring known to work, develop an LCD control library.  This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets.  The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.
Backpack:  Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins.  Use appropriate resistors to V+ on the anode sides of the LEDs.  Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino.  Write simple test software using Wire.h calls to send data to the PCF8574, verifying proper operation using the LEDs.  This may require detailed study of the Texas Instruments PCF8574 Remote 8-Bit I/O Expander for I2C Bus data sheet.  Write your PCF8574 control library.  Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.

I'm sorry I didn't mention that I want to develop a C code by my self, because I want to develop my own libraries so I have more programing knowledge and skills, and not only use pre-written libraries like Arduino libraries. Because C++ codes and libraries are my next goal after I have enough experience with C.

@PerchEagle, set edit 1

Yes, absolutely :) thank you very much for reply and help I really appreciate the help I get for engineers these days, I now working to get the I2C protocol in a clear picture so I can get to work with many I2C modules I have. In regard to your reply, I did a 4-bit interface and I did it good enough. Now I want to connect it with the I2C so I save pins and get advantage of the I2C because it allows you to work with many devices at the same two lines.

I uploaded my code in the main post. Regards,

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


text:
Transfer 10-bit via Arduino-to-Arduino SPI protocol
The task I need to accomplish is as follows:
I have an analog/digital converter that sends out a 10-bit signal. This signal needs to be transferred to an Arduino Uno using the SPI protocol. Because the SPI protocol works with a 16 bit pattern I need to expand the incoming signal. The slave Arduino then needs to put out the transferred number in decimal.
I imitated the ADC with another Arduino Uno, setting it as master, but unfortunately at the time I only had one Arduino so I couldn't test my code. Furthermore, I don't really have a clue how to "expand" a 10-bit signal to a 16-bit one. Can someone please explain it to me and have a look at my code?
Code for the master Arduino:
#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  SPI.beginTransaction(SPISettings(62500, LSBFIRST, SPI_MODE0));
}

void loop() {
  byte x=0000001101;
  byte y=0011111111;
  digitalWrite(SS,LOW);
  SPI.transfer(x,y);
  digitalWrite(SS,HIGH);
  delay(1000);
}

Code for the slave Arduino:
#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, INPUT);
  pinMode(MOSI, INPUT);
}

void loop() {
  byte x=SPDR;
  byte y=SPDR;
  printf(x,DEC);
  printf(y,DEC);
  delay(1000);
}

A byte is only 8 bits, so your code:
  byte x=0000001101;
  byte y=0011111111;

won't do what you think it does.
A 10 bit value will be stored as an int (which is 16 bits) or 2 bytes.
Assuming it is an int then this will convert it to two bytes.
 const int adcData = 0x03FF;  // From ADC
 byte dataToSend[2] = {0, 0}; // Initialise it to zeros
 dataToSend[0] = (adcData & 0xFF00) >> 8;  // didn't really need the bit mask just to make it clearer.
 dataToSend[1] = (adcData & 0x00FF);
 // Now send dataToSend via the SPI bus.

To reassemble the data on the otherside:
 byte dataReadFromSPI[2];  // Filled with the data read from the SPI
 int adcData = 0;
 adcData = (dataReadFromSPI[0] << 8) | (dataReadFromSPI[1]);

Please note that 0000001101 is not a binary number in C/C++. It is actually octal (577). GCC allow an extension of number literal syntax for binary numbers. 0b0000001101 or the Arduino style B0000001101.

Could you please also explain how to transfer a whole array over the SPI protocol. I struggle a bit with that one...

I haven't used SPI, but you should be able to find some example code.  There will be a function that writes some data to the SPI bus, it will probably accept a single byte, so it may well be as simple as calling it twice.  There is usually some start transmission and end transmission functions, make sure you call this write function between these two calls.


text:
How to connect an Arduino to WIFI using an ESP8266
Hi I am trying to make Arduino Uno on local network with the help of ESP8266 wifi module.
I tried to search on internet, found mostly they are making ESP8266 as web server.http://circuits4you.com/2016/12/16/esp8266-web-server-html/
Can anyone help me how to add Arduino Uno on network with the help of ESP8266.

Have the idea of searching this very same site with the words "Arduino" and "ESP8266" ever come to your mind?
Please have a look at https://arduino.stackexchange.com/questions/13470/arduino-with-esp8266 and also https://arduino.stackexchange.com/questions/30837/setup-arduino-uno-with-esp8266-esp-1. By refining your search you might also find additional answers to more detailed questions that might arise as you move forward with this project.

@RobertoLoGiacco I see those examples but they are sending some commands to ESP8266 and reading it. I have done this example. I want something like get the dynamic ip from wifi network with SSID and password and assign it to arduino so i can access it from network

getting a dynamic ip from wifi is DHCP client. You cannot assign an IP to an Arduino, only the ESP8266 has some knowledge of being on the network.
Your question is so broad and vague it would require a series of blog posts to get covered in all its aspects. You didn't even explain your wiring between ESP8266 and Arduino, so we are assuming you are using an hardware serial connection, but yous "assign Arduino an IP" made me doubt about this.

This was closed as unclear. I have re-opened it at the OP's request. I think it might be classed as "too broad" but let's see where the answers take us.

Sending the following commands to the ESP should get you started:
AT+RST                         # Reset
AT+CWMODE=1                    # Set to station-mode as a client
ATE0                           # turn off command echo
AT+CWLAP                       # optional: list access points
AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

(I made-up the comment syntax; don't try to send those.) The full
ESP8266 AT Instruction Set has the complete set of commands and a functional description of each one.
Update:

... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to
  TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).

For this approach do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to TX of Arduino, Ground of Arduino to RESET ?

No you still need to cross them over.

I have this code https://pastebin.com/C4ZUmVc0 when I am sending AT commands to ESP8266 it is working and blue light blinks.. now I have coded as you suggested.. now I want to know allocated IP address of it ? any way of it ?

Here is my logs Sending an AT commands
Got response from esp8266: AT+CWMODE=1
Got response from esp8266: ATE0
Got response from esp8266: busy p...
Got response from esp8266: AT+CWLAP
Got response from esp8266: busy p...
Got response from esp8266: AT+CWJAP_DEF=Moto,reset1234
Got response from esp8266: busy p...
Got response from esp8266:
Got response from esp8266: OK

All of the commands are documented in the manual I linked, but "AT+ CIFSR" seems like the one you want.

I am facing some issues while connecting ESP8266 with WiFi with AT commands. I asked here do you know what is the issue https://arduino.stackexchange.com/questions/37976/error-on-sending-atcwjap-def-commands-to-esp8266 thanks for suggesting to use AT commands. +1

It depends on how you want to approach it.  I know of two options:

Use AT commands.
Program the ESP.

When you are using AT commands you need to program the Arduino to open a serial line to the ESP (ensuring rx and tx are crossed over).  You tell the Arduino to send the AT commands you need to the ESP and wait for each one to be acknowledged.  Then the Arduino sends its network data via the serial connection, to the ESP and the ESP will forward it to the network.
You can program the ESP in EXACTLY the same way as you would the Arduino.  You could write some code to accept data from the Arduino over either Serial, SPI, I2C or your own proprietary communication method.  The ESP has libraries to be a DHCP client, DNS, HTTP client, etc. (most of which you have probably seen already).  If you then write a simple application that establishes the connection to the network and then waits for a packet of data from either the Arduino or the network and forwards it as appropriate.
I can't tell you which option is best, because I have never tried either method.  I just program the ESP to do everything that the Arduino would have done anyway and simplify the code.

I was trying to program ESP8266, have some kinda setup like I connected Arduino to my laptop, connected RX of ESP8266 to RX of Arduino, TX of ESP8266 to TX of Arduino, Ground of Arduino to RESET. But I was doing something like https://arduino.stackexchange.com/questions/37798/error-espcomm-open-failed I pasted my error logs also there..

I hope my setup was correct ? What could be cause of errors ? Would you care to answer there please ..

Arduino Rx <- ESP TX and ESP Rx <- Arduino TX.  The Arduino transmits on the Tx and the ESP listens for it on the Rx, and vice versa.  If you do Tx to Tx and Rx to Rx it won't work at all.  BTW Most people make that mistake first time.  Also the Gnd of the Arduino and ESP must be connected together, otherwise you can get a floating ground, which will result in them not knowing what Low and High are.  You should also use a bidirectional level shifter for any connections (except Gnd) between a 3.3v device (ESP) and a 5V device (Arduino)

I have connected and ESP8266 is able to receive command whatever I am sending like this https://pastebin.com/YYSjASZe now can you please suggest what changes do i need to make to get allocated ip address so i can access it from network I have selected "Arduino Uno" as board in Arduino IDE


text:
How to set alarm on DS3231 sensor?
I want to know if it is possible to set an alarm in DS3231.
I want to set the alarm every 6 AM in the morning. Is this possible?

Yes it is (see datasheet datasheet) ... the DS3231 has 2 alarms.
There is also a library for the Arduino, see: library.
The alarm(s) can be set (repeatedly) via one of the following functions:
Alarm.alarmRepeat(hours, minutes, seconds, function);
Create an alarm that will call a function every day at a particular time.

Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function every week on a specific day at
a particular time.

 "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
 dowThursday, dowFriday, or dowSaturday.

Detailed info and more functions: link

is it okay that i used the SDA SCL pins ? for ds3231 although I use the timelib.h and timealarm library?

I'm not sure, I never played with I2C so far, I see the DS3231 uses I2C, so I assume the library uses I2C to interact with the DS3231. Probably it needs to be connected via I2c (thus SDA/SCL).

When I try this Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day   Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day using the timelib.h and timerAlarm.h library , when i close the serial monitor it restart counting ..

What do you mean exactly with 'restarts counting' ? I assume when the alarm(s) set is equal to the time of the IC, the alarm callback function is fired.

In the TimeAlarmExample ..
setTime(9,21,0,05,03,17); // set time to Saturday 8:29:00am Jan 1 2011 time is set to 8:29 am .. and then Alarm.alarmRepeat(8,30,0, MorningAlarm); // 8:30am every day  when i close the serial monitor it restart counting back to 8:29 am ..

Is it possible to achieve alarm using DS3231.h library ?

I think it is, but I never tried.

But if you first set the time (to 8:29) and than the alarm (to 8:30), the time will not change; it should continue counting from the time it was set (8:29), and never reset back to 8:29 or counting backwards.

I find the answer to my question .
I just add Time  t; and t = rtc.getTime(); into my code then an if statement like this if (t.hour == 11 && t.min == 59 && t.sec == 00)
ref http://www.instructables.com/id/Setup-for-DS3231-AlarmTimer-Function/

The correct way to use RTC alarms is to setup them to fire an interrupt when alarm date/time occurs. This way MCU doesn't have to poll RTC frequently. The configuration is described in "Alarms" paragraph of the datasheet.


text:
#define VS local static const char
Could someone give me a hint regarding what would be the best practice to save memory: should I #define strings or use local static const char arrays?
Code example, option #1:
#define         LCD_LIMIT   "Number of hours"
...
setup(){
    DisplayData(LCD_LIMIT, actual_Data);
}
...
void DisplayData(const char *theme, String data){
}

Code example, option #2:
setup(){
    DisplayData(actual_Data);
}
...
void DisplayData(String data){
    static const char theme[] = "Number of hours";
}

Cheers

Check out PROGMEM to put data in flash mem.

Thanks @JohnnyMopp! Does it mean both my two options are similar in terms of memory footprints and digging PROGMEM is much more interesting?

The #define will be substituted in at compile time. So as far as memory usage goes
#define MYSTRING "hello world"
DisplayData(MYSTRING);

and
DisplayData("hello world");

are completely identical.
but
static const char theme[] = "hello world";
DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).
However if you are using the same string twice or more then things are different.
The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.

Thanks for this detailed reply. So does this also apply to static const char arrays declared only locally (and therefore only called when the function itself is called?

A static variable declared within a function is basically a global variable that the compiler won't let other parts of the code access. It exists at all times, not just when the function is called and so takes a constant amount of memory. If it was local but not static then it would only use RAM when in the function but you would have the performance hit of copying the string from flash to RAM every time the function was called.

As Michel indicated in his answer the F() macro will store the string in flash and not copy it to RAM which will use less memory but may give a tiny performance hit.

Thanks @Andrew for the clear explanation, I really got it.

I think they both are similar with respect to memory stored in the heap.
However, since you pass one extra pointer, it cost 2 of 4 bytes extra on the stack (temporary space).
To save more memory use the F() function to store it in FLASH (32 KB on Arduino Uno) instead of the heap (only 2 KB). By using
static const char theme[] = F("Number of hours");


text:
Combining code for two sensors in one programming
We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.
We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.
TH02 Code:
 void setup()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void loop()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
delay(1000);
}

DHT11 Code:
byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setup()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void loop()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

delay(2000);
}

We are new to arduino and we are trying to understand the codes and how the functions work.. It will be a great help if someone makes us understand what we are doing wrong.

This example combines both codes but uses a single delay. If you want readings at two different times you should use two unsigned long global variables to store the millis() of the last time the functions were called. Then you use an if statement to only call readTH02() or readDHT11() when the last millis is less than the <= current-interval.
It is better to use millis interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called BlinkWithoutDelay to understand how to use intervals instead of delay()
void setup()
{
  setupTH02();
  setupDHT11();
}

void loop()
{
  readTH02();
  readDHT11();

  delay(1000);
}

void setupTH02()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void readTH02()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
//delay(1000);
}

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setupDHT11()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void readDHT11()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

//delay(2000);
}


text:
Serial monitor isn't updating in while loop
I'm trying to make a lamp that fades when it reacts with surrounding light. I've installed a library from github  that doesn't require the delay (). The serial monitor doesn't refresh.
The lamp is supposed to fade from 0-255 when in the dark and fade 255-0 when in light. It's supposed to happen only once so I can't put it in loop().
The LED is connected to PWM pin 10. The LDR sensor is connected to A0.
#include <LEDFader.h>
int sensorvalue = analogRead(A0);
LEDFader led = LEDFader(10);

void setup(){

  if(sensorvalue<=380){
    led.set_value(0);
    led.fade(255, 3000);
  }
  if(sensorvalue>=555){
    led.set_value(255);
    led.fade(0,3000);
  }
}

void loop() {
  Serial.begin(9600);
  Serial.println(sensorvalue);
  led.update();

}

Please post the code as something other than a screen shot. You have some fairly big mistakes in that code but I'm not going to sit here re-typing it from a picture when you can't be bothered to copy and paste it.

@Andrew  sorry was typing this question on a mobile phone. Code will be up in few minutes

@Visual Micro  i can't put the fade code at while loop as it will repeat it's process of turning on and off. I only want it to do it once

I have edited the example to show how to only change fade when the analog value changes. If you only want it once then do it in the setup() but if it needs an analog reading that does not make sense. My example shows how the fade can respond to a valid analog reading at any single moment.

Maybe you were still struggling so the answer has been updated to a complete working example.

@VisualMicro but will the fading keep repeating itself? Cause I'm trying to find a way that only runs once.

You need to be clear about what you want to happen once? If you put all the code in the setup() it will happen only once with the analog reading found when the cpu starts. If you put the led.update() in the loop then the loop will keep fading the led using the values read once in the setup(). So put the code in the setup that needs to run once. I will try to update with a few variations.

Arduino does not work that way. You only try to read a sensor value outside of a function, so will happen once only, if it works at all. You need to read the sensor more often and always read from within a function.
Serial.begin() is used once when the code starts, so that will be in the setup()
Your LED fade values are only set one time, when the cpu starts because you have the fade in the setup().
In the following example we do all fade code in the loop() but change the fade values only when the sensor reading changes.
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;
int sensorValueLast = 0;

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

void loop()
{
  sensorValue = analogRead(A0);
  Serial.println(sensorValue);

        if (sensorValueLast!=sensorValue)
        {
          sensorValueLast = sensorValue;
          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }
        }

  led.update();
}

This example only calls led.fade() when the sensor value changes but uses the same sensor reading that was found during startup. The sensor is read just once time and the fade values are set just one time.
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;
int sensorValueLast = 0;

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

void loop()
{
  sensorValue = analogRead(A0);
  Serial.println(sensorValue);

        if (sensorValueLast!=sensorValue)
        {
          sensorValueLast = sensorValue;
          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }

          led.update();
        }
}

This example does everything just one time, when the cpu starts
#include <LEDFader.h>
LEDFader led = LEDFader(10);

int sensorValue = 0;

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

   sensorValue = analogRead(A0);
   Serial.println(sensorValue);

          if(sensorvalue<=380)
          {
             led.set_value(0);
             led.fade(255, 3000);
          }
          if(sensorvalue>=555)
          {
            led.set_value(255);
            led.fade(0,3000);
          }

          led.update();

}

void loop()
{
   //we will always see the same value
   Serial.println(sensorValue);
}


text:
#endif without #if
I have an extrange Problem...
I have written this short code:
////////////// BOARD SETTINGS \\\\\\\\\\\\\\
#define BAUD_RATE 9600

// Board type selection
// Uncomment the wanted
//#define WAND 0
//#define GUN 0
#define RIFLE 0

////////////// WAND SETTINGS \\\\\\\\\\\\\\
#ifdef WAND
//#define USE_CHARGER 0

#endif

////////////// GUN SETTINGS \\\\\\\\\\\\\\
#if GUN
//#define USE_CHARGER 0

#endif

////////////// RIFLE SETTINGS \\\\\\\\\\\\\\
#ifdef RIFLE
  #define USE_CHARGER 0

#endif

It's in a file called Settings.h, that I use in the main code:
#include "Settings.h"

void setup(){
  Serial.begin(BAUD_RATE);
  #ifdef WAND
    Serial.println("Initializing Wand...");
  #endif
  #ifdef GUN
    Serial.println("Initializing Gun...");
  #endif
  #ifdef RIFLE
    Serial.println("Initializing Rifle...");
  #endif
}

void loop(){
  #ifdef WAND

  #endif
  #ifdef GUN

  #endif
  #ifdef RIFLE

  #endif
}

But for an extrange reason, it gives me this error: error: #endif without #if
Full error is:
In file included from D:\MEGA\Winsoft\Projects\Hardware\MWands\Arduino_5\Arduino_5.ino:1:0:

Settings.h:15: error: #endif without #if

 #endif

  ^

Settings.h:21: error: #endif without #if

 #endif

  ^

Settings.h:27: error: #endif without #if

 #endif

  ^

exit status 1
#endif without #if

Any idea in where am I wrong?
And taking advantage that I'm asking, is necessary the 0 after #define RIFLE 0, next to each definition?

The way you are using it, no you dont' have to add the 0 #define XYZ is enough. #ifdef XYZ will work for this case.

Also, you have declared #if GUN which you probably meant #ifdef GUN.

Using #ifdef and ending with #endif still showing me that error

I didn't say it would fix the error, I was just answering your second question "is it necessary to have the 0..."

It looks like your comment style is causing the problem.
Remove the ////////////// BOARD SETTINGS \\\\\\\\\\\\\\ style comments, or change them to something like: /*----------- BOARD SETTINGS -----------*/

The \ at the end of the comment continues the current line onto the next one, so you get ///// comment \\\\\#ifdef... which comments out the #ifdef.

If you remove backslashes at the end of comments on lines before #ifdefs, it will work just fine.
The gvim editor was much more helpful in that:


text:
Arduino Nano Circuit grounding
I am making an LED circuit for a Lobot (from star wars) costume headset that will not be on a PCB or stripboard. It will all be running inside the walls of the plastic shell I am making. Please see Gif of what I am hoping to do:

EDIT:
The LEDs will run through 4 different programs. Here is one program as an example:
-Far left and right led pairs will alternate on/off
-Single LEDs will blink twice then off for a cycle
-The (4) pairs on the left and right will rise and fall like a soundboard
-The (3) pairs of white(blue in the demo) will chase bottom to top and back down again
I am new to electronics so I am a little nervous about running the ground wire for it. Here is my circuit:
EDIT 2:
Here is a reworked diagram based on the suggestions i received below:

The reds were switched to blue for the simulation but will actually be white. So they are 3v each but running in parallel will need 100ohm.
Now that we have that out of the way, is the ground wire run correctly?
The simulation runs perfectly, but I want to make sure that I am not overlooking something important before I try it on my arduino IRL. Is there a neater way to do this? Google searches availed me not. What is the accepted method for this type of circuit?

Hello and welcome. Most of your LEDs miss their current limiting resistor. I am not sure about the Arduinos digital outputs but typically that is not a safe thing to do.

Could you describe how you want it to behave, please? The circuit is unusual, but perhaps it makes sense when you know what you're trying to achieve.

@MarkSmith I edited my original post with more details on the program i am running. I had to double-up the LEDs to slim down the circuit due to the limited number of pins on the nano.

The schematics is unfortunately somewhat complicated to read as one has to look at the pinout to understand it. When comparing it to the pinout however I find a few things that are odd, e.g. one of the green wires (top, fourth pin from the right) is connected to GND.
Note that the sum of the forward voltages of the LEDs connected in series need to be (significantly) lower than the supply voltage of the Arduino. This forward voltage is different for differing LEDs (depending on the colour). Blue LEDs have a higher voltage (typically 3.0 - 3.5 volts). Connecting two blue LEDs or some more red LEDs in series leads to a necessary forward voltage higher than what the Arduino can provide.
Be sure to add the current limiting resistor for the LEDs in the appropriate places. Due to the non-linear current-voltage characteristic of (light emitting) diodes those resistors are a must-have (unless driving them with a current source, which the Arduinos GPIO pins are not). Do use one resistor per LED or if LEDs are connected in series. Do not use only one resistor for LEDs wired in parallel. For more details on this topic see here.
Edit to add (revision of question):
Given 3 V forward voltage and 100 Ohm series resistor one LED presumably leads to a current of about 20 mA. But since you intent to drive two LEDs in parallel (so 40 mA) from each pin, you're well out of spec and hitting Absolute Maximum Ratings:
DC current rating, source:

DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  20 mA

Absolute Maximum Rating, source

DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  40.0mA

Furthermore you intend to connect 18 pairs of LEDs (give or take the red LEDs). This would be a total current of 720 mA which is significantly above the limits of the microcontroller. Consider that all the current flowing through the LEDs into the GPIO pins also needs to flow to VCC through the controllers power supply lines (just two pins!). Those have limits too:
Absolute Maximum Rating, source

DC Current VCC and GND Pins  . . . . . . . . . .  200.0mA

You need an external driver (such as the ULN2803, as presented in this answer) or transistors.

I apologize for the confusing schematics. The Arduino i used in the fritz was a micro, not a nano. The major difference is the micro has two additional rows of pins that i am not using see image here: link

@AndrewMetzger, Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D

As to the resistors, i have tested it on an uno without having any issues but I can add them onto the circuit. Based on a calculator i used online, i would need 30ohms of resistance for the reds and for the whites the current is too low, which i am fine with a lower output.

Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino

I am putting all comments here as answer.
Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D
Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino.
To make it SUPER COOL i would suggest WS2812B LEDs. They need 5V, GND, and Data in. And you can make it any color you want and control all LEDs separately.
Some video about WS2812B
I would strongly recommend it.

Thank you so much for the advice. If I had not already programmed this using the Arduino I would definitely look into your suggestion of the alternate chip. Provided I add the resistors has everyone suggested comma would the circuit work with the ground wire the way it is?

This chip does not require to change your code, and it is easiest to change few lines in your code, rather than make new pcb. When i will get back home i will make few hints for you.


text:
Using a 4*4 keypad to enter an integer value
I have a 4*4 keypad and I want to use it to enter a number.  I will then use this number as a delay to a LED or a motor to run for the specified time.
This is my sample code:
#include<Keypad.h>
#include<LiquidCrystal.h>
const byte numRows = 4; //number of rows on keypad
const byte numCols = 4; //number of columns on keypad

char keymap[numRows][numCols]=
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'X', '0', 'Y', 'D'}
};

char value[4]="";
int index = 0;

byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

Keypad key= Keypad(makeKeymap(keymap), rowPins, colPins, numRows,numCols);

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
lcd.begin(20,4);

lcd.print("       WELCOME      ");
delay(100);
}

void loop() {
char keypress = key.getKey();
while (keypress != NO_KEY){
  if (keypress == 'X'){
      lcd.clear();
      for(int j=0;j<=4;j++){
        value[j]=0;
      }
      index=0;
      }
   else if (keypress == 'Y'){
      int amt = atoi(value);
      digitalWrite(13, HIGH);
      delay(amt);
      }
   else
      value[index]=keypress;
      index++;
    }
}

How do I read the value returned by the keypad as an integer?  (When I press 3 I want to read 3 not "3").

Hello and welcome! What is your actual question?

from this code i should be able to get the input from the keypad and pass the value to delay the led

Am I missing something, any reason you can't initialize keymap to contain 3 rather than '3'? It's an array of 8 bit values, why not set it to be the numbers you want rather than text characters?

You can easily read by this line of code
value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3

I would write '0' rather than 48. The two are equivalent, but the former makes it clearer that you are subtracting the code point of the digit zero.

Your problem is that you have your keypress matching inside a while loop. That means it will, once matched once, continue matching over and over again as infinitum. You need to replace your while with an if so it only runs once for each keypress.


text:
Basic questions on Inputs
I'm completely new to Arduino or even micro-controllers, I'm not even good in physics.
First of all, I'll explain what I am trying to build:
I have an Arduino Nano, for a university project (computer science) I'm trying to make an alternative controller(HID). This controller will be a simple glove, which contains conductive yarn from the Arduino to each finger. If two fingers connect their conductive yarn, I know which fingers are connected and I map this to an input for the computer, which I connected to the Arduino.
For example, if the thumb touches the index finger, it means an X on the computer.
To get the code done is not the problem I guess.

Since I'm completely new, I have some pretty basic questions:
1) Can I use the circuit diagram I created or won't it work? Imagine the switches are my hand, which works like a switch.
2) Does my circuit need a connection to 5V and ground, or can one of the pins be a GROUND / 5V?
3) To know if a switch is active, do I have to watch for changes on the pin? For example, the pin is LOW, is it HIGH after the circuit is "closed"?
If you guys can provide me further information for my project or nice tutorials to get in touch with micro-controllers, I would really appreciate it.
Thank you in advance!

That is not even close to what almost every switch input tutorial explains.

Are both hands independent or would it be possible to e.g. contact left thumb with right index?

1) Can i use the circuit diagram i created or wont it work?

It won't work. The reason is when the switches are open the input pins are floating and that means they could be HIGHor LOW or flipping back and forth. You want the pins to be always in a specific state whether the switch is open or closed. To do this a pull-up or pull-down resistor is used. This resistor sets the pin to HIGH or LOW respectively when the switch is open but the value of the resistor is chosen so that when the switch is closed it overpowers the resistor and the pin reads the opposite state. Since you have your switches connected between the input pin and 5 V you would need to add a pull-down resistor to every pin. That's easy enough but there is an even easier way. The microcontroller on your Nano has internal pull-up resistors you can turn on by doing this:
pinMode(inputPin, INPUT_PULLUP);

See: https://www.arduino.cc/en/Reference/PinMode
So using the internal pull-ups meas you wouldn't need to add any extra components. But a pull-up isn't helpful if you have your switches connected to 5 V because that would make the pin read HIGH whether the switch is opened or closed. So you would need to connect the switches to GND instead. This would mean that the input pin will read HIGH when the switch is open and LOW when the switch is closed.

3) To know if a switch is active do i have to watch for changes on the Pin?

Of course. The easiest way to do this is with digitalRead().
See: https://www.arduino.cc/en/Reference/DigitalRead
You need to make sure your code is non-blocking. When blocking code like delay() is used the microcontroller will not be able to check the state of the input pins and so you could miss touches or have the controller not be responsive enough.

When you're dealing with switches, you need to watch out for 'bounce'. This means that a switch is never perfect and when it changes state from ON to OFF or vice versa, usually there are several fluctuations that take place before the switch settles on a final ON/OFF value.
You could debounce your switches by either hardware or software. If you're debouncing your switches by software basically you run a check on each switch to see if it's digital value has stabilised over some finite time period (usually a few milliseconds) and take action on the switch value only AFTER its value has stabilised.
Hardware debouncing makes use of capacitors in your circuit that prevent high frequency fluctuations in the line from reaching your digital pin. Put simply, the capacitor acts like a channel to 'drain' away variations in voltage. If you are implementing hardware debouncing, you can just do a digitalRead() to read your pin.
http://dduino.blogspot.in/2012/03/arduino-button-debouncing.html

You can also buy ICs that debounce switches.  They are supposed to be for reset switches on microprocessors.


text:
SPP-C and HC-05 are they the same thing or something else?
I was actually thinking to buy a cheap HC-05 module while I was searching I found a similar (think so) module It say it is a replace for HC modules.
Is it compatible with Arduino Nano and will it work same as the HC-05 module ????

In theory they are the same and have the same capabilities. Practically they are not. With SPP-C you get twice the headache for half the price as for HC-05. In had to find it out the hard way Sending data using Bluetooth SPP-C Module without a Breakout-Board. I tried both SPP-C and HC-05 with and without breakout boards finding the same issues. So if you are willing to spend time, risk your project and save some money then use SPP-C. Otherwise use the well known HC-05.

What about using with a breakout board will it be easy ???

As I wrote, I tried both. But yes. They are supposed to work as a drop in replacement.

Yes, both the SPP-C and HC-05 are compatible with the Arduino range, and they do work in pretty much the same manner!


text:
Can I connect an Arduino Uno Wifi to Arduino Cloud?
Can I connect an Arduino Uno Wifi to Arduino Cloud? If yes, how? If no, what cloud is compatible?
I have tried to look online but I could not find anything that raises this question.

If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.
Another option is the Yun shield which turns your Uno into a kind-of Yun.
There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

* Cloud: n. An idiotic buzzword used to describe pretty much any website these days.

Voted for just because you clearly defined what cloud means :)

As noted above, if you can comply with the interface you should be able to talk to 'the cloud'.  You should even be able to use a PC based web browser.

I believe the Arduino White Fluffy Insubstantial Thing requires encryption (SSL), so basic shields won't work with it - hence the requirement of the WiFi Shield 101.


text:
How to program Fio v3 without MicroUSB port
I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why.  Is there any other way to program it?  I'm thinking perhaps those 6 pins under the microcontroller?

Also can I still power the board?  I notice it doesn't have a VCC or RAW pin like the Pro Micro version.  I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?
I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at.  Here are some relevant links anyhow:

Product page
Schematics
Datasheet

The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.
Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.

Ah cool thanks.  I also found these under the zigbee, I don't suppose I can solder a USB cable into them can I? https://www.dropbox.com/s/jv5r2c84saajrdv/IMG_20170505_013718.jpg?dl=0

@hamstar I have no idea what that is, but I don't see anything related to USB there.

Looking at the hook up guide might help.  https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide
The "best" solution might be to try and get the connector replaced, if the pads are still OK.  But soldering those connectors is not an easy task.
The datasheet you linked to is the Lion charger, forget about that PDF.

Thanks, yea the pads are no good and I am not very accurate at soldering. I checked that guide but it has no mention what the 6 pins in the middle are.   I also found some pins under the Zigbee board labeled DTR and CTS with but it seems they may be the serial connection to the Zigbee (https://www.dropbox.com/s/jv5r2c84saajrdv/IMG_20170505_013718.jpg?dl=0).


text:
I can't upload my program to Arduino Uno
I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

I reset immediately after uploading but it doesn't work.What else should I do?
I'm using Ubuntu and the Arduino IDE.

https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

Checks:

Check if the board has power (probably it will).
Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
Check if you have multiple versions of the IDE running.
Check if you have multiple IDEs installed.
Check if you don't have the RX pin used while uploading a sketch.

Try the following:

Use a different USB port on your computer
Use a different USB cable
Reinstall the Arduino IDE

Apparently, I had two versions installed and I was launching the wrong one (Arduino Genuino). Thank you

You are welcome ... you also can change the board in the IDE (I will update my answer)

I struggled with a failure to upload the Blink program, with LED between #13 pin (+) and GND lead.
My solution was found by choosing other serial ports by stepping through the Serial Port options under the Tools menu
Selecting the correct port brought my new board to life!

Hi and welcome to Stack Exchange! How does this differ from the second point in the accepted answer?

Make sure you have a current limit resistor between #13 pin and the LED, like 270 ohm to 1K, 2K, in that range.  Don't burnout your IO pin.

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


text:
Detect certain characters and if not a consequence
How can I program in Arduino Uno a serial.available that will detect some chars that aren't supposed to belong in a list of options, like this:
void lerRespostaUtilizador(){
  if(Serial.available('s' && 'v' && 'r'){
    Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
  }
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
      Serial.println("");
      break;
    }
}

What I want is if the user inserts some chars that aren't 's', 'v' or 'r', a message will appear saying what they can insert to obtain certain results.

Check this Serial.available('s' && 'v' && 'r'). I can guess what you think it means but it does not.

How can I correct it then?

Simply wait for something to read, read the character, and add a default switch section case that catches illegal characters.

I would rewrite that as something like this:
void lerRespostaUtilizador(){
  while (!Serial.available());
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      break;
    default:
      Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
    }
}

Yeap, that works perfectly!
But can you explain me how the while works and how is it connected to the default option?


text:
I2C begginer with I/O expander with mega328p C code
I've just started with the I2C protocol. I read about it in the datasheet, other documents, blogs and videos.
So, I started to develop my code and I think I did my first success, I succeeded to send start and check TWST for sending start signal.
I get started OK, but I can't proceed to send data. What I'm missing? I'm thinking I didn't send the correct address.
void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  Serial.begin(9600);
  I2C_init();
  //  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x40);           // sending the address
  I2C_TWSR_Check();       // waiting for response
}

void loop() {
  uint8_t i;
  // simple loop to blink an LED on the I/O expander pin
  for (i=0;i<5;i++) {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
    I2C_tx(0x00);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(void) {
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void) {
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1<<TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status) {
    case 0x08: // start OK
    Serial.println("Start is OK");
     break;
    case 0x10: // Re start
    Serial.println("Re start");
     break;
    case 0x18: // SLA+W OK ACK
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20: // SLA+W no ACK
    Serial.println("SLA+W no ACK");
     break;
    case 0x28: // data OK ACK
    Serial.println("data OK ACK");
     break;
    case 0x30: // data OK no ACK
    Serial.println("data OK no ACK");
     break;
    case 0x38: // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;
     default:
     Serial.println("Error");
    break;
  }
}

Can you tell us exactly what I/O expander device you are using? If you could provide a link to the documentation that would be great!

https://www.picclickimg.com/d/l400/pict/181805816595_/1pc-of-PCF8574-IO-Expansion-Board-I-O-Expander.jpg Thank you so much for reply,

I solved the problem :)

Can you post the solution as an answer and accept the answer then, it might help people that have a similar issue in the future.

Of course, but can I post it as an answer?

OK the answer is that I didn't send the correct address!
Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C_TWSR_Check();.
I did this code for Master transmitter and receiver only.
So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.
For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
uint8_t I2C_rx(void);
void I2C_TWSR_Check(void);

uint8_t bitmask;

/////////// I2C modules addresses ////////////
// 8-bit I/O expander 0x20
#define IOEXP_WR  0x40    // I/O 8-bits expander address
#define IOEXP_RD  0x41

// LCD1602 adapter
#define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
#define LCD1602_RD  0x4F

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
}

void loop() {

  I2C_start(LCD1602_WR);
  I2C_TWSR_Check();
  I2C_tx(0xff);
  I2C_TWSR_Check();
  I2C_stop();
  _delay_ms(500);

  I2C_start(LCD1602_WR);
  I2C_tx(0x00);
  I2C_stop();
  _delay_ms(500);
}

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}

Question titles on SE sites should not be edited to indicate that a problem has been solved, rather the answer providing the solution should be marked accepted - even when as in this case it is your own.

I thought it's better to declare to the viewer that the problem for this topic is solved and so anyone who is browsing for a certain point on Google would see that it's solved.

The procedure for that on SE sites is accepting an answer, not editing the title.  So accept your own answer - only that will cause the system to consider it resolved and stop churning it back up as if it needs further attention.

"and stop churning it back up as if it needs further attention", what does this mean? Not so clear to me :) sorry.

Just click the hollow check mark beside your answer so we can be done with this.


text:
LED series Resistor- Noob question
Can someone please explain to me, like I'm 5, why this circuit does not work?

Every resistance calculator I use says that there is not enough voltage to calculate a resistance. If I understand correctly, wouldn't the LEDs light but just at a lower brightness?
Using R = V/I, The source voltage is 5v, the LED voltage is 6 divided by the current of 20mA equals -50ohms. All of the charge is used up by the time it reaches the arduino right?

The simple reason is that LEDs are not light bulbs. An LED is not a passive device and does not follow Ohms law.
To a first approximation if the voltage across an LED is below the forward voltage then no current will flow. In that situation the voltage across the LED pins is whatever the supply voltage is.
If the voltage across an LED is over the forward voltage then an unlimited current can flow and the voltage between the pins is fixed at the forward voltage.
This approximation isn't perfect but 90% of the time it's good enough.
So with 1 LED and no resistor you get 3V over the LED and then 2V left over with zero resistance, I=V/R = 2/0 = infinite current flow. The LED is dissipating 3*infinity watts of energy and instantly vaporizes. Clearly this isn't exactly what happens in the real world but the result is enough to tell you that bad things will happen.
With 1 LED and a 200 ohm resistor you get 3V over the LED and then 2V extra with 200 ohms resistance, I=V/R = 2/200 = 10mA. The LED is within its operating current and will light up.
With 2 LEDs and no resistor you get 3V on one LED and 2 V on the second (or 2.5 on both if you prefer). Either one or both LEDs are below their forward voltage and so no current flows. The LEDs remain off.

The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.
Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)
Read this: https://www.baldengineer.com/led-basics.html :

Forward Voltage
The Forward Voltage defines the amount of voltage
required in order to conduct electricity. Any voltages below this
amount will cause the LED to remain “Open” and non-conductive. This
also means any components in-series with the LED will not have current
flowing through them either! Once the voltage dropped across the LED
reaches the Forward Voltage, it will begin to conduct electricity. Not
only that, but the LED will only drop its Forward Voltage at any given
time.
For example, consider a LED with a Forward Voltage rated at 3.0V. Now
what happens if you attach the Anode to the Positive (+) Terminal of a
AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will
the LED do anything? No! The AA (LR-6) Battery only has a nominal
voltage of 1.5V. Until you add a second battery, the LED will not
light up.

LEDs won't necessarily light at lower brightness (or conform to Ohm's law at all), it's explained here. If an appliance apparently does provide a "dim" LED mode, it's usually using a clocked signal (and blinking rapidly).

I understand, thank you for the link. If i run on this configuration, would it damage my LEDs or Arduino?

Probably not, as the other Andrew noted above, no current will flow.

Can someone please explain to

With the right leds, the circuit can work.
Where it may fail:

Two less with combined forward voltage greater than the one applied to them. The meds wouldnt light up or wouldn't light up brightly, depending on the leds used.
The two leds with combined forward voltage much less than the supply which has low output resistance. The two leds may light up very brightly, or so briefly ending up in led heaven permanently. If you can capture them in high frame rate code on the glow before their death is quite pretty.


text:
Should I use OOP?
I am a long time participant in a competition called Robocup Rescue Line. For next year's competition, I am building a robot (and the code for the robot) from the ground up. The tasks that the robot has to do are complex enough for the code to be a fairly complex thing. I have some experience with classes and OOP so I thought I could try to organize the code in a OOP fashion. I thought I could have a class for each type of Sensor (e.g: LineSensor(), RGBSensor UltraSound()...) and another for the Motors (e.g: Motor()) that would have two instances on the code. Basically, all the code has to do is take sensor readings and produce a motor response. With this class structure, where would I do this correspondence? Is this not appropriate for this kind of project? Is there a better way to do this, that is still OOP?

I have a lot of experience with OOP, but mostly in embedded/pure software designs. However, I'm sure you can use it in a robot project too.
Avoid creating lots of objects dynamically, this results in gap in the very small memory available for the Uno. Try to create the object instances beforehand (this will also benefit performance hits during execution, by placing it into the initialization).
About the Sensors: you can make a baseclass if needed (Sensor) and let other classes derive from it (there is a small performance hit when calling methods though).
For the controlling:

Put sensor readings in the sensor classes
Put motor responses in the motor classes
Put the control in a special class (Control?) that couples the sensor response to the motor response.


text:
Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board
Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look here. But here the example is for testing small LEDs bulbs.
I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.
Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

You can edit it. I just need proper guidance for it and a few good suggestions.

Just replace the led/resistor with a relay... repeat as necessary

Actually am new to arduino. So, Kindly Can You Please tell me with example of 1 relay how to connect it with this bread board properly (just tell me with any 1 relay)

If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.
Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/

I would strongly recommend ULN2803. They are designed to drive inductive load (motors, relays and so on). And they are so easy to use. For beginners they are best choice.

What about using an I2C I/O expander like MAX7328 or equal and a ULN28XX as relay driver. and you can connect several I/O expanders to the same I2C buss with different addresses.
This will use minimal amount of pins and minimal amount of components.


text:
Is the use of malloc() and free() necessary in my Kalman noise Filter function?
I had a code that implements Kalman noise filtering on Arduino, and there is a use of malloc() and free(). I'm wondering if this will affect the Arduino or not (for example, the program will not function as I wanted, ...).
This is because when I got all raw (unfiltered) data and wrote the same Kalman Noise Filter function on Matlab, the filtering works well. However, when I write this FKalman function directly in Arduino, it doesn't work like it did on Matlab.
The Kalman Noise Filter is based on this article: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/
Here is the code (just have a look at the function Fkalman and the tick, ignore the other parts):
#define START_MSG

#define NBDATASEND 6
#define NBBYTE2SEND (2*NBDATASEND)

char StartMessage[] = "START";
char StopMessage[] = "STOP";
uint8_t byteRead;
uint8_t StartAsked = 0;
uint8_t StopAsked = 0;
unsigned long previous = 0;
int mod_11k = 12;
int mod_17k = 13;
uint8_t Header = 174;
uint8_t tab_1[NBBYTE2SEND]={0,0,0,0,0,0,0,0,0,0,0,0};
uint16_t data_toSend[NBDATASEND]={0,0,0,0,0,0};

float P1[4];float P2[4];float P3[4]; float P4[4];float P5[4];float P6[4];
float xprec1[2];float xprec2[2];float xprec3[2];float xprec4[2];float xprec5[2];float xprec6[2];
float *sol1;float *sol2;float *sol3; float *sol4;float *sol5;float *sol6;
float Te;
float Tbeg;

void setup() {
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  digitalWrite(mod_11k,LOW);
  digitalWrite(mod_17k,LOW);
  //Start serial port with Gumstix
  Serial1.begin(115200);

//Initialize KF
 P1[0] = 0.05; P1[1] =0; P1[2] =0; P1[3] = 0.05;
 P2[0] = 0.05; P2[1] =0; P2[2] =0; P2[3] = 0.05;
 P3[0] = 0.05; P3[1] =0; P3[2] =0; P3[3] = 0.05;
 P4[0] = 0.05; P4[1] =0; P4[2] =0; P4[3] = 0.05;
 P5[0] = 0.05; P5[1] =0; P5[2] =0; P5[3] = 0.05;
 P6[0] = 0.05; P6[1] =0; P6[2] =0; P6[3] = 0.05;
 xprec1[0] =0; xprec1[1] =0;
 xprec2[0] =0; xprec2[1] =0;
 xprec3[0] =0; xprec3[1] =0;
 xprec4[0] =0; xprec4[1] =0;
 xprec5[0] =0; xprec5[1] =0;
 xprec6[0] =0; xprec6[1] =0;

  //Wait for start message
#ifdef START_MSG
  //Waiting START message to begin
  StartAsked = 0;
  while (StartAsked == 0)
  {
    if (Serial1.available() >= strlen(StartMessage))        //?????
    {
      //Serial.write("Bytes available");
      // verifiy that the received stream is well the start stream
      for (i = 0; i < strlen(StartMessage); i++)
      {
        byteRead = Serial1.read();
        if ((uint8_t)StartMessage[i] == byteRead)
        {
          StartAsked = 1;
        }
       // Serial.println(byteRead);
      }
    }
    delay(1);
  }
  Serial1.write("START");
  //Serial.write("START");
#endif

//KF first time
    Tbeg = millis();
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    xprec1[0] = data_toSend[0];
    xprec2[0] = data_toSend[1];
    xprec3[0] = data_toSend[2];
    xprec4[0] = data_toSend[3];
    xprec5[0] = data_toSend[4];
    xprec6[0] = data_toSend[5];
    Te = (millis() - Tbeg)/1000;
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();
}

void loop()
{
    tick();
}

void tick() {
    //Previous value for filtering
    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];
    P4[0] =sol4[2]; P4[1] =sol4[3]; P4[2] =sol4[4]; P4[3] =sol4[5];
    P5[0] =sol5[2]; P5[1] =sol5[3]; P5[2] =sol5[4]; P5[3] =sol5[5];
    P6[0] =sol6[2]; P6[1] =sol6[3]; P6[2] =sol6[4]; P6[3] =sol6[5];
    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];
    xprec4[0] =sol4[0]; xprec4[1] =sol4[1];
    xprec5[0] =sol5[0]; xprec5[1] =sol5[1];
    xprec6[0] =sol6[0]; xprec6[1] =sol6[1];

    free(sol1);
    free(sol2);
    free(sol3);
    free(sol4);
    free(sol5);
    free(sol6);

    //Get data
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    Te = (millis() - Tbeg)/1000;

    //Filter
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();

    data_toSend[0] = sol1[0];
    data_toSend[1] = sol2[0];
    data_toSend[2] = sol3[0];
    data_toSend[3] = sol4[0];
    data_toSend[4] = sol5[0];
    data_toSend[5] = sol6[0];

    //Send data
    Codage(data_toSend,tab_1);
    HeaderSendnUInt8_RS232(tab_1,NBBYTE2SEND,Header);
}

void Codage(int16_t *d_send, uint8_t *tab_Send)
{
    int i;
    for(i=0; i<NBDATASEND ;i++)
    {
       d_send[i]=d_send[i]+8192;
       tab_Send[2*i]= (uint8_t) ((d_send[i] & 127));              //lấy 7 bit đầu
       tab_Send[2*i+1]= (uint8_t) ((d_send[i] & 16256)>>7);       //lấy 7 bit sau
    }
}

uint8_t HeaderSendnUInt8_RS232(uint8_t *ToSend, uint8_t NbToSend, uint8_t Header)
{
    Serial1.write(&Header,1);         //Header đâu phải pointer??
    return(Serial1.write((const uint8_t*)ToSend, NbToSend));
}

float *Fkalman(float xprec[2],float ymes,float P[4],float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = 0.05;
    int r = 100;

    //x prediction
    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];

    //P_pred = F.P.F'+Q
    Ppred[0] = q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q+ P[3];

    //Kf = (P_pred.C').inv(C.P_pred.C'+R)
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    //X_est
    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);

    //P_est = (I-Kf*C)*P_pred
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

If you find any problem related to the Fkalman function or my loop function, please tell me. Thank you!!

It's not recommended, however you're only working with small amounts, and the same amount each time (6 floats per "sol" and 6 "sols", so 36 floats, or 144 bytes). Since it's always the same amount I would expect the same block of memory to be allocated each time.
Personally I would use local array variables in the calling function and pass them as a parameter to the function(s) that manipulate them, rather than returning a pointer to an allocated array.
float sol1[6];
Fkalman(xprec1,data_toSend[0],P1,Te,sol1);

....

void Fkalman(float xprec[2],float ymes,float P[4],float Te, float *sol){

etc.
However I can't see it causing an issue, so if you would clarify "doesn't work as well" we may be able to point you in a better direction.

As Majenko already explained it is only 144 bytes. You can use local variables as he proposes.
If you need to keep the values over multiple calls to the Fkalman function, create the space as a variable of an array for each of the calls (if the function is called a fixed number of times).
Besides this, malloc cost some time and for performance reasons it is better to do this during start up once, so the loop function is not hindered by mallocs and free.


text:
Multiple SPI reads slows down read time dramatically
I have a two channel 24bit ADC(LTC2402- http://cds.linear.com/docs/en/datasheet/24012f.pdf) that I am communicating with via Arduino Leonardo(Leonardo because it was free!). If I attempt to do multiple reads the SPI becomes very slow while if I do a single read the time to send is what is expected. I have have integrated with python and timed the different transactions. A single read takes around 170ms( this is for both channels and the datasheet of the ADC indicates about 65ms per conversion(table 3 arduino as external sck etc.)) BUT if I do 5 reads the time taken is about 1.5s(expected about 0.65s) 10 reads take about 3s and 20 about 6.5s. Doing no ADC conversions and just serial comm to python is less than 2ms.
The relevant python code is as follows:
def getdata(ser,code):#ser is the arduino that has been connected, code is for writting to arduino
    ser.write(code)
    ch0=float(ser.readline().decode()[:-2])
    ch1=float(ser.readline().decode()[:-2])
    return ch0,ch1

code='1'
code=code.encode()

a=datetime.datetime.now()
ch0,ch1=getdata(ser,code)
b=datetime.datetime.now()
print(b-a)

The arduino code is as follows. The code has been simplified to just the necessary byte reads from the ADC, all other code has been removed to ensure the delays are coming from the SPI.transfer(0x00). The full code retrieves 4 bytes per channel and converts this to voltage and returns these values.
#include <SPI.h>

const int ltcs = 3; //active low ADC enable

float ch0=0.0;
float ch1=0.0;
byte b0;

void setup() {
SPI.begin();
SPI.beginTransaction(SPISettings(200000, MSBFIRST, SPI_MODE0));

Serial.begin(9600); // set the baud rate

pinMode(ltcs, OUTPUT);
digitalWrite(ltcs, LOW);
}

void loop() {
if(Serial.available()){

   int data = Serial.read() - '0';
   if(data>0){

   getdata2(ch0,ch1);
    //getdata2(ch0,ch1); //run multiple getdata2 to test multiple conversions
   //getdata2(ch0,ch1);
    //getdata2(ch0,ch1);
   //getdata2(ch0,ch1);

    Serial.println(0.2);
    Serial.println(0.4);

  }
  }
  }

 void getdata2(float &ch0, float &ch1) {
   ch0 = 0.0;
   ch1 = 0.0;

   for (int i = 0; i < 2; i++) { //Do twice to retrieve both Channels
     while (digitalRead(MISO) == HIGH) {
     }

       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
   }
   }

Can anyone help me? I have tried different SPISettings with no change. Interestingly I also find that the Baud rate does not change either.
Thanks for the help if any

Why are you reading from MISO? Why are you ignoring b0? You don't seem to be changing ch except to set it to zero. I don't see what getdata2 achieves except to slow things down.

The time isn't increasing exponentially. 5 reads take 1.5s, 10 reads take 3s and 20 reads takes 6s. That's a linear increase.

@NickGammon - Hi, MISO is just to see when data is ready. I'm only ignoring b0 for the example code. The actual code reads byte by byte and reconstructs to the 24bit which is then translated to voltage. In the actual code ch is the translated voltage as a float. So in short getdata2 is the function that recieves 4 bytes from the ADC and translates to voltage. I may have been a little dramatic by saying the time increases exponentially but it does double after a few reads. Hope that clears it up

@NickGammon- The Code I included here was to ensure that no other code was causing delays. This is the bare minimum needed to receive data from the ADC

I can only see one call to getdata2 call in the above code. Can you please show the actual code that is slow?

Try removing all references to serial comms. Just call getdata2 in a loop, and toggle an LED each time it finishes. That will demonstrate whether the issue is with SPI or the way you are communicating with your PC.

@NickGammon, did you not see the commented out calls to getdata2? It's as simple as calling getdata2 multiple times... I used this exact code and timed for each added getdata2 call

@NickGammon, I did something similar I commented all the b0=SPI.transfers but left the serial comm and wait for MOSI etc and that completed in under 2ms.

Why do you have a loop of 2 iterations when reading the ADC? Why the delayMicroseconds(1)? After doing while (digitalRead(MISO) == HIGH) { } you hardly need to test if MISO is LOW, right? What else would it be?

@NickGammon- loop is to read both channels @ 4 bytes each. BUT you're right, no need for the delay and test MISO LOW but they have no effect on time. The delay was there initially to see if a short delay would prevent the much longer one which it didn't.

MISO will be changing rapidly. A second test will not be helpful. digitalRead is quite slow. You might be better off connecting SDO (MISO) to an interrupt pin, if you want to know when the conversion is ready. Even your while loop (with digitalRead inside it) will probably execute too slowly.

Interestingly I also find that the Baud rate does not change either. - on the Leonardo serial comms goes through the USB interface, and changing the baud rate in the sketch does not affect the output rate.

@NickGammon- I tested the MISO response by running getdata2 multiple times but commented out all b0=SPI.transfer() and even if I run 5 or more times the time to complete is <2ms. So the delay is not due to the digitalRead or the while loop.

There is no way that SPI.transfer() can slow down. It's impossible. Do what I suggested and remove all serial comms.

@NickGammon- Sorry Solved it. It wasn't a software issue after all... It was me being dumb and incorrectly assuming the external oscillator frequency. Thanks for the time and effort though.

I found the error. Unfortunately I was so busy blaming the code and assuming it was my lack of arduino knowledge that I forgot to check the hardware specs. I thought I was using the maximum external oscillator frequency(f_EOSC) of 300KHz, but in fact was using the 50Hz internal oscillator frequency with an external f_sck from the arduino. This means that the conversions where in fact running at expected times. The thing that threw me off was that the first reading was much faster than the rest. This was most likely because at first read I only had to wait for one channel conversion as the other was already done before I request the data and so the first readings wait time is only as long as a single channels conversion. I would need to implement a 300KHz external clk if I want faster conversion speeds. Thanks for the help for those who tried:)

You probably want to take a look at the datasheet and work on one routine that returns adc results from a channel selected by the user. The typical process is to read the register until EOC is asserted (_EOC is low).
and you would go from there.

@dannyf- Can you please elaborate? I have the ADC correctly returning values so I am unsure what you're referring to. It's literally just the timing.

@dannyf- Nevermind. I solved it. I was actually already doing what you suggested. The /EOC is implement on the SDO/MISO channel just before data conversion. Thanks though.


text:
Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?
I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as vim). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that vim and other packages have disappeared, as well as my Python code.
Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?

After upgrading the firmware and rebooting:

Log in to your Yun through your browser and use the LuCI interface.
Navigate to "System" > "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)


text:
Problems adding ESP8266 wifi board
I just received an ESP8266 wifi module and I am trying to add the board. However I am having an issue. All websites/tutorials say to use http://arduino.esp8266.com/stable/package_esp8266com_index.json, however nothing is there. Can it be found somewhere else?

Can you please add more information to your question.

I am mirroring (eventually when the uploads finish) most of the files here: http://majenko.co.uk/esp8266

It looks like the server is down.  Isitdownrightnow reports that it's been down for almost 4 days: http://www.isitdownrightnow.com/arduino.esp8266.com.html
There is a discussion about it over on the ESP8266 forums: http://www.esp8266.com/viewtopic.php?f=26&t=3134&start=8
Let's hope it will be back again soon.


text:
Two devices on one UART/Serial
I'm using an Arduino Mega which has 4 RX/TX UARTS/serials.
3 RX's of them I use for MIDI In
2 TX's of them I use for MIDI Out (maybe later a DMX out too)
One I use currently for debugging. On the other hand, in the future I want:

Using an ESP8266 WIFI which also seems to use an UART (both RX/TX)

Of course I can remove the debugging RX/TX, but maybe some more additions are needed and for the first RX/TX I need to remove the RX each time I upload (so I rather leave it for debugging).
I was wondering, is it possible to share an UART if I don't use the WIFI module and MIDI port at the same time?

It's certainly possible to multiplex a UART port, yes, though you will need extra hardware to do it. You will need:

A multiplexer to select between the two RX lines and feed the right one to the Arduino's RX pin
A demultiplexer to select which of the devices to send the Arduino's TX pin to.

"Analog" (de)multiplexers (e.g., CD4052) may be the simplest option since they can work in both directions. Another alternative would be combinations of tri-state buffers and glue logic to control them.

You could simply send the TX to both devices. If one is always going to be missing it doesn't matter what the data line to it is doing. Rx it depends whether these are TTL level signals or not. If they are TTL straight from the devices and one one device is ever fitted you can wire them together. As soon as you have a level shiftier or buffer on the signal then you need a Mux.

If there is only one physical device connected at a time then yes you can just wire direct.

I don't know if e.g. a WIFI ESP8226 is considered as physically connected (I guess it is) ... the MIDI cable is not, but I rather don't want to be rely on a user having to remove the cable (also the MIDI in is transferred through an opto coupler which is physically connected to an RX pin).
However, it's ok to know there is a solution (for now). I just don't want to think further into a direction that is absolutely impossible from the start.
(background: now I use or plan to use an SD card to move from a PC from the Arduino every time, but later a WIFI module is more convenient).

If your application can tolerate the limitations of SoftwareSerial, it's the easiest way to add a port. The terminal may be the better candidate for it.

SoftwareSerial is the absolute worst alternative.  It disables interrupts for an entire character time (1ms @ 9600) when transmitting OR receiving (it can't do both at the same time, either).  If the baud rates don't match, this would cause all the other UARTS to lose characters.  If he must use a software serial port (not that I suggest that), use AltSoftSerial instead!

The original SoftwareSerial hasn't been in the core library for quite some time. Since v1.0, SoftwareSerial has been replaced by http://arduiniana.org/libraries/newsoftserial/ which addresses some, if not all, of those shortcomings. The different software implementations come with their ownabilities and limitations (AltSS is tied to fixed pins, f/ex). And do note that I alluded to the limitations of software implementations.

Nope.  Those are the current problems.  Look at the SoftwareSerial::recv method, which is called from the ISR: it has a for loop.  The ::write method is very similar.  :(

I am not a favorite for using SoftwareSerial, only for debugging it might be 'acceptable', but in that case I probably rather try to wire another Arduino only for that purpose.

Consider running the RX and TX of the first UART to the common terminals of an On-Off-On DPDT switch or relay.  Calling the On positions A and B, connect the A terminals to RX and TX of one device, and the B terminals to RX and TX of another device.  Use position A for the first device,  position B for the second device, and the Off position for program loading.
It isn't clear to me whether your debugging is via USB serial or via a separate device. In the former case, a DPST switch would be adequate.  Also, two SPDT's could be used in place of a DPDT if you wish to switch RX and TX separately, or four SPST switches can be used if you have nothing better.
This is premised on the idea that during development you need to be able to send/receive debugging IO.  I don't know how to interpret your
“don't want to be rely on a user having to remove the cable”  phrase, but suppose a user-cabled setup won't need debug-channel switching.

This should be possible (at least for two of the UARTs, since I need the other exclusively and simultaneously). I am debugging it now via the USB serial (but afaik, I have to keep that RX/TX free, at least while downloading, maybe nothing to do with debugging). And the SPDT/DPDT could be used for two UART 'inputs'.  And I mean with user in this case myself (as the debugger). Sorry for being unclear,