text:
Where can I storage a local database?
I want to create a website where the users can have their own database. An example:
- An user will receive some data from HTTP POST and I want to storage all the information into a local database to access to it. For example, the URL that the user has visited in the last month.
I know that the best option will be to create a database in my server and put each user in it, but it will be very long database and the information between users is not shared, therefore it will be more secure using a local database, but I don´t know if that can be done.
My project is about ESP8266 and uploading data to a server, so this can be done using a microcontroller instead the computer. I have seen the raspberry to use it as a server and storage there the database, but it is so expensive. Can be done using another board as Arduino, Texas Instruments, etc...
The main aim is to create a main hub to storage all the values received from the ESP8266 and then share over internet, but I don´t know how to build a hub where I can store a database inside and a HTML website to show the values. Any ideas? I would like to avoid a computer to do it.
I think in something for less than 10 GBP, because I bought and Arduino and Ethernet shield for 5 GBP both, fake version, but useful for my project

You want a database but to avoid using a computer? I sense you will have problems with that.

Yes, for example can be used raspberry. And for Ardingly I know that can be done a HTML page host using ethernet shield, but I'm not sure if can be done a proper server.

You can use the Sparkfun data project:
https://data.sparkfun.com/
they build an open source tool called phant (https://github.com/sparkfun/phant) that you use to host on your own or use their free version online

As I understand the question, you want a 'mini' database for your ESP8266, without the need to connect to the internet.
One way I can think of is that you could use your ESP8266 flash memory to store the database. Use SPIFFS with, say, 1 MBytes flash size, leaving 3 MBytes for your actual program (assuming the ESP8266 has 4 MB flash memory). More than 20 thousand record files for 50 bytes each.
But you'll need to write your own create, read, update, delete (CRUD) function to handle the files.
If someone has already written such functions, that would be useful to share here.


text:
Sending AT commands to a gprs shield using serial port
I have a GPRS shield connected to an arduino uno board, i want to use the shield to send sms and do phone calls, from a C# Wpf application, the arduino is connected to the application using the serial port,
In order to do that I've upload the following sketch to the arduino board:
#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);
unsigned char buffer[64]; // buffer array for data recieve over serial port
int count=0;     // counter for buffer array
void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);             // the Serial port of Arduino baud rate.
}

void loop()
{
  if (GPRS.available())              // if date is comming from softwareserial port ==> data is comming from gprs shield
  {
    while(GPRS.available())          // reading data into char array
    {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
    clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
    count = 0;                       // set counter of while loop to zero
  }
  if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
    GPRS.write(Serial.read());       // write it to the GPRS shield
}
void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<count;i++)
    { buffer[i]=NULL;}
}

every thing works perfectly when sending AT commands to the shield using the Serial Monitor, for example to dial a call this is all what i need to do

this works perfectly, but when trying to do the same thing from c# application, nothing happened !
here how i send the AT command from the code :
private readonly SerialPort _serialPort;
public void Callphone(string number)
{
    _serialPort.Open();
    _serialPort.Write("ATD + +" + number +";");
    Thread.Sleep(100);
    _serialPort.Close();
}

PS: sending sms works fine from the serial port, using the same way :
 public void SendSms(string number, string message)
    {
        _serialPort.Open();
        _serialPort.Write("AT+CMGF=1\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CSCA=\"" + MessageCenterNumber + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CMGS=\"" + number + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write(message + "\x1A");

        Thread.Sleep(SleepTimeStamp);
        _serialPort.Close();
    }

Am i missing something ?

I dont't know much about C# but I have some ideas. And as noone answered. Let's try! ;-) 1st) I saw that you append \r in the working example. But you did not in Callphone.  2nd) what is the content of your number string? Is is prepended with a +? Then you write ATD + ++<number> to the shield. 3rd) In the working example you send a lot of text compared to the Callphone. Perhaps you have to flush the buffer.

Let the arduino send your string to your terminal and verify that it's 100% right. Much like a loopback.
(Also, you don't really need an arduino inbetween?)

Thank you guys for your time, @Peter Paul Kiefer I've tried all you suggestions 1) adding the \r didn't solve the problem, 2)I've verified on debug mode no extra '+' is sent, I've even tried sending "ATD + +213698629552" directly without using  a param, 3) each time the buffer is flushed, and i am also triggering the call only (no sms send code is executed first ), Thanks again and do you have anything else i can try ?

@FuaZe He uses an arduino shield, so I think the arduino is nessecary ;-)! It's a good Idea to echo the sended command, to see if a part of the command would be removed. @SamTheDev When you send the ATD command directly without a parameter, did you forget the ; at the end in your code too or is it just a typo in you comment? Another idea: When you communicated with the shield using the arduino terminal,  you send a single AT command at first. Did you do that in your C# program too? I don't know If it is nessecary but it's the only difference I see.

Using an UART-USB cable/chip you can send commands directly to and from the GSM module. Though you will have to power it with an external supply (which you always should). Doing so will enable you to play around with the different AT commands and responses before you're programming it out (so that the arduino will send those).

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:
Keyboard.print() skips keys
I'm playing with the Arduino Leonardo Keyboard.print() command, but I'm facing a annoying problem:
When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):
Keyboard.print("echo \"This is a demo\"");

Output:
echo his is a demo

And when I use this line:
Keyboard.print("echo -This is \"a demo-");

Output (note the umlaut over the a instead of getting "a):
echo 'This is ä demo'

I suspect that the problem is that my computer is configured to use Spanish layout.
What source code file can I change to fix this? I can't find the defines used by Keyboard.print()

In your particular case, the double quote is to be entered (using the Spanish keyboard layout) by Shift + the physical key labelled 2. On a US keyboard, Shift + the physical key labelled 2 is "@".
Thus, this simply will get the desired result (the Arduino library assumes a US keyboard layout):
Keyboard.print("echo @This is a demo@");

More general solution
More generally, strings can be encoded as in the following table (the exact mappings depend on the particular keyboard layout - this will work for many European keyboard layouts).
If the physical key (and modifier key, if any) exists on the US keyboard to get the character typed out using the non-US keyboard layout, then this method works fine.
To get   Use   Notes
--------------------------------------------
;        <     Will result in Shift action
:        >     Will result in Shift action
(        *     Will result in Shift action
)        (     Will result in Shift action
/        &     Will result in Shift action
?        _     Will result in Shift action
=        )     Will result in Shift action
&        ^     Will result in Shift action

-        /
+        -
_        ?

"        @     Will result in Shift action

,        ,     The same
.        .     The same
#        #     The same

Even more general solution
Even more generally, some keys are not on the US keyboard (e.g. the 102th key on European keyboards for the original PC keyboards, often with <, >, \, and |), and it is not possible to use Keyboard.print().
Instead, use the low-level HID().SendReport() function - with code 100 (decimal) for the first parameter for the 102th key. See the library source code, Keyboard.cpp (/libraries/Keyboard/src/Keyboard.cpp), for how to use HID().SendReport().
Alternative solution
Some operating systems enable entering characters using the keyboard and a numeric code.
This is at the expense of making it operating-system dependent (but making it independent of the active keyboard layout).
For example, Ctrl + Shift + U on Linux (GUI only, dependent on the window manager(?)). For the particular problem (the Unicode code point for " is 0022), without any functional abstraction to reduce the redundancy:
Keyboard.print("echo ");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

Keyboard.print("This is a demo");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

Unicode code points can be found at unicode-table.com.
Media keys
Even though the media keys are listed in the table (e.g. code 128 for "Volume Up" on page 53), they do not work using the method described in the previous section. But there is a solution.
Platform
This was tested with:

Arduino Leonardo
The Spanish keyboard layout was added to the Linux settings and activated. There were 14 different ones to choose from, but I used the one labelled "Spanish". It was verified that "@" actually resulted in an output of """. It was also verified that the Ctrl + Shift + U method worked.
Linux, Ubuntu 19.10 (Eoan Ermine), but with the buggy GNOME replaced by Cinnamon.
The Arduino Leonardo connected to an extra current port of a D-Link USB hub (necessary, for unknown reasons - probably a local problem)
Arduino IDE v. 1.18.10

I know this because I have implemented it for a macro keyboard where the keyboard layout is (usually) Danish in the operating system (Windows or Linux).

Excellent answer!

(Code 128 for "Volume Up" is on page 56, not 53.)

(For a future update: The first link doesn't actually show the double quote will be entered by Shift + 2. It ought to be replaced by something better. For example, this one.)

(For a future update: Both "#" and "?" will also result in a Shift action (Shift + 3 and "/", respectively). And consider using Markdown tables, if available. 102th → 102nd (?).)

(For a future update: The leading zeros in "0022" may not be necessary. It wasn't necessary in GNOME.)

(For a future update: For the Unicode code input: Instead of Return at the end, an alternative it to keep holding Ctrl  and Shift down (releasing them at the end))

The Arduino assumes a US keyboard layout.  The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys.  Instead the send a scan code that defines where on the keyboard the key is.  It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.
Some special keys are known as dead keys.  These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.
Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.
So there are two things you can do to "fix" it:

Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file HID.cpp in the Arduino core (hardware\avr\cores\arduino or somewhere like that - I forget off hand) and is the _asciimap array.  It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including modifier keys like Shift.  You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list.  For instance, the character " is listed as:
0x34|SHIFT,    // "

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier.  You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.

+35: Thank you very much! When I find the exact file location I'll tell you it!

In my computer is located in /usr/share/arduino/hardware/arduino/cores/arduino/HID.cpp. I'll try to override these mappings with some custom ones.

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


text:
Compilling error not highlighting line in code
A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.

Because the Arduino "IDE" is a mere toy. If you want real IDE facilities then you need to use a real IDE, not the sub-par text editor that is the Arduino IDE.

I would also recommend to stop relying on that sort of hints. If you read the error message, you will find out that gcc not only tells you where it encounters the error, it also tells you why there is an error.

Update your IDE version to 1.6.x . That should fix your issue.

The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.
See my post about How the IDE organizes things.
The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.
In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.


text:
Using 2 RGB lights over Bluetooth with a DigiSpark
I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)
Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.)
The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module.
So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream?

The function of this device is to display warning signals from a web server nearby. These warning signals are color-coded and relate to two different domains on the server. One light per server. Per server there are about 30 different errors, each with their own admin-defined color. Exact protocols are still under development since I first want to see the device working before I start on the related code. (I'm more a coder anyways.)

Which means, analog connections.

Nope. It means PWM.
How would you control the brightness of a single LED?
By generating a PWM signal with:

sufficiently high frequency to not be able to notice the flickering;
duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive.
Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.
Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.
If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: I2C 6-channels PWM generator.

PWM, not analog. Noted. I keep making that mistake. The calculations for the resistors won't be too complex. It doesn't have to be perfect either. The challenge is mostly finding the right part to use and to know how to use that part from the sketch.

To be fair, the Arduino library calls it Analog, but you do get an analog value only after passing through a low pass filter.  I linked what I think is the right part. Did you have a look at it? To know how to program it, you need to check its datasheet. Investing in a  Bus Pirate[1]  might be worth considering, to decouple the I2C programming with the PWM programming.  [1]: http://dangerousprototypes.com/docs/Bus_Pirate

Yes, I checked the part but I can't any distributor in Europe who sells these. Another challenge will be connecting it to my other hardware. Soldering is not my strongest point. Found a shop in my area that sells a Bus Pirate but it takes three weeks before it's back in stock. And that's the most annoying part: waiting for things to become available somewhere.

You can use the extra time practicing soldering ;-)

Well, I'm not in a hurry anyways. :) Plenty of other projects that I want to do first. Most of them coding-related but this project would have been nice to combine coding and electronics. :)


text:
Library, instantiation of a class object
I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.
I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.
However, I find that there are two forms that both seem to work for instantiating an object in the main program.
With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.
Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?
#include "Minimal_library.h"

// allocate buffer to be used
#define BUF_SIZE 40
char buff[BUF_SIZE+1];

// which of these two instantiation calls works?

// Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
...

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)

Should be equivalent. See https://en.wikipedia.org/wiki/Copy_elision

I'm sure that wikipedia article was relevant to those in the know, however I don't understand a word of it. Do you have anything that simplifies rather than complicates?

Put out of your head the idea that the Arduino IDE has some special syntax. It's just C++ which is very widely covered on the Web in tutorials. See my post about How the IDE organizes things - there is some pre-processing of sketches before they go to the C++ compiler, but apart from that, whatever works in C++ works on the Arduino (exceptions excepted because they are disallowed by a compile-time option).

The statement
Minimal_library obj(BUF_SIZE, buff);

means “create an object named obj, initialized by calling the class
constructor with the supplied parameters”.
On the other hand,
Minimal_library obj = Minimal_library(BUF_SIZE, buff);

means “create an unnamed object initialized as before, then copy it
into an object named obj, then delete the unnamed object”.
The compiler would normally optimize the second form into the first one.
It is even allowed to do so in some weird cases where they may not be
equivalent. In the end, it's mostly a matter of style. I prefer to do
the optimization myself and write the first form. But if you find the
second form more readable, go ahead: you can normally trust the compiler
to optimize out the unneeded copy.

Thanks, now I understand the copy_elision refernce. I guess it's just the syntax that seems less obvious than python, but partial knowledge is not always helpful. I might understand obj=MinLib(params) to be as you describe, with the leading MinLib taking the role of a cast, but that doesn't work for the first form. Could you link me to the simplest documentation that describes how storage in a class instance is organised. I expect header/public to be persistent attributes, and local on the stack, are header/private persistent by the instance? Can the class take variables like python?

@Neil_UK: I do not have such a reference, as I learned from a combination of books and online resources. public/private does not make a difference storage-wise, the whole object is stored as a single entity in static RAM (for a global or static local), on the heap (if you new it) or on the stack (for a non-static local). A member qualified as static in the class definition belongs to the class itself, not to any particular instance, and is stored in static RAM.


text:
(SOLVED more or less) Direct reading/writing to PORTD, unexpected readback, how does the serial library use it?
TL;DR When Serial is invoked on a rev3 Uno, the UART uses the Tx and Rx pins on PORTD regardless of what you try to do to PORTD I/O directly. The warnings on arduino.cc about avoid those bits appears to be wrong. Readbacks from PORTD on those pins reflects the last user input, not the state of those pins.  /TL;DR
I have extensive assembler (other platforms) and python experience, but no C and am still on the lowers lopes of the Arduino learning curve. I am using the Arduino/C IDE at the moment for simplicity, though I have a feeling that once I bite the bullet (not for this project if possible), I am going to find the direct AVR route suits my style more.
I'm developing a charliplexed LED driver application on Uno hardware which uses most of the I/O pins, so am having to use portD. I'm using direct writes to DDRD and PORTD rather than digitalWrite(), for a number of reasons not all related to speed.
I am aware of the use of pins 0 and 1 for serial comms, so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1, and DDRD &= Bxxxxxx11 when setting to 0.
I hadn't intended reading back the port, though I'm knee-deep in debug readbacks, so did it eventually. When I read back DDRD, it's Bxxxxxx00 every time. But my readbacks are working, so serial communication using the Serial.println(xx) format and the monitor in the IDE, continues to work.
I would have expected the Tx direction bit to be 1. Is it the case that the Serial library grabs the port when it needs to transmit, and then reverts it? So is it actually 0 when I read it, or am I reading wrongly, or I can't read it? As I expect DDRD &= Bxxx to work, I should be able to read it.
I'm comfortable working with the bare metal, where I have total control, and with python where it's all magic, but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.
Here's the code
const byte portD_1_mask = B11111100;
const byte portD_0_mask = B00000011;

#define DEBUG_LEN 20
char debug_str[DEBUG_LEN+1];
#include "debug_formats.h"

byte counter;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // send an intro:
  Serial.println("\n\ndebug portD demo:");
  Serial.println();
}

void loop()
  {
    counter += 3;
    Serial.println(counter);
    drive_LEDs(counter);
    delay(100);
  }

void drive_LEDs(int a)
{
    // create port programming variables, initialised to 0
    byte D_dir = 0;
    byte D_data = 0;

    // prepare bytes to be written to the ports
    // the anode gets driven by ORing into both data and direction
    D_dir |= 4;  // constant for this demo
    D_data |= 4;
    // the cathode(s) get driven by ORing into the direction only
    D_dir |= a;   // wave these around

    Serial.println("generated programming bytes");
    Serial.print("direction - data - ");
    debug_format(D_dir, D_data);
    Serial.println(debug_str);

    // finally write all pins to their new values
    // D port needs to pussyfoot around not changing the TxRx pins

    // reset D port 7-2 to all 0s
    PORTD &= portD_0_mask;
    // and then set the ones we've got in the 7-2 positions
    D_data &= portD_1_mask;
    PORTD |= D_data;

    // and the same for D direction
    // switch D 7-2 to inputs first
    DDRD &= portD_0_mask;
    // then set the outputs
    D_dir &= portD_1_mask;
    DDRD |= D_dir;

    // and see what we have written to port
    Serial.println("what the hardware has been set to");
    Serial.print("direction - data - ");
    D_dir = DDRD;
    D_data = PORTD;
    debug_format(D_dir, D_data);
    Serial.println(debug_str);
}

and the results it produces on the monitor
debug portD demo:

3
generated programming bytes
direction - data - 00000111..00000100..
what the hardware has been set to
direction - data - 00000100..00000100..
6
generated programming bytes
direction - data - 00000110..00000100..
what the hardware has been set to
direction - data - 00000100..00000100..
9
generated programming bytes
direction - data - 00001101..00000100..
what the hardware has been set to
direction - data - 00001100..00000100..
12
generated programming bytes
direction - data - 00001100..00000100..
what the hardware has been set to
direction - data - 00001100..00000100..

The hardware is doing what I'd expect, LEDs are flashing.
Now I'm not concerned that the 'generated programming bytes' have LSBs set and they don't appear in the readback, as I'm doing a data &= portD_1_mask which clears the LSBs before ORing into the port.
What I am questioning is the fact that the two LSBs on DDRD are always read back as 0. If the Serial library grabbed and kept those pins continuously, then I would expect the Tx pin to be an output, whenever I read it. But it's not reading back that way. So does that mean Serial only makes the Tx an output when it's transmitting, and then puts it back to input when not? Or is my read of the DDRD Tx bit not working for some reason, though it seems to be working for the other bits?
OK, so I've got the 'scope out, put a resistor network on the Tx pin so I can see whether it's high or low Z, and it stays low Z even when not transmitting, so the UART does 'retain' the port. This means the readback of the DDRD contents is a lie. Section 19.6 of the AVR doc 8161 does say the port pins are overridden by the UART, which this seems to confirm.
So if they are overridden, all this warning on the arduino.cc site tutorials about not stomping on the pins is incorrect. The following code bashes the bejaabers out of PORTD while using it to receive and send.
  int count;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // send an intro:
  Serial.println("\n\ndebug portD demo:");
  Serial.println();
}

// the loop function runs over and over again forever
void loop() {
  count += 1;
  if ((count&1)==0) DDRD = 0; else DDRD = 0xff;
  if ((count&2)==0) PORTD = 0; else PORTD = 0xff;

  PORTB = 0xff;
  byte dd = DDRD;
  byte pp = PORTD;
  Serial.println();
  Serial.println(count);
  Serial.println(dd);
  Serial.println(pp);
  PORTB = 0;
  delay(2000);

  if (Serial.available() > 0)
  {
    byte inByte = Serial.read();
    Serial.print("got >");
    Serial.println(inByte);
  }
}

and this fragment of output captured from the monitor shows it keeps working. I used a sufficiently long delay so I'd be able to hit all phases of the write to data and direction on PORTD.
9
255
0
got >49

10
0
255
got >114

11
255
255
got >99

12
0
0
got >115

13
255
0
got >115

Lessons
a) When Serial is in use, the UART hardware does override the Tx Rx pins, at least on a rev3 Uno.
b) It does hang on to the hardware between active transmissions
c) The warnings on arduino.cc tutorials about writes to PORTD and DDRD don't seem to be valid, it appears the hardware just ignores them
d) Reads back from PORTD and DDRD show what you last wrote in pins 0 and 1 when the UART is in use, not what's on the pins.

so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1 - how does that set anything to 1? Please post code that proves what you are saying. All this description stuff doesn't prove anything. Please post a Minimal, Complete, and Verifiable example

If your (unposted) code turns on Serial communication, the serial hardware takes over the functions of digital pins 0 and 1.

@NickGammon code posted.

The "Serial library" does nothing with the pins. The "Serial library" controls the UART peripheral which then controls the pins. When using the UART peripheral you have no control over the UART pins directly, and any use of DDR, PORT or DIN on those pins is essentially meaningless.

@Majenko I understood from the examples on the arduino.cc tutorials that it was possible to interfere with the UART's use of those pins, which is why I'm following the DDRD |= xxxxxx00 method of setting the high 6 pins' direction. Are you saying that that's not the case? I would have expected the first use of the Serial library to result in the 'capture' of those pins for the UART, which is why I'm questioning always reading both pins as input. Ultimately I have a method for using the D port and serial communication, I'm just trying to get my mental model to match documentation and HW.

Anything written on Arduino.cc should be taken with a shovel full of salt.

According to the ATmega328 datasheet, USART function seems independent of DDR of the TX and RX pins; that is probably what explains your observations.

I've just put a scope on the portD pin 1 Tx pin, with a weak pullup to 4v so I can tell the difference between driven and high Z. The pin stays low impedance, even when not transmitting, so it looks like the UART does retain the pin. The readback of 0 for the DDRD is therefore not reading what the output is doing. Section 19.6 of the AVR docs does say the TxDn pin is 'overridden' by the UART, rather than having to fight for it. I've just done the experiment where I stomp all over PORTD while using it for output. It still works, I'll post the results. Not tried input under those conditions

See the datasheet: 14.3.3 Alternate Functions of Port D

TXD/PCINT17 – Port D, Bit 1
  TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
  PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
RXD/PCINT16 – Port D, Bit 0
  RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still
  be controlled by the PORTD0 bit.
  PCINT16: Pin Change Interrupt source 16. The PD0 pin can serve as an external interrupt source.

So basically if you turn on the USART the pins are configured as input/output regardless of DDRD.

but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

It's not the IDE - it's the underlying hardware.

This means the readback of the DDRD contents is a lie.

No it isn't. The hardware is ignoring DDRD in those bits. See this example:
void setup()
{

DDRD = 0;
byte a = DDRD;
DDRD = 0xFF;
byte b = DDRD;

Serial.begin (115200);

DDRD = 0;
byte c = DDRD;
DDRD = 0xFF;
byte d = DDRD;
Serial.end ();

Serial.begin (115200);
Serial.print ("a = ");
Serial.println (a);
Serial.print ("b = ");
Serial.println (b);
Serial.print ("c = ");
Serial.println (c);
Serial.print ("d = ");
Serial.println (d);
}

void loop()
{
}

Output:
a = 0
b = 255
c = 0
d = 255

The code is setting DDRD and reading it back as set. However the hardware is ignoring those bits because of the alternative use of those ports.

Yes, thanks. My issues were 'what does 'turn on the USART' mean?' so is it 'on' only when transmitting, or is it 'on' from the time Serial.begin() is called, and it looks like the latter. The second was the warning claptrap in the tutorials on arduino.cc that tell you how to not to mess with those pins. It turns out the hardware 'magic under the hood' is quite strong enough to avoid the need to tell noobs anything about the shared use of those pins, and let them write regardless, as they won't upset Serial, just won't be able to use those pins. I'll find my way round the docs soon. Thanks.

The stuff on the Arduino reference is addressed at beginners. If you read the datasheets you can do what you want. Once the USART is enabled it will continue to take over those pins until it is disabled. (ie. Serial.end()).

In the tutorial, I would have thought that 'port D bits 0 and 1 are don't care, you can do what you like with them but they don't connect to the hardware I/O after a Serial.bgin()' was more accurate, and more noob friendly, than 'dont drive them, because if you do you'll trash your serial comms, and here's a fiddly |= way to avoid that', which is unnecessary, alarmist and wrong. Of course the total noob will stay with digitalWrite(pin_no). I wonder if the tutorials can be corrected, Majenko doesn't appear to like them!


text:
Graph plotting on Python using Tkinter Canvas
I'm trying to plot a graph with python using the canvas widget, I'm currently sending data in from an arduino sensor sketch ..does anyone have an idea on how I can plot this graph in real time on Python using canvas. I've read up on it but I'm having problems with unpacking the x , y and z axis data and looping it to updating in real time. Below is the arduino sketch.And also the skeleton of the Tkinter canvas sketch. Thanks!!
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup(){
    Serial.begin(115200);
    ski.begin(13, 12,11,10, A0, A1, A2);
    ski.setARefVoltage(3.3);
    ski.setSensitivity(HIGH);
    ski.calibrate();
}

void loop(){
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\nx: ");
    Serial.println(x);
    Serial.print("\ty: ");
    Serial.print(y);
    Serial.print("\tz: ");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}//End of Arduino Sketch

  from Tkinter import *
  import serial #import Serial Library
  import numpy as np # Import numpy

  ardoData = serial.Serial('COM4', 115200)
  accelX1 = []     #to hold the incoming axis data from the arduino
  accelY1 = []
  accelZ1 = []

  class GraphException(Exception):
      def __init__(self, string):
         Exception.__init__(self, string)

  class Smoking(Canvas):
     def __init__(self, master, FrameTitle, Col, Row, Height):
        Canvas.__init__(self, master)
          self.FrameTitle = FrameTitle
          self.x1Axis = range(1001)
          self.y1Axis = range(1001)
          self.z1Axis = range(1001)
          self.Line1 = range(1001)
          self.Line2 = range(1001)
          self.Line3 = range(1001)
          self.configure(height=Height, width=750, bg='grey', bd=3, relief=GROOVE)
         self.grid()
         self.grid_propagate(0)
         self.Col = Col
         self.Row = Row
         self.place(y=Col, x=Row)
         self.create_text(380, 20, text=self.FrameTitle, fill = 'black')
         for i in range(0, 1001):
            self.Line1[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='blue', width=0)
            self.Line2[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='red', width=0)
            self.Line3[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='yellow', width=0)

     def LiveValues(self,accelX1, accelY1, accelZ1, Centerline = False, Dritter = False):
          for x in range(1, 59):
             for i in np.arange(1, 1001, 1):
                  while(ardoData.inWaiting() == 0):
                      pass #do nothing
                  ardoString = ardoData.readline()
                  dataArray = ardoString.strip().strip('\n')   #Split into an array called dataArray and strip off any spaces
                # Ensure that you are not working on empty line
               if ardoString:
                   dataArray = ardoString.split(",")
               if len(dataArray) > 1:
                   self.x1Axis = int(dataArray[0])
                   self.y1Axis = int(dataArray[1])
                   self.z1Axis = int(dataArray[2])
                   accelX1.append(self.x1Axis)
                   accelY1.append(self.y1Axis)
                   accelZ1.append(self.z1Axis)
              for x in range(0, 1001):
                 self.coords(self.Line1[x], -10+(x*10), self.accelX1[x], (x*10), self.accelX1[x+1])
                 self.coords(self.Line2[x], -10+(x*10), self.accelY1[x], (x*10), self.accelY1[x+1])
                 self.coords(self.Line3[x], -10+(x*10), self.accelZ1[x], (x*10), self.accelZ1[x+1])

   # Create and run the GUI
   root = Tk()
   app = Smoking(root, "Smooth Sailing", 1000, 1000, 1000)
   app.mainloop()

So after working with the answer given on the post I ended up with a Line graph that is not reactive, I understand that I have to tweak the code to suit the range of values I am getting which is shown below. I increased the limit as indicated by @patthoyts but I still couldn't get either lines to show up on the canvas and to even be reactive ( what i mean by that is to respond to the movement of the sensor). Also, do bear with me Editors!, if I'm going about editing this question the wrong way, is just that I'm quite desperate to have this issue resolved. Does anyone have any clue as to how I could resolve this issue. Thanks PS: I added both images , that of my data stream and the image on the canvas.

You should show at least part of your python code. Really this is not about arduino but about plotting a graph from a stream of 3 decimal numbers, 1 per line, output every 10 ms. Create a canvas and put a line on it. Read 3 lines and parse the numbers then convert into canvas coords and update the line configuration coords property.

@patthoyts.....please do bear in mind THIS is a NEWBIE alert!!!!! I have limited idea on how to go about it...The idea I had going was simply inculcated in this sketch below

To generate a useful example I've setup an Arduino Nano with a magnetic orientation sensor and have it output 3 values per line for the X, Y and Z field strengths. It prints 1 line every 50ms and the following python tkinter script plots this. It started as your python code above but it has been reworked to be more pythonic. The result looks like this:

Call the script with the comport and speed. eg: python magplot.py COM21 19200
#!/usr/bin/python
#
# Read stream of lines from an Arduino with a magnetic sensor. This
# produces 3 values per line every 50ms that relate to the orientation
# of the sensor. Each line looks like:
# MAG   1.00    -2.00   0.00
# with each data line starting with "MAG" and each field separated by
# tab characters. Values are floating point numbers in ASCII encoding.
#
# This script supports both Python 2.7 and Python 3

from __future__ import print_function, division, absolute_import
import sys
if sys.hexversion > 0x02ffffff:
    import tkinter as tk
else:
    import Tkinter as tk
from serial import Serial

class App(tk.Frame):
    def __init__(self, parent, title, serialPort):
        tk.Frame.__init__(self, parent)
        self.serialPort = serialPort
        self.npoints = 100
        self.Line1 = [0 for x in range(self.npoints)]
        self.Line2 = [0 for x in range(self.npoints)]
        self.Line3 = [0 for x in range(self.npoints)]
        parent.wm_title(title)
        parent.wm_geometry("800x400")
        self.canvas = tk.Canvas(self, background="white")
        self.canvas.bind("<Configure>", self.on_resize)
        self.canvas.create_line((0, 0, 0, 0), tag='X', fill='darkblue', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Y', fill='darkred', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Z', fill='darkgreen', width=1)
        self.canvas.grid(sticky="news")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid(sticky="news")
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_columnconfigure(0, weight=1)

    def on_resize(self, event):
        self.replot()

    def read_serial(self):
        """
        Check for input from the serial port. On fetching a line, parse
        the sensor values and append to the stored data and post a replot
        request.
        """
        if self.serialPort.inWaiting() != 0:
            line = self.serialPort.readline()
            line = line.decode('ascii').strip("\r\n")
            if line[0:3] != "MAG":
                print(line) # line not a valid sensor result.
            else:
                try:
                    data = line.split("\t")
                    x, y, z = data[1], data[2], data[3]
                    self.append_values(x, y, z)
                    self.after_idle(self.replot)
                except Exception as e:
                    print(e)
        self.after(10, self.read_serial)

    def append_values(self, x, y, z):
        """
        Update the cached data lists with new sensor values.
        """
        self.Line1.append(float(x))
        self.Line1 = self.Line1[-1 * self.npoints:]
        self.Line2.append(float(y))
        self.Line2 = self.Line2[-1 * self.npoints:]
        self.Line3.append(float(z))
        self.Line3 = self.Line3[-1 * self.npoints:]
        return

    def replot(self):
        """
        Update the canvas graph lines from the cached data lists.
        The lines are scaled to match the canvas size as the window may
        be resized by the user.
        """
        w = self.winfo_width()
        h = self.winfo_height()
        max_X = max(self.Line1) + 1e-5
        max_Y = max(self.Line2) + 1e-5
        max_Z = max(self.Line3) + 1e-5
        max_all = 200.0
        coordsX, coordsY, coordsZ = [], [], []
        for n in range(0, self.npoints):
            x = (w * n) / self.npoints
            coordsX.append(x)
            coordsX.append(h - ((h * (self.Line1[n]+100)) / max_all))
            coordsY.append(x)
            coordsY.append(h - ((h * (self.Line2[n]+100)) / max_all))
            coordsZ.append(x)
            coordsZ.append(h - ((h * (self.Line3[n] + 100)) / max_all))
        self.canvas.coords('X', *coordsX)
        self.canvas.coords('Y', *coordsY)
        self.canvas.coords('Z', *coordsZ)

def main(args = None):
    if args is None:
        args = sys.argv
    port,baudrate = 'COM4', 115200
    if len(args) > 1:
        port = args[1]
    if len(args) > 2:
        baudrate = int(args[2])
    root = tk.Tk()
    app = App(root, "Smooth Sailing", Serial(port, baudrate))
    app.read_serial()
    app.mainloop()
    return 0

if __name__ == '__main__':
    sys.exit(main())

Update
Looking at the updated question it is clear that the new Tkinter code is not updating the display. In all windowing systems it is essential that the application thread is allowed to process events regularly. This is why the example code above uses the Tk after() method to add calls to the event queue. The read_serial() function checks to see if any data is available and if not schedules a retry later. This is done by using after() to request the same method is called again in 10ms time. During that 10ms delay the Tk application processes all the other windowing system events like mouse movement, keyboard input and crucially expose and painting events.
The same method is used to call the replot() method once we have updated the list of data items. In this case after_idle() has been used which means schedule this function call as soon as nothing else is happening.
The act of changing the canvas line coordinates will cause further events to be raised by Tk which affect the display only once they are processed by the event loop. If we never process the events, nothing will appear on screen.

I suggest adding some print() statements in read_serial to check you are reading values and splitting them right. Then check the scaling in replot. I've offset by 100 and scaled to 200 so the values must be -100 < x < 100. If your values lie outside that range they'll be offscreen. You could use max_all = max([max_X, max_Y, max_Z]) to range dynamically.

@pattyhoyts from your update, I garner that even though the structure of the sketch is correct, it's compilation/execution is the problem . Would you advise I continue to find ways for it to work on my system (Windows) or ditch it for something else?


text:
pushing accelerometer data in packets from an arduino due to the pc and unto processing
I'm quite a newbie to this and I've been struggling for sometime now with my school project, trying to find a way to send accelerometer data from my MMA7361 in data packets, I understand that I have to send the data in packets, but I'm having problems going about it. One of the requirements of the project is that I have to send the data in array-packets of all the individual axes (e.g. a buffer array to hold the x-axis value, another for the y-axis value and also for the z-axis value). I have read quite a lot of documentation on the internet about this  but putting it together is a challenge. Below is the infamous MMA7361 code sketch, do please help out if you can thankyou.
    #include <AcceleroMMA7361.h>

    AcceleroMMA7361 accelero;
    int x;
    int y;
    int z;

    void setup(){
        Serial.begin(9600);
        accelero.begin(13, 12, 11, 10, A0, A1, A2);
        accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
        accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
        accelero.calibrate();
    }

    void loop(){
        x = accelero.getXRaw();
        y = accelero.getYRaw();
        z = accelero.getZRaw();
        Serial.print("\nx: ");
        Serial.print(x);
        Serial.print("\ty: ");
        Serial.print(y);
        Serial.print("\tz: ");
        Serial.print(z);
        delay(500);                                     //(make it readable)
    }

How large do you want the buffer to be? For instance, how many x values do you want to read from the sensor before you send the data packet?

thanks @Chris for the response, the buffer is supposed to hold 1000 values at a time

It's pretty simple to store the x, y and z co-ordinates in three separate arrays. Instead of storing them in single int variables you can just store them in int arrays. You can make three arrays that are of size 1000 a store the raw values there. In order to iterate through the arrays within loop() you can set up i at global scope and include an if statement that will know when the arrays are filled, for example if (i == 1000) and within this if statement you can set up a for loop that will iterate through the arrays and print their values and after reset i to 0 and then reset the buffer arrays i.e. fill them with zeroes. This last step is not needed since they will be overwritten anyway but it is good to have so you don't accidentally use old values.
Also the for loop that will print the values will take 8 minutes with that delay(500); You can make this delay smaller or print the value before each if statement as the data comes in.
#include <AcceleroMMA7361.h>

AcceleroMMA7361 accelero;
int xAxisBuffer [1000] = {0};
int yAxisBuffer [1000] = {0};
int zAxisBuffer [1000] = {0};

int i = 0;

void setup(){
    Serial.begin(9600);
    accelero.begin(13, 12, 11, 10, A0, A1, A2);
    accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
    accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
    accelero.calibrate();
}

void loop(){
    // This stores the x, y and z values in their
    // respective arrays
    xAxisBuffer[i] = accelero.getXRaw();
    yAxisBuffer[i] = accelero.getYRaw();
    zAxisBuffer[i] = accelero.getZRaw();
    ++i; // moves to the next position

    if (i == 1000){ // the arrays are full
        // prints the (x, y, z) values
        // because the delay is .5 seconds it will
        // take about 8 minutes to print all 1000
        for (int j = 0; j < 1000; j++){
            Serial.print("\nx: ");
            Serial.print(xAxisBuffer[j]);
            Serial.print("\ty: ");
            Serial.print(yAxisBuffer[j]);
            Serial.print("\tz: ");
            Serial.print(zAxisBuffer[j]);
            delay(500); //(make it readable)
        }
        // restart at beginning of the arrays
        i = 0;
        // reset the arrays
        memset(xAxisBuffer,0,sizeof(xAxisBuffer));
        memset(yAxisBuffer,0,sizeof(yAxisBuffer));
        memset(zAxisBuffer,0,sizeof(zAxisBuffer));
    }
}

LORD GOD!!!......Thanks @Chris ...you are a life saver...I've been stuck in this loop for a month now. Thank you very much...

No problem, if you're stuck like that again ask the question here. If this answered your question choose it for best answer (It's the check mark under the score for my answer).

Thanks, remember to pick the best answer on any future questions you have. It helps the community find good answers quickly.

sure @Chris...will do!!!


text:
How to Send Live Sensor Data to iOS Custom Apps with BLE
I am looking for a Bluetooth Low Energy (BLE) device that could send live sensor data from Arduino to iOS custom apps, not the app that is already in the app store. I would like to create my own apps to receive the sensor data. Or are there any other ways to achieve it?

I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:

Finding a BLE chip that is relatively easy to integrate with an Arduino, and
Selecting the tools that you'll use on the iOS side to develop your app.

Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:
aruduino ble
I found quite a few candidates that look promising, here are some of the better ones:

Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0 – I put this one on the top of my list because the price is pretty reasonable (< $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.
Redbear Labs - I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.
BLEduino - this is a Kickstarter, and while it looks interesting, a very quick investigation didn't reveal a source where you can buy one.

The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.
Next you'll need to select development tools. I started by searching with the terms:
ble swift ios
I got a number of promising results, including:

Arduino Tutorial: Integrating Bluetooth LE and iOS with Swift
Apple: Bluetooth for Developers
Adafruit - Introduction to Bluetooth Low Energy

These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.

Getting Started with the nRF8001 Bluefruit LE Breakout
RedBearLab/iOS


text:
Arduino library making
I make my own library for arduino.
The file structure is like below.
AAA - README.md
    - examples - A - A.ino
               - B - B.ino
    - AAA.h
    - BBB.h
    - CCC.h
    - BBB.cpp
    - CCC.cpp

It works well. But I want to grouping a library source files like below.
AAA - same as above
    - src - AAA.h
          - BBB.h
          - CCC.h
          - BBB.cpp
          - CCC.cpp

It doesn't work at all.
Arduino IDE shows the message

Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?

I'm going to assume your library structure is like this because the structure you described above would not cause that error:
AAA
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the 1.5 library format. Putting all the source files in the src subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:
AAA
|_library.properties
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp


text:
Is it possible to send data from internet server to ESP8266 behind proxy or regular requests from ESP8266 are required?
It would be kind of push notification or something like that probably.
I can first connect to server and send it any data for "registration"...
I found many examples with websockets but all of them was about ESP8266 is like "server". That's not this case...

https://en.wikipedia.org/wiki/WebSocket

I found many examples with websockets but all of them was about ESP8266 is like "server" there. That's not this case...

So look for more examples where the ESP8266 is the client? They must be out there somewhere.

have you looked into using MQTT?

It seems evident that you don't want your ESP8266 running as a server of any kind. That's understandable given that server programs consume a fair amount of system resources (CPU, RAM, etc.) that are in short supply. That means you'll have to use your ESP8266 as a client and this means either

Polling - where the ESP8266 repeatedly connects to your "internet server" to explicitly ask for information at frequent intervals. Your internet server would have to be able to collect information in batches and hang onto it until your ESP8266 connects again to request the information.

Socket connections - where your ESP8266 maintains a consistent socket connection to your "internet server." Note that the HTTP protocol relies on socket connections, but clients open a socket connection, request a web page and its images, CSS, etc., then disconnects the socket. You can also use sockets at a more basic level as a bytestream. This programming can be tricky, but ESP8266 does have examples of TCP socket communication like WiFiClient and ethernet client.

Client approaches have a variety of headaches:

server has to hang on to information until the client comes back to retrieve it
you have to work up some kind of data structure to track which information has been handled and which work must still be done
latency issues -- i.e., what happens when there's a delay in processing information.

Server approaches also have challenges:

server programs can be tricky to write so that they keep running. a single exception or fatal error can crash the program
server programs are vulnerable to DDoS or other attacks, and can easily overwhelm a small device like ESP8266
firewall and networking issues -- depending on how this device connects to the internet, it may or may not have a consistent IP address where it can be found, the ISP that connects it may not allow incoming connections for the ports that it listens on, etc.

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


text:
How to change Multiple variable values through Serial Monitor
I am trying ... with minimal success to change/Check and also run voids through the serial monitor .the code i  put i am having probles is that when i am try to send a value larger than 9 the value assigns a diffrent number Ex i set to 200 but arduino sets it as 512.. i got around it deviding the value by 1.6 and got me the new number and only works upto 90 , but i am tryn to see how it should be done correctly...
const uint16_t inputLength = 512;
int ss = 0;
int bHold = 0;

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

 void loop() {
  if ( Serial.available() > 0 )
  {
    static char input[inputLength];
    static uint16_t i;
    char c = Serial.read();

    if ( c != '\r' && c != '\n' && i < inputLength - 1)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "ss", 2) )
      {
        char* p = input + 2;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10); //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
          ss = array[i];
          Serial.println(ss);
        }
      }

      if ( !strncmp(input, "bHold", 5) )
      {
        char* p = input + 5;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10);   //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
         bHold = array[i];
        // bHold=bHold /1.6;
         Serial.println(bHold);
        }
      }

      if ( !strncmp(input, "Whos There", 10) )
      {
        Serial.print("me");
      }
      if ( !strncmp(input, "hello", 5) )
      {
        Serial.print("hi");
      }
      if ( !strncmp(input, "sa", 2) )
      {
        Serial.print("  ss= ");
        Serial.print(ss);

        Serial.print("  bHold= ");
        Serial.print(bHold);

        Serial.println(" ");
        Serial.println("==============================");
      }
    }
  }
}

Thank you for any tips you can give...
EDIT: I am trying to pass a new value with command on the serial monitor "ss 500"..so that in the arsuino ss = 500. but in this case it makes it equal to 1280.
EDIT2: Chaged the strol to 10...works perfectly ...Thank you TisteAndii!!!!

What do you mean with "ss = array[i], DEC;". That is "ss=DEC" and gives the same value ss. Should be "ss = array[i]; Serial.println(ss, DEC);"

Edit the code in your post if you have made any changes to it so far.

You are setting the input string's base to 16 instead of 10 in your strtol conversions, which is why you are getting 1280 when you expect 500.

Ex i set to 200 but arduino sets it as 512 - TisteAndii is right. 0x200 is 512 in decimal.


text:
Speeding up Arduino DC Motors
I am using the Adafruit Motor Shield v2.3 for Arduino Uno. I am using the analogWrite() command to power my DC motor and have set the speed to 255. Is there any way to speed up the Arduino motor even further? Thanks!

The speed of a motor is a function of the motor itself and the voltage applied to it. There is no programmatic way of increasing the speed of a motor. You would either need to increase the voltage being applied to the motor (as long as it is within the limits of your motor and speed controller) or find a different motor to use that is faster.
It appears the Adafruit motor shield accepts between 5-12 volts, if you are not already at the maximum of 12 volts, and your motor is rated to allow it, you can increase the voltage you are applying to the shield. All that 255 means in this case is give the motor all the power that is available, so if you are only giving the controller 5 volts, it is only going to give the motor 5 volts.
Also I might recommend instead of using analogWrite() that you use the official Adafruit library to control your shield as it uses its own PWM library which is more performant for motor control than the built-in Arduino one.
EDIT
Actually, with v2 of the shield, it has its own PWM driver controlled over I2C. In which case analogWrite() shouldn't work at all, or at least it doesn't do what you think it does. Instead use the official Adafruit library and I also recommend following the official tutorial as well.

Sorry about that, I was actually using the Adafruit Library. My Arduino us being powered by a 9v battery. However, the motor is only getting 5v. Is there any way to give the motor more power? I can't power the Motor Shield via another source of power; I have to use the VIN Jumper.

There are plenty of other questions on this site that address this, but the short version is do NOT use a 9v battery for motors https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14


text:
Errors when deploying Simulink model to Arduino Due
I am trying to connect an Arduino Due to Simulink to run it in external mode. I am unable to successfully deploy to hardware.
I'm testing it with a blinking light model: A pulse generator connected to a digital output pin. This is the error message:
  ### Starting build procedure for model: due_blink
   Code Generation  1
  Elapsed: 8 sec
  ### Generating code into build folder: C:\Users\Dana\Documents\MATLAB\due_blink_ert_rtw
  ### Invoking Target Language Compiler on due_blink.rtw
  ### Using System Target File: C:\Program Files\MATLAB\R2015b\rtw\c\ert\ert.tlc
  ### Loading TLC function libraries
  ### Initial pass through model to cache user defined code
  ### Caching model source code
  ### Writing header file due_blink.h
  ### Writing header file due_blink_types.h
  .
  ### Writing header file rtwtypes.h
  ### Writing source file due_blink.c
  ### Writing header file due_blink_private.h
  ### Writing source file due_blink_data.c
  ### Writing header file rtmodel.h
  .
  ### Writing source file ert_main.c
  ### TLC code generation complete.
  ### Evaluating PostCodeGenCommand specified in the model
  ### Using toolchain: Arduino ARM v1.6.1 | gmake (64-bit Windows)
  ### 'C:\Users\Dana\Documents\MATLAB\due_blink_ert_rtw\due_blink.mk' is up to date
  ### Building 'due_blink': C:\PROGRA~1\MATLAB\R2015b\bin\win64\gmake -f due_blink.mk all
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-gcc -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "due_blink.o" "due_blink.c"
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-gcc -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "due_blink_data.o" "due_blink_data.c"
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-g++ -fno-threadsafe-statics -fno-rtti -fno-exceptions -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "USBCore.o" "C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp"
  <command-line>:0:13: error: initializer fails to determine size of 'STRING_PRODUCT'
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp:69:34: note: in expansion of macro 'USB_PRODUCT'
   const uint8_t STRING_PRODUCT[] = USB_PRODUCT;
                                    ^
  <command-line>:0:13: error: array must be initialized with a brace-enclosed initializer
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp:69:34: note: in expansion of macro 'USB_PRODUCT'
   const uint8_t STRING_PRODUCT[] = USB_PRODUCT;
                                    ^
  gmake: *** [USBCore.o] Error 1
  ### Build procedure for model: 'due_blink' aborted due to an error.
  Error(s) encountered while building "due_blink":
  ### Failed to generate all binary outputs.
  Component: Simulink | Category: Model error

I have the Arduino Due board selected in the settings, with the correct COM port. When running the same model with an Arduino Uno, ld.exe crashes with exit status 255.
I can connect to the board in the Matlab command window and manually change the pins to HIGH or LOW, so it must be a problem with Simulink.
Any help would be appreciated.


text:
Get csv field values
I am uploading data using Thingspeak and I would like to get only values stored in a field. Is there any way to get this in a cvs http request?
When you call a cvs http url, you get:

What I am trying to get is just the value in field2: 10,10,12,12,16 without the headers.

Is your hope to get just the content of field2 via the HTTP request? Or are you looking for a way to parse the data to get the content of the field?

I woud like to get just the content of field2 via HTTP request to integrate data into an array of chart library that only accepts thins kind of data.

Where you wrote, “i would like to get only values stored in a field.Is there any way to get this in a csv http request?.When you call a csv http url,you get: created_id,entry_id,field1,field2 2015-10-22 19:30:00,14878,18,5 ,what i am trying to get is only the value in field2: 5 without headers”, does  “csv” stand for comma separated values or is it some other acronym?  Please edit your question and make it more understandable.

The csv url data comes with comma separated values and all data is the first field when they opened with excel.I have edited the question and added a picture to show the format.

You can use this format to achieve what you described:
http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)

Source: http://community.thingspeak.com/documentation/api/
Edit: It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:
  int i;
  String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";

  for (i = response.length()-1; i >= 0 ; i--)
  {
    if (s.charAt(i) == ',') break;
  }
  String value = response.substring(i+1);
  Serial.println(value); // This will show only 5

Hello. Thanks for your reply. I already tried that option through the following url:https://thingspeak.com/channels/(channel_id)/fields/field2.csv?key=***&results=1 ,but the final result is:
created_at,entry_id,field2 2015-10-22 19:30:00,14878,5,so i don't know if there is more url options to get only 5 value.
Thanks.

It seems there are no options like that, but you can always try my answer.


text:
Two commands in Void loop?
So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?
So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int inPin2 = 26;
int outPin1 = 13;       // the number of the output pin
int outPin2 = 6;

int state = LOW;      // the current state of the output pin
int reading;           // the current reading from the input pin
int reading2;
int previous = HIGH;    // the previous reading from the input pin
int previous2 = HIGH;

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();
  lcd.print("Zone1|State: ");
  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);

  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    doIt(outPin1);
  }
  else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
    doIt(outPin2);
  }

  previous = reading;
  previous2 = reading2;
  time = millis();
}

So basically I just added the sketch to this post.

Edit: Use the code below as it is, it's working for me:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;
int inPin2 = 26;
int outPin1 = 13;
int outPin2 = 6;

int state1 = HIGH;
int state2 = HIGH;
int reading;
int reading2;
int previous = HIGH;
int previous2 = HIGH;

int debounce = 150;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin, int state)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();

  if (outPin == outPin1)
    lcd.print("Zone1|State: ");
  else if (outPin == outPin2)
    lcd.print("Zone2|State: ");

  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);
  delay(debounce);

  if (reading == HIGH)
  {
    state1 = !state1;
    doIt(outPin1, state1);
  }
  else if (reading2 == HIGH){
    state2 = !state2;
    doIt(outPin2, state2);
  }
}

Oh one question, do I have to do void doIT (int outPin) for both outputs?

I added what you had, but when I press the button, nothing happens, can you review for me please?

I put the code as an edit above

You have a mistake in the loop(), you don't actually need to call digitalWrite(outPin, state); since it's already called in the function doIt().

Another mistake is that you used the same name for two variables which is outPin, this one is already used in the function doIt(). you need to give it another name, say outPin1.

Sorry that I keep bothering you, but I updated the above sketch, and it still seems to not want to do anything.

No problem man, I'm still seeing digitalWrite(outPin, state); in your loop(), all the way down ??

I already removed that, sorry I didn't remove it in this discussion, but in my sketch I did.

Ok, please give me some time, I'll try it out and get back to you.

You're welcome man, do you really need to do the debouncing? why not using a delay after every digitalRead()?

I doubt that's the issue, but the reason why I use it is because its just more reliable, and runs much better for the ram I'm pretty sure, sorry but I am very noob XD

Actually, can you post the same thing but without the doIt? and whatever is in the doIt put it in the if statements? Or edit mine.

If I remove the doIt(), I will just end up repeating the same lines of code in two if statements which is not so pretty ;) anyway try the edited answer I posted since it is working for me.

I'm just now figuring out how to make the Zone1 into Zone2 for the 2nd button, but thanks again!

Easy ;) I've re-edited my answer to do that as well.

Jeez, you are the best XD Thanks Again again again!

I think you are asking
if (value > 5)
{
  StatementOne;
  statementTwo;
}

But I think you might want to write a function, which would look like this
void doThing(int button, int led)
{
  if (digitalRead(button))
     digitalWrite(led);
}

[Edit after reading your comment]
So you need to store the state of the system as a variable in the code.
bool state = false;
if (button1 && !state)
{
  state = true;
  // Your on code.
}
if (button2 && state)
{
  state = false;
  // Your off code
}

You need to add your existing code for turning your LCD and LED on and off where the comments are.
The state variable holds the on or off state of your LCD and LED.
You can of course split it even further so your LCD and LED come on separately of each other.
Does that help?  If so don't forget to mark it as answered.

What I mean is, I have 2 button commands, so if I press it, show something on LCD and led turns on, then when I press it again, do opposite.  I did that with the If command and it worked, but I want 2, so its the same thing but on a different pin

OK, I've edited the answer, because I can't type code in a comment, hope that helps, if not tell me why and I'll have another go :)

Actually, that would work as well! I need to put another command, so ill use this for my sensors! Thank you!

authors: عبد الرحمن عقده


text:
When should you worry about interference affecting the analog input?
I made something that uploads the measured current to Thingspeak. Everything works, but i did not place the DC to DC converter on the board because i was worried that it would interfere with the analog input. Also the ESP8266 is very close to the Arduino Pro Mini. Could it affect the reading?
Could i have put the DC to DC converter on the board without any problem?

230VAC to 12VDC adapter(not on the picture) --> 12VDC to 3,3VDC(on the picture)-->the prototype board
Sensor: SCT-013-030 30A = 1V

There is not enough information for making  hardware improvement suggestions.  For starters what are you using as a sensor?  What type of impedance does it have? Is it generating current, voltage or does its resistance vary? However, my first thought is to shorten what appears to be an excessively long cable between the ADC input and the sensor. And if you are really worried about power noise, try a test where you run everything off of batteries.

Sensor: SCT-013-030 30A = 1V

Ah, that's what that blue thing is!  The internal resistance is low.  About 62 ohms according to the specifications.  In general, the lower the internal resistance the less influence electrical noise will make.   We can say it is less likely for the switcher to interfere with the ADC should you decide to mount it on the board.  I am a bit more concerned about the switcher coupling with the radio.  To be safe, I would keep them on opposite sides of the board and point the radio's antenna away from the switcher.

You are more likely to have noise injected on the power pins of the Arduino that by EMI or capacitative coupling. With the switcher on board of off board it will make no difference if the voltage it supplies to the Arduino (and hence to the ADC) is noisy and full of spikes.

Noise reduction involving Analog to Digital Conversions can be done in many ways.  Common software solutions involve averaging multiple conversions.  Exponential smoothing is one such method.  One advantage of exponential smoothing is that it can be applied to an endless stream of conversions.

I don't want to smooth it, i just want to know if the DC to DC converter or the ESP8266 could affect the analog reading?
Also the analog input is an AC signal, i guess you can't smooth that.

Actually ADC are noisy enough that, say, an 8 bit ADC only gives you a few bits of significant accuracy w/o taking multiple samples into consideration.  The DC to DC is probably operating at a high frequency.  So, guessing because I don't know much about your sensor, you might be able to mitigate any effect by adding a low pass filter to the ADC input.  In the end, designing with switchers is notoriously problematic.  I have seen hardware designers spinning boards because of switcher problems.  Others may have more experience, but this may come down to trying & testing.


text:
How to convert String to Double?
I found the .toFloat() but that's not accurate enough.
String StrEx = "57.10598";
float FloatEx = StrEx.toFloat();

Serial.println(String(FloatEx)); //outputs 57.11
Serial.println(StrEx);           //outputs 57.10598

There is no double.

What does Serial.println(FloatEx, 5); give you?

@Majenko gives me 57.10598. Thanks!!!

It is a common misconception that, because when you print a float you only get 2 decimal places, that the float only has 2 decimal places.
That is not true. A float doesn't have a number of decimal places - that is how it gets its name - floating point: the decimal point floats around as needed.
The problem is actually that, by default, all the Arduino print and string conversion functions are set to 2 decimal places. Unless you specify the number of decimal places you want to print (or convert to) you get 2 decimal places.
By specifying 5 decimal places when you print or convert to a string you get 5 decimal places.  It still won't always give you exactly the same number, but that is because a 32-bit float cannot store all possible numbers, so some are only an approximation. It's still a whole lot more accurate than 57.10598 -> 57.11 though.


text:
How to create a simple TCP server with the analogRead value on Wemos D1 mini?
I want to create a TCP server on the Wemos that serves the analogRead value of the connected potentiometer.
The code below is based on this example.
The Wemos connects to the Wi-Fi and i'm able to ping it,
but the problem is that I can't connect to the server.
Also I don't really understand why the length of the data has to be passed with the data (serverClients[i].write(sbuf, len);). Why can't the library figure that out?
#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  Serial.begin(115200);
  Serial.print("\nConnecting to "); Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.setNoDelay(true);
  Serial.print(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0); //analog read
    String sSensorValue = String(isensorValue); //int to string
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}

I've never used a Wemos, but if you compare to the code you linked, you seem to be missing a server.begin() call.

Also, that code looks a little wonky to me. For example, the continue is completely useless. Did they want a break there?

@JohnnyMopp You have a great eye for detail!

So the problem was that I forgot the following line.
Thanks to @Johnny Mopp for pointing this out.
server.begin()

Correct code:
#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.begin();
  server.setNoDelay(true);
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0);
    String sSensorValue = String(isensorValue) + "\n\r";
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}