message:
I want to know how to record and play radio waves?

I want to make a universal remote.I have an ir receiver and transmiter. I.I can use it to control my tv and other equipment.I want to also control my dish network in the US. I checked and think that the dish uses 395mhz but i am not sure.**How can i replicate a dish remote radio signal**.I know it is radio signal and not ir. **What part do I need for the arduino?**

body:
This is only a partial answer, but should be enough to get you started.

The parts are:

 1. Build a receiver http://www.somerset.net/arm/fm_only_lowtech.html
 2. Tune it to the right frequency
 3. Use it to detect the codes sent from your remote
 4. Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
 5. Tune it to the right frequency
 6. Transmit the codes
 7. Success!

Step 3 is probably best done with a scope - you should find someone who has one, who can operate it, because they can be damaged.


sender: user

message:
Temperature sensor reading is higher than the actual temperature

// Tells the Arduino to read A2 and stores the value in “Vin”
    Vin = analogRead (tempSensor);

    // Converts the voltage value to temperature and stores it into the “TC” variable (in °C)
    TC = 500.0 * (Vin / 1024.0);

The temperature shown is about 50.25°C, sometimes it is showing 36-38°C   degrees, but the actual temperature is about 25-26°C.

Why this is happening?

Code:

    Vin = analogRead (tempSensor);
    TC=(500.0*Vin)/1023.0;
    TF = ((9.0*TC)/5.0)+32.0;
    lcd.setCursor(0, 1);
    lcd.print(TF);
    lcd.print((char)223);
    lcd.print("F ");
    lcd.print (TC);
    lcd.print((char)223);
    lcd.print("C");
    delay(1000);

sender: assistant

body:
It sounds like your voltage to temperature calculation is wrong. Assuming the temperature voltage relationship is linear you can work out the formula. Take two measurements at two known temperatures (quite far apart, perhaps outdoors and in) and note down the value Arduino measures for Vin. Lets call these VinA & VinB for TempA and TempB.

You can calculate measures per degree with...

MeasuresPerDeg = (TempB - TempA) /(VinB - VinA)

And the a constant as...

Constant = TempA - VinA*MeasuresPerDeg

Your equation to calculate temperature should now be

TC=MeasuresPerDeg*(Vin/1024.0) + Constant;


body:
Any chance you're printing Vin, and not TC?

500*(50.25/1024) = ~24.5

If not, please post as much of your program as possible


body:
I gave up on using a LM335, which is quite similar to your LM35. The problem is these devices self-heat due to the quiescent power they draw. The LM35 data sheet suggests you correct for this in software (footnote 5), and the LM335 datasheet dodges the bullet by quoting accuracy figures that can be achieved in an oil bath rather than free air.

But the figures you are quoting suggest you have a bigger problem, as I am talking of a few degrees inaccuracy, not tens of degrees.

I changed to a DS18B20 and never looked back - simple interface and self-heating is compensated for by the device.


body:
What are the variable types of `TC` and `TF` - int/float/double? Something else?

If they're integers, you may be losing some numerical precision in the calculation.

When you get 50.25°C - have you checked the `Vin` is correct?

Also when you write the values out, the serial.print() can take the number of decimal points as a second argument.

    // Print to three decimal places
    Serial.print("TF=");
    Serial.println((float)TF, 3);
    Serial.print("TC=");
    Serial.println((float)TC, 3);
    Serial.print("Vin=");
    Serial.println(Vin, DEC);


message:
Arduino around the Xmega?

I came across a dev board around the Atmel Xmega controller. This an AVR like used on Arduino, but with a lot of extras.

![enter image description here][1]

I was surprised to see that the board is hardly more expensive than an Arduino, despite:

> - 384kB of Flash (versus 32kB for Arduino)
- DMA
- Xmega can run at 32 MHz (16 MHz for Arduino)
- on-board OLED display
- on-board light and temperature sensors
- on-board microSD socket

For all these on-board features you'd need a shield or breakout board for Arduino. I seems to me that for a lower price than Arduino you could build a much more powerful system, which is Arduino-compatible.
How hard would it be to port Arduino to the Xmega?

see also [http://www.element14.com/community/docs/DOC-71436](http://www.element14.com/community/docs/DOC-71436)

  [1]: https://i.stack.imgur.com/UCSG3.png

body:
There's an attempt to get the Atmel XMEGA boards working in Arduino IDE.

https://github.com/akafugu/Xmegaduino

It's not fully featured yet but appears to have to features to allow you to start hacking with this board.


message:
Choosing rangefinder for obstacle-avoiding

I am looking to buy a range finder module for an obstacle avoidance robot.
Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.

In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?

both need 5V
both have max range of 3-4m
Sensor angle HC- 15 degrees, parallax cant find..

body:
> Odds are pretty good they are real close. I've only used the sr04 with
> 4 pins (too lazy to mod) and it was ok. cant say if the parallax is
> better or not. For 4 times the price you'd expect it to be, but so far
> in robotics, price seldom reflect performance in my experience. –
> Spiked3

I've also used the SR (with 4 pins) and it worked great. <2$ on eBay


message:
Matlab to Arduino communication

I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you

body:
You cannot send larger values because byte only covers the range from 0-255.

To send larger values, you can break your int variable into 2 byte variables. Here's an example:

    // On Arduino
    int myVar = -123;
    byte myVar_HighByte = myVar>>8; // get the high byte
    byte myVar_LowByte = myVar; // get the low byte
    // x86 compatible machines are little-endian so we send the low byte first
    Serial.write(myVar_LowByte);
    Serial.write(myVar_HighByte);

    % On MATLAB
    s = serial('COM10')
    fopen(s)
    myVar = fread(s,1,'int16')

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)

Edit: On second thought, it might be easier to use a pointer.

    // On Arduino
    float myFloat = 3.14159265359;
    byte* ptr = (byte*) (&myFloat);
    Serial.write(*ptr++);
    Serial.write(*ptr++);
    Serial.write(*ptr++);
    Serial.write(*ptr);

    % On MATLAB
    s = serial('COM10')
    fopen(s)
    myVar = fread(s,1,'float')

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.


body:
If you want to send your data directly from Matlab to the Arduino, you can try using the "Matlab Arduino Support package". It lets you read/write pins on the arduino directly from Matlab command line or script just like you would with a VERY LOW END Data Acquisition card.

This has the advantage of removing the burden of managing the serial communication. I don't know how it handles large numbers though.

http://www.mathworks.com/hardware-support/arduino-matlab.html?refresh=true


message:
Send array of Infrared codes

I'm having a bit of a problem when sending IR Codes stored in variables. I swear I had this convered up already. I don't actually know the reason why I can't use variables in the first place. I receive data over Bluetooth Serial Com and I'm using an Arduino ProMicro as ISP for the Arduino Nano.

I want to send data over Serial comm and then send an IR code to the end receiver.

Here is some of the code():

    #include <IRremote.h> // IR Library - Encode/Decode

    void irSerial( char SerChar[] ) // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action referece
    byte CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 2; // Size Of The array

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR <= IRArray; CountIR++){ // Loop through array
        if ( SerChar[0] == IDChar[CountIR]) {
           bluetooth.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
    }

There's not a problem with the current expression as it compiles normally and I can send serial data normally finishing the function. If I replace the array **CodesIR[CountIR]** for example with **0x61A0F00F** then it works perfectly.

How can I use a variable instead? Can anyone help? It is the **byte CodesIR[]** ??

I used a **Switch/Case** and it works but I prefer a variable/array and less useless coding. Thanks for understanding!

body:
Well as usual it was something stupid (-__-) I changed the **byte** array for **long** and it worked perfectly.

Here is the complete code working():

    #include <IRremote.h> // IR Library - Encode/Decode

    void irSerial( char SerChar[] ) { // Receive array of characters

        char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
        String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
        long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
        int IRArray = 3; // Size Of The array # Edit

        if ( SerChar[0] == 's' ) { // Compare Array
          for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
            if ( SerChar[0] == IDChar[CountIR]) {
               Serial.println(HRD[CountIR]); // Send String in array - Works
               SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
            }
          }
        }
    }


message:
Data at Serial Port Avaliable

I am interfacing a GSM modem via Arduino at Serial port 2.

I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I  have a code like below which checks for response from GSM modem based upon a user configurable timeout value:

    sendATcommand(str_at_cmd, str_ok, 500);

    int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
    {
        uint8_t x=0;
        char response[100];
        unsigned long previous;
        int answer = 0;
        memset(response, '\0', 100);
        answer = 0;;
        delay(100);
        ClearSerialData(); // read and flush all data
        debug_println(ATcommand);
        Serial2.println(ATcommand);
        delay(200);
        x = 0;
        previous = millis();
        do {
           if(Serial2.available() > 0){
           response[x] = Serial2.read();
           delay(100);
           debug_print(response[x]);
           response[++x] = '\0';
           if (strstr(response, expected_answer) != NULL)
           {
               debug_print("\nAnswer Mathced");
               answer = 1;
           }
           }
        }while((answer == 0) && ((millis() - previous) < timeout));
        debug_println("\nReturning from AT Command");
        return answer;
    }

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.

My question if I change the code like below

    while(Serial2.available() > 0){
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
    }

So when does Serial2.available() method returns <= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

body:
Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().


message:
Interfacing Arduino Leonardo with PCA8574AN

I'm trying to interface my Leonardo with a "Mindsensors Magic Wand" - 8 LEDs connected to a PCA8574AN chip.
On the manufacturer's page, they say it's compatible with Arduino, however no instructions or code are given.
http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=120

I've connected the SDA, SCL, 5v, and GND connectors on the arduino to the device, but have had no luck in communicating with it. None of the LEDs light up regardless of input.

I can verify that power is being supplied.
The i2c address of the device is 0x70.
Code is below.

    #include "Wire.h"
    #define TWBR=400000L
    void setup() {
      // put your setup code here, to run once:
     Wire.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      delay(2000);
      Wire.beginTransmission(0x70);
      Wire.write(32);
      Wire.endTransmission();
    }

body:
**tl;dr:** It seems like you need to send a null bit (0) to terminate the communication with this board.

In the downloads section, I found a .nxc file, which I assume is a NXT code file.

In the main loop, they configure the I2C port and a "touch sensor" (I believe this is to figure out how to synchronize the text with the motor). In that, there is a main loop in which they call `DispLetter`.

This is the `DispLetter` function:

    void DispLetter (const byte & letter[])
    {
      int nbytes;
      // Wait for the end of previously sent data
      while(I2CStatus(I2Cport, nbytes)==STAT_COMM_PENDING);
      // Write buffer to send to PCF8574
      byte WriteBuf[];
      ArrayBuild(WriteBuf, I2CAddr8574, letter);
      for(int i=1; i<ArrayLen(WriteBuf); i++)
      {
         WriteBuf[i] ^= 0xff;
      }
      I2CWrite(I2Cport, 0,  WriteBuf);
    }

Let's read this code! First of all, it seems to make sure that the I2C port is connected, which we don't really have to worry about in our case since that's platform-specific.

After that, they create an array called `WriteBuf[]` that will store the data to be sent to the controller. Then we come across a function called `ArrayBuild`. Looking that up, it combines `I2CAddr8574` and `letter` and places it into the `WriteBuf` array. ([Click here for documentation for that function.][1]) Please note that the `I2CAddr8574` is just a byte containing 0x70 (the address of the chip), so we will not have to do this step since the Arduino handles the address. So, you will just have to send the `letter` array to the controller, ignoring the `WriteBuf` and `ArrayBuild`!

Let's figure out how `letter` is passed. In the main loop, they had this code:

    DispLetter(L_);
    DispLetter(E_);
    DispLetter(G_);
    DispLetter(O_);

That must display "LEGO." Let's figure out what `L_` is defined as. At the beginning of the document, they have this defined:

    // Display patterns
    // Each byte represents a column of dots
    // Bit set to 1 means lit LED.
    // Least significant bit is at top of column.
    // Last byte must be all 0
    // Maximum number of bytes par pattern: 15

    byte L_[] = {0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0};
    byte E_[] = {0xff, 0x89, 0x89, 0x89, 0x89, 0x81, 0x81, 0};
    byte G_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x91, 0x90, 0x72, 0};
    byte O_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

    byte La_[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0};
    byte Ea_[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
    byte Ga_[] = {0x72, 0x90, 0x91, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};
    byte Oa_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

    byte N_[] = {0xff, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xff, 0};
    byte X_[] = {0x80, 0x41, 0x22, 0x14, 0x08, 0x14, 0x22, 0x41, 0x80, 0};
    byte T_[] = {0x01, 0x01, 0x01, 0x01, 0xff, 0x01, 0x01, 0x01, 0x01, 0};

As you can see, they listed out how the dots are configured. There's a max of 15 bytes (I assume including the null bit).

There's one more piece of code that we haven't talked about:

    for(int i=1; i<ArrayLen(WriteBuf); i++)
    {
       WriteBuf[i] ^= 0xff;
    }

So it goes through each bit, and does something to it. That is the shorthand for this:

    WriteBuf[i] = WriteBuf[i] ^ 0xff;

No, that is *not* an exponent. That is an exclusive OR, a *bitwise* operator. A bitwise operator is basically where it "overlays" the two binary sequences and it does a special computation on them. If the nth bit of each input number is 1 or the nth bit of each input number is 0, the nth output bit is 0. If the nth bit of one input number is 1 and the nth bit of the other input number is 0, then the nth bit of the output is 1.

Since 0xff = B11111111, it will essentially reverse the values of each bit. You can avoid this if you say that a bit set to *0* is on, instead of a bit set to *1* (like they do in the example code). A minor adjustment that just makes your life a bit easier :)

After that, you can write that array to the I2C bus and it should display the data!

  [1]: http://bricxcc.sourceforge.net/nbc/nxcdoc/nxcapi/group___array_functions_gae8d75e08c670f09f01200a897d7ed2ba.html


message:
Unable to alter SPI speed on Arduino Micro

I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

    unsigned int m_SPISpeed = 400000;
    SPI.begin();
    pinMode(m_SPISelect, OUTPUT);
    m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
    ...
    SPI.beginTransaction(m_SPISettings);
    digitalWrite(m_SPISelect, LOW);
    SPI.transfer(regAddr | 0x80);

Where `m_SPISpeed` is 400000. No matter what i set this value to it is always operating at `125000Hz`.

body:
As was pointed out in the question comments, your use of **unsigned int** is the problem. The prototype for SPISettings is:

    SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

The comments in spi.h say:

    // We find the fastest clock that is less than or equal to the
    // given clock rate. The clock divider that results in clock_setting
    // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
    // slowest (128 == 2 ^^ 7, so clock_div = 6).

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).


message:
can i give a vcc to 14v?

What is maximum voltage PWM pins can give?
can i give a vcc to 14v?

body: Since PWM pins are digital outputs, the maximum output voltage is VCC.


body:
On a typical Arduino board, PWM pins will theoretically only ever operate at ground (+0v) or `Vcc` (typically +5v). PWM is a square wave, which means it alternates rapidly between those two values, aka `LOW` and `HIGH`.

With that said, if you run it with a 50% duty cycle, then the **average** voltage over several cycles will work out as 50% of `Vcc` (i.e. typically 2.5v). The same applies to other percentages. It's important to note that it's not equivalent to a 'true' analog signal though, and shouldn't be used as such.

As a side note, there are some modified Arduino clones which have a voltage selection switch. These typically let the pins operate at either 3.3v or 5v, and should affect PWM (as far as I know).


body:
+5V

I understand for higher power people driving motors trigger a MOSFET transister which normally can go to 30 volts but this unit here appears to be able to switch 100 volts: https://www.banggood.com/100V-9_4A-FR120N-Isolated-MOSFET-MOS-Tube-FET-Relay-Module-For-Arduino-p-1396252.html this unit is likely to be able handle up to 50 Khz switching frequency (based on the regular MOSFET switching speed). Anything higher you'd need GaN (Gallium Nitride) transisters as used in Class D audio amps. Anyhow 100 volts and 9.4 amps would be 940 watts of DC, or maybe 664 watts of RMS sine wave (ball park), probably I would not trust more than 300 watts through that thing mind.


message:
Should I use an Arduino or not?

I am building an electronic gadget eventually to sell.

I think the Atmega IC is used in the arduino and could this be programmed as easily as the arduino?

I'm wondering if I can use the chip and buy just what I need for my circuit, which would be cheaper as there would be no licensing obligations to the Arduino company

Cheers
Eamonn

body:
Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.

Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.


body:
That's what I do all the time. You might want to buy an ISP programmer to program the chips (e.g. USBASP or usbtinyisp). If you just want to try things out first, you can use your arduino board as an programmer by uploading the ArduinoISP sketch.

The Arduino Uno uses an ATMega328, but you could use other AVR chips too. E.g. the ATMega8, which is slightly cheaper. Or an ATTiny85, which only has a few pins, and is therefor a lot smaller (also cheaper). So you can choose a chip that best fits your needs.


body:
I'd like to second the other posts - if you are familiar with Arduino, going to a stand-alone chip is very easy.

You miss out on the following things: programming via USB, 7-12volts through the power jack, and/or power through USB, reset button, led on pin 13, and the clock. Depending on where you get your Atmel chip, you may also need to set the fuses.

The code is exactly the same, even if you go down to a smaller chip (or larger - whatever suits your project best!).

Programming: I use a FreeTronics ICSP (ISP) to program the chips, and have the 6-pin ICSP header on all my projects for easy reprogramming. This particular programmer has a "slow clock" jumper, because when you get the chip from the Atmel factory, their internal clock runs at 1mhz, too slow to program with the Arduino IDE default settings. You can leave it at 1mhz, if your project doesn't need any more, or change the fuses. You will need an ICSP to set the fuses (see further down). By using an ISP rather than usb, you also save a little memory - you don't need a bootloader (which is pre-programmed on Arduinos, but not when you buy the chips from the factory).

You will need to sort out your own power - this depends on what you need, and what you have. You can use a 5-volt AC-DC power supply ("Wall wart") and plug it into mains. Or, you can power it off USB - if you only use USB for power, you can solder the socket directly on your board. You can use a regulator (which is what the Arduino uses for the 7-12v power socket), or, if running it off a 12v power supply, it might be easier/cheaper to buy a car phone charger from the dollar store, and a lot of the work will be done for you. Also, the power supply doesn't have to be 5v - depending on your application, you might run it from 5.5v to as little as 1.8v, depending on your clock speed. Find the data sheet for the chip you use.

A reset button is very easy to add, if you need it - all it takes is a resistor and a pushbutton. Weather you need it or not, depends on your project.

The same applies to the led on pin 13 - it depends on your project.

Finally, the clock. The Arduino has a 16mhz quartz clock. You can do the same, it only takes 3 components (you will have to set the fuses, see further down). You can use a clock up to 20mhz, giving you a 25% speed boost if you need it (you may need to change some settings, because timing functions like delay depend on the clock speed - your delays will be 25% shorter). Or, you can use the internal 8mhz clock (either at full speed, or as from factory, at 1/8 speed, so you get 1mhz). At 4mhz or less, you can run the Atmega at 1.8 volt, or 0.7 volt for the "pico power" chips.

As I have mentioned, you may need to set the fuses to the correct value. The best idea is to go to http://www.engbedded.com/fusecalc/ to work out what fuse settings you want. Specific things to look for: the clock source (internal or external? what speed?), divide clock by 8 internally, and brown-out detection (Arduino chips turn themselves off when the power goes below 4.3v). Warning: setting wrong fuses may set your chip so it is very difficult to fix. You can set the fuses using an ISP; if the clock speed is very slow (I think < 4mhz? which it is when it comes from the factory), then you will have to "slow program" - some ISPs have a "slow program" jumper, but you can use an option to avrdude to do the same - I think it's -B e.g. -B10).


body: Arduino of course started as a prototyping platform. Build this first, get it working, then move to a circuit board of your own design with the same chip and go from there. However, as the cost of all the components and really the boards themselves drops, I frequently find my self thinking, why not just use the board. Obviously if you are going to market something, having a full arduino in there might be a bit much, but if its just for your own application, I don't see any reason why you wouldn't just buy boards and use them as necessary.


body:
Thanks for all the replys. I have a lot to learn as I only heard of arduino a month ago.
Didn't have a reason before.
My arduino hasn't arrived yet so I made my basic circuit with components on a breadboard.
I think I will need the arduino as I need some monitoring in the circuit.

Thanks again much appreciated.
Eamonn


body:
Since you are already using Arduino, I think you not should use atmega, but must! To prevent future headaches, since you look new to electronics, I HIGHLY recommend to check for app notes by Atmel. Just type it "Atmel app notes" at google and you will find a lot of useful tips. Some of them are start to routing by crystal resonator, them GND and Vcc. Use, if possible, on each IC a 100nF ceramic SMT capacitor nearest as possible and another one of 10uF (can be electrolytic) on most robust ones (like microcontroler). Always route opposite signals (like Vcc and GND) tied together with the same size to low its impedance... If you are doing with high inductance loads you should use another sorce (and maybe also a diode as rectifier or an optocoupler).

There's a lot of good practices and if you want to sell your work, you really have to study them.

Good luck! Also look for the electronics SE


message:
Arduino Raspberry Pi USB Communication

I am trying to connect an Arduino and Raspberry Pi over USB.  I would like to send serial commands, just like the serial monitor in the Arduino IDE.  I know how to do this on the Arduino end but I'm not sure how to send/receive serial communication on the Pi end.  Ideally the solution would utilize Python.

body:
You would be better to ask this on http://raspberrypi.stackexchange.com

You can use program `minicom` on the Pi; this is a terminal program like the serial monitor in the Arduino IDE, and of course you can use Arduino IDE on the Pi.

If you look at the Pi site you will see lots of Python serial communication programs.


body: Why do you want to use the USB port on the Pi? Isn't it easier to connect the Arduino directly to the UART pins (Pins 8 and 10) on the PI and then read out the UART in your python programme?


body:
You will need PySerial to accomplish this. A tutorial on interfacing Arduino and the RPi using a usb can be found [here][1]

  [1]: http://blog.oscarliang.net/connect-raspberry-pi-and-arduino-usb-cable/


message:
How to save the SHA256 with HMAC into a variable instead of serial print?

#include "sha256.h"

    uint8_t hmacKey1[]={
    0x65,0x63,0x73,0x74,0x61,0x63,0x79
    };

    void printHash(uint8_t* hash) {
    int i;
     for (i=0; i<32; i++) {
       Serial.print("0123456789abcdef"[hash[i]>>4]);
       Serial.print("0123456789abcdef"[hash[i]&0xf]);
      }
     Serial.println();
    }

    void setup() {
       uint8_t* hash;
       uint32_t a;

     Serial.begin(9600);

     // HMAC tests
      Serial.println("Test: RFC4231 4.2");

    Serial.print("Result:");
    Sha256.initHmac(hmacKey1,20);
    Sha256.print("Hi There");
     //My TRIAL ATTEMPT
     int i;
     for (i=0; i<32; i++) {
     hash[i] =Sha256.resultHmac();
     Serial.println(hash[i]);
     }
    }

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays

     sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite [here][1]

Heading
=======

  [1]: https://github.com/spaniakos/Cryptosuite "here"

body: The hash is a series of binary digits. They are usually represented in hexadecimal form for readibility. You are just printing out the raw bytes, which will give a series of random ASCII characters. Some of these may be control characters which interfere with serial port communication.


body:
My solution was making a new function that returns a String with the hash

    String GetHash256(uint8_t* hash) {
     char tmp[16];
     String sHash256 = "";

     int i;
     for (i=0; i<32; i++) {
      sprintf(tmp, "%.2X",hash[i]);
      sHash256.concat(tmp);
     }

     return sHash256 ;
    }


message:
New to Arduino: Should I learn C, C++ or both (C & C++)?

From what i've researched here is my thoughts on both

1. C++
I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff.  Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial

Notice that it uses the C++ syntax.

I also see arduino projects on github written on C++
https://github.com/search?l=C++&q=Arduino&type=Repositories&utf8=✓

2. C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).

Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

body:
Arduino supports c++, but does not support many of the standard libraries.
The vast bulk of the functions in the Arduino IDE are c functions.

You can do almost everything in c, except for a few advanced items.

Due to the limited c++ libraries it will be difficult to learn c++ on Arduino; indeed it is not the ideal platform to learn c, as most of the tutorials will not work (because there is no I/O on Arduino).


body:
The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as `printf` and `malloc`) can be used from C++ programs.

The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.

Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.

As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.

It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.


body: For starting out? I would say neither. The arduino IDE is based on a programming language called processing. Which you can look at. Honestly, if you have done any programming in the past you will be fine for the basics. The advanced stuff might make you look at working with c++ files. But there is nothinging overly complex there. A lot of the add-on hardware that you can purchase comes with existing arduino libraries. Use these as a baseline.


body:
@ConnorWolf Way too kind.

Arduino is based on Wiring, which is based on Processing, which is a kludge of Java, resembling C++ running on an embedded prototyping platform ill suited for learning programming by any Definition.  Many libraries half written and confusing, implementing only as much as the original author needed, not the entire spec (SPI being a great example).

Get a Pi for the same price, at least it is an end user computer for poor people.

Besides, if you have something that can run the Ardunino IDE why are you learning to program on an Arduino? You need to be proficient in C or C++ before you attempt anything for real on an Arduino. Blinking lights is fine, beyond that, good luck.

Learn C or C++ (preferred as it is newer) on what you have, then start using the Arduino. Eclipse or Microsoft Visual Studio Community are both free and support both languages. (Both also support Arduino development when the time comes, avoid the Arduino IDE it is terrible). There are enough samples for either to keep you busy for a long time. Embedded programming REQUIRES understanding of low level hardware and IS NOT suitable for learning.

Forget modern debugging. Paid engineers grumble when they have to do it and it cost a decent price for the enabling hardware. Stick to the old fashioned printf debugging style.


message:
Error code 10 for arduino device driver

How can I fix error code 10 while installing the device driver for Arduino in Windows 8.1?
The LED on the board is blinking after connecting it to the laptop, so I don't think so that the board is damaged. What is the cause of this issue?

body:
First of all, test if you even need a new driver. On Windows, the Arduino drivers for my Uno and my Mega were installed automatically by Windows. I'd advise to restart your computer, ***using the actual restart button, not manually shutting off and turning on... this is very important with Windows 8.1 and its Hybrid Boot default!!!*** A normal reboot doesn't fully reload all of the drivers. Next, open the Arduino IDE, and then see if you can successfully upload the "blink" example sketch.

If that doesn't work, let's try something else.

First of all, open up Device Manager and find your device:

> ![Device manager][1]

It should be under the *Ports (COM & LPT)* section. After that, right click and click on *Properties*.

> ![Right click menu][2]

Then, let's go to the *Driver* tab and click on *Update Driver*. Then, click on *Search Online Automatically for this Driver.*

> ![Properties Window][3]

First, try seeing if an automatic update finds any drivers capable. If not, I've found previously that there's sometimes a *Reinstall* or *Fix* button somewhere if the driver isn't working correctly.

In addition, you can also update it manually using Device Manager. Instead of clicking on *Search Online Automatically for this Driver,* click *Browse My Computer Manually.* For me, there was a Mega driver under the *Let me pick from a list of compatible device drivers on my computer* and there was a Mega driver for me (although I don't know if that's because I have it installed already).

You can also use that same menu to point it to the location of the installation of the Arduino IDE and it will search for any compatible drivers.

Rolling back the driver is another option if the Arduino IDE tried to install a faulty driver that somehow got corrupt over a working driver installed by the computer.

The last thing I would suggest trying as a last resort is using the *Uninstall Driver* button and then trying to reinstall the driver manually. I've never done this with an Arduino board, although there have been some times with other drivers that this has helped to remove the faulty driver.

If none of this works, it may be a faulty board.

  [1]: https://i.stack.imgur.com/v8Q0A.png
  [2]: https://i.stack.imgur.com/RUPKR.png
  [3]: https://i.stack.imgur.com/FHjqo.png


body: After wasting a huge amount of time trying get the Arduino IDE to upload the sketches to my new starter robot I came across the following document in the Arduino Website :"Guide to the Arduino Leonardo and Micro"... In this document they explain how the serial port communication work on the leonardo (which is the ME-Baseboard from MakeBlock)...They state that auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it... Whatever that means... I went into the makeblock driver setting (under windows 8.1 device manger) and change the baud rate to 1200... Surprise surprise... all  works fine now, I can compile and upload the sketches for the starter robot... What frustration !!!! And for the people at Makeblock... I have been trying to create a community userid and while the system say that it will send me an email, it never does !!!


body: I am sad to report that what actually happened it that changing the baud rate also led to a change in board type in the arduino IDE... So the sketch did compile and load but assuming that the board is a UNO.  End result, still facing same problem and robot behave a bit erratically probably because the upload was not performed for a leonardo board.  I have tried counless times with countless different procedures on an acer laptop with Windows 8.1, an acer laptop with Windows 7 and a surface pro with Windows 7.  Same problem everywhere.  If someone from Makeblock read this blog, I would appreciate if you could send me the validating email so I engage this troubleshooting process on their community discussion board.


body:
I had the same issue. The drivers, which shipped with Arduino IDE didn't work for me.

Actually, the reason was that I was using Arduino UNO clone. And it required another driver.
This video helped me to find the answer: https://www.youtube.com/watch?v=r9MGJ16pRLc

In my case I had to install the CH340 chipset usb driver. The driver can be downloaded from this page: http://www.microcontrols.org/arduino-uno-clone-ch340-ch341-chipset-usb-drivers/

After I installed CH340 driver, the upload from Arduino IDE started working perfectly.


message:
Arduino Based Home Automation System

I am working on my project of home automation system using Arduino GSM SIM900 & four channel relay module. I am facing a problem in my code. Can any one help me on this, SMS is receiving but its not switching the relays?

    #include <SoftwareSerial.h>

    // EN: String buffer for the GPRS shield message
    String msg = String("");
    // EN: Set to 1 when the next GPRS shield message will contains the SMS message
    int SmsContentFlag = 0;
    //control pins of relay.
    int relay_a=4;
    int relay_b=5;
    int relay_c=6;
    int relay_d=7;

    // EN: Code PIN of the SIM card (if applied)
    //String SIM_PIN_CODE = String( "XXXX" );

    void setup()
    {
      Serial.begin(19200);                 // the GPRS baud rate
      // Initialize  PINs
      pinMode( 4, OUTPUT );
      pinMode( 5, OUTPUT );
      pinMode( 6, OUTPUT );
      pinMode( 7, OUTPUT );
      digitalWrite( 4, LOW );
      digitalWrite( 5, LOW );
      digitalWrite( 6, LOW );
      digitalWrite( 7, LOW );
     Serial.println( "AT+CMGF=1" );
     delay(200);
    }

    void loop()
    {
        char SerialInByte;
        if(Serial.available())
        {
            SerialInByte = (unsigned char)Serial.read();
           delay(5);

            // -------------------------------------------------------------------
            // EN: Program also listen to the GPRS shield message.
            // -------------------------------------------------------------------
           // EN: If the message ends with <CR> then process the message
            if( SerialInByte == 13 ){
              // EN: Store the char into the message buffer
              ProcessGprsMsg();
             }
             if( SerialInByte == 10 ){
                // EN: Skip Line feed
             }
             else {
               // EN: store the current character in the message string buffer
               msg += String(SerialInByte);
             }
         }
    }
    // EN: Make action based on the content of the SMS.
    //     Notice than SMS content is the result of the processing of several GPRS shield messages.
    void ProcessSms( String sms ){

      if( sms.indexOf("ona") >= 0 ){
        digitalWrite( relay_a, HIGH );
      }
       if( sms.indexOf("onb") >= 0 ){
        digitalWrite(  relay_b, HIGH );
      }
       if( sms.indexOf("onc") >= 0 ){
        digitalWrite(  relay_c, HIGH );
      }
      if( sms.indexOf("ond") >= 0 ){
        digitalWrite(  relay_d, HIGH );
      }
      if( sms.indexOf("offa") >= 0 ){
        digitalWrite(  relay_a, LOW );
      }
      if( sms.indexOf("offb") >= 0 ){
        digitalWrite(  relay_b, LOW );
      }
      if( sms.indexOf("offc") >= 0 ){
        digitalWrite(  relay_c, LOW );
      }
      if( sms.indexOf("offd") >= 0 ){
        digitalWrite(  relay_d, LOW );
      }
    }
    // EN: Request Text Mode for SMS messaging
    void GprsTextModeSMS(){
      Serial.println( "AT+CMGF=1" );
    }

    void GprsReadSmsStore( String SmsStorePos ){
      Serial.print( "AT+CMGR=" );
      Serial.println( SmsStorePos );
    }

    // EN: Clear the GPRS shield message buffer
    void ClearGprsMsg(){
      msg = "";
    }

    // EN: interpret the GPRS shield message and act appropiately
    void ProcessGprsMsg() {
      if( msg.indexOf( "Call Ready" ) >= 0 ){
       //  Serial.println( "*** GPRS Shield registered on Mobile Network ***" );
         GprsTextModeSMS();
      }

      // EN: unsolicited message received when getting a SMS message
      if( msg.indexOf( "+CMTI" ) >= 0 ){
       //  Serial.println( "*** SMS Received ***" );
         // EN: Look for the coma in the full message (+CMTI: "SM",6)
         //     In the sample, the SMS is stored at position 6
         int iPos = msg.indexOf( "," );
         String SmsStorePos = msg.substring( iPos+1 );
       //  Serial.print( "SMS stored at " );
      //   Serial.println( SmsStorePos );
         // EN: Ask to read the SMS store
         GprsReadSmsStore( SmsStorePos );
      }

      // EN: SMS store readed through UART (result of GprsReadSmsStore request)
      if( msg.indexOf( "+CMGR:" ) >= 0 ){
        // EN: Next message will contains the BODY of SMS
        SmsContentFlag = 1;
        // EN: Following lines are essentiel to not clear the flag!
        ClearGprsMsg();
        return;
      }

      // EN: +CMGR message just before indicate that the following GRPS Shield message
      //     (this message) will contains the SMS body
      if( SmsContentFlag == 1 ){
     //   Serial.println( "*** SMS MESSAGE CONTENT ***" );
     //   Serial.println( msg );
     //   Serial.println( "*** END OF SMS MESSAGE ***" );
        ProcessSms( msg );
      }

      ClearGprsMsg();
      // EN: Always clear the flag
      SmsContentFlag = 0;
    }

body:
I think you'd want to include a call to `ClearGprsMsg()` right before the line `GprsReadSmsStore( SmsStorePos );`.

Then, `msg += String(SerialInByte);` is probably wrong, see for example http://arduino.cc/en/Tutorial/StringConstructors:

    // using a constant integer:
    stringOne =  String(13);
    Serial.println(stringOne);      // prints "13"


message:
Program button to switch between two values

There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.

So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.

I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

body:
Pseudocode:

    value = 0
    if button is pressed:
      value = 1 - value


body:
It sounds like you are using a number as a boolean (true/false) value.

You might consider using a a boolean instead.

    boolean value = false;
    if button is pressed {
        value=!value
    }
    if value {
        // do something here.
    }

You can set it to `true` or `false`, or change it to it's opposite (with `value=!value` as shown above). You can also do `if value` or `if !value` ("if not value") - these are equivalent to `if value=true` or `if value=false`.


message:
How to get Baite Pro Mini working?

I have recklessly bought the [Baite Pro Mini][1] and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.

I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

1. How exactly should I connect the Arduino device to the computer?
I have a converter USB to serial pl2303HX: ![PL2303HX][2] which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

-------

edit:

Here is the description of pins of the pl2303HX: [![Pin layout of PL2303HX device][3]][3]
<sub>(source: [fasttechcdn.com](https://img.fasttechcdn.com/123/1230400/1230400-3.jpg))</sub>

I did connect it the following way:

    Baite Pro Mini      pl2303HX
    GND
    GND  <------------> GND
    VCC  <------------> +5V
    RXI  <------------> TXD
    TXC  <------------> RXD
    DTR

I also tried the permutation with different `GND` pin. I also tried pressing the `reset` button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.

I believe my failure might have something to do with the absence of `DTR` pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

2. Which exactly [Arduino bootloader][4] do I need?

3. How to connect USBASP to the Beite Pro Mini?

  [1]: https://www.aliexpress.com/item/1432585134.html
  [2]: https://i.stack.imgur.com/zARZh.jpg
  [3]: https://i.stack.imgur.com/FL8Xr.jpg
  [4]: https://docs.arduino.cc/hacking/software/Bootloader

body:
I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).

I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.

I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.

Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!

You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)


body:
Your connections are incorrect if you are "straight through" connecting.
Gnd & Vcc are adjacent on the processor board and separated by 2 pins on your converter.

If you find Gnd, Vcc, TX, RX on USB module and processor then you should

 - Connect Gnd to Gnd

 - Connect Vcc to Vcc

 - Connect ........TXD to RXD and
     ........................RXD to TXD

 - Ensure that you have the correct USB converter drivers loaded.

A reset does not seem to be needed when using the Baite processor AND Baite USB module.

_______________

I have a number of Baite Pro Minis working perfectly.
In my experience (3 or 4 sales so far) Baite's products are usually of acceptable quality .

Connecting "almost any plausible permutation of the wires" is a fine way to attempt to destroy the converter and/or the BPM. Logical connection should work - if you have not damaged something.

Connect as Ignacio says.
Note that you connect **BPM-TX to USB-converter-RX**, and RX to TX and **NOT RX to RX). The BPM has connections shown on the PCB.

![enter image description here][1]

Baite provide this diagram

![enter image description here][2]

Your converter module has a different pinout which needs to be allowed for.

![enter image description here][3]

You must also have drivers on your system for the USB to serial bridge IC used on your converter. The Baite converter uses a CH340G IC. Your may or may not.

  [1]: https://i.stack.imgur.com/XWl8i.jpg
  [2]: https://i.stack.imgur.com/Acic3.jpg
  [3]: https://i.stack.imgur.com/BsLyx.jpg


message:
Loading local libraries

I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?

So this is my situation;

    project.ino
    libs/
      MyNewLib/
        MyNewLib.h
        MyNewLib.ccp

Now my question is: how can I include my custom library? I've tried several variations on this;

    # project.ino

    #include <libs/MyNewLib/MyNewLib.h>
    #include "libs/MyNewLib/MyNewLib.h"
    #include <./libs/MyNewLib/MyNewLib.h>
    #include "./libs/MyNewLib/MyNewLib.h"

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.

Cheers.

**UPDATE**

I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

body:
I am just back to using the arduino after some time away and am somewhat bewildered
by similar issues and confused by different info from different sites and for different
versions of the ide.

What I have found is that if you have a sketch in a directory, then shut down the Ide you can drop .h, .cpp... files in the directory and the ide, when restarted, will open them with the sketch.

Include them by using simple quotes on the file names, no path, no angle brackets.

I am sure this is only part of the full answer, but it has gotten me started.


body:
The Arduino plugin for Visual Studio supports local libraries you can find the plugin [here][1]

  [1]: http://www.visualmicro.com


body:
As far as I know, you can include your libraries from a custom location by using their absolute path.

Since absolute paths could be boring from a code-portability point of view, you could define some macros to get the absolute path from a given relative one. In this way, you would just have to fix the 'project root' path when passing from a device to another.

Define your project's root folder :

        #define PROJECT_ROOT C:\path\to\your\project\folder

Define a relative-to-absolute macro 'transformation' :

        #define TO_STRING(s) #s
        #define ABSOLUTE_PATH(root, relative_path) TO_STRING(root\relative_path)
        #define RELATIVE_PATH(library) ABSOLUTE_PATH(PROJECT_ROOT, library)

Include your files using the relative path :

        #include RELATIVE_PATH(some\file\relative\path.h)
        #include RELATIVE_PATH(another\file\relative\path.h)

I hope it will be useful.


body:
The simplest way I've found to do this is store the libraries in your local sketch directory and create a symbolic link in the [HOME]/Arduino/libraries directory.  Then you can check them in to Git easily with your sketch/project and Arduino's still happy because the libraries are accessible in the global folder.

Maybe even create an install script that creates these links automatically and check that into Git too.


body:
I recently tested this local library structure. It works with:

    #include "libs/MyNewLib/MyNewLib.h"

The Arduino IDE 1.6.7 build pre-processing will even pick up the source code for the library.

Cheers!


body:
Another really bad fix - create a file called `libraries.cpp`, which contains:

    // force the linker to build the libraries
    #include "libraries/LIB1/src/FILE1.cpp"
    #include "libraries/LIB1/src/FILE2.cpp"
    #include "libraries/LIB2/src/FILE1.cpp"

Of course, this only works if the library does not itself contain any includes...


body:
Okay, here is how it works, and I checked it to make sure.

Sure you can use hard paths, but every programmer _hates_ using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.

You will find the conclusion is NOT intuitive at all. Cutting to the chase: *relative paths **don't** work correctly.* Now, why?

But first, let me explain why anyone would want to place program files _outside_ the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.

As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the *library*, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.

In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does *not* start in your project directory. Instead it starts in "./libraries"! So the resulting path is:

`#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp`

In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.


message:
Measure total microcontroller current?

So I have a Duemilanove board and am utilizing 7 output pins, I power a Pixy camera and pan/tilt servos from the ICSP header, i also power an HC-SR04 sonar snsor directly from the board.

Of those 7 output pins, 4 are PWMs for the motors (don't ask why), 3 are for servo control (tower pro mg-995)

when I try to output these 7 pins simultaneously things don't work, i get "components at a time" behavior. Like servos turn first, then the motors spin (servos stopped).

Initially we thought it must be a power supply problem (8 1.2v NiMh bat series) which powers the l298n h bridges (two of them) and also powers the board and servos. But now im starting to fear that it's the board itself and that it can't handle simultaneous outputs.

I've read from [here (method #10)][1] that taxing the board more than 200mA is a problem. But what exactly happens if you do just that? And is my case exactly like this one? If so, how to fix it?

+ Edit +

Here's how the circuit looks.
![enter image description here][2]

**Edit:**

Yes i do think there is a need for decoupling capacitors but im not sure where to put them. They dont seem to work. The bounty goes to the best answer on the proper decoupling of this circuit.

**Edit:**

Here's some images on the Pixy camera

![enter image description here][3]
![enter image description here][4]

**Edit:**

Actually from the original problem I noted when I posted this question, things don't work as expected. WHen the big servos move, the pan/tilt camera don't move when they are supposed to, or the motors briefly stop. I'm wondering if is also an Arduino idiosyncrasy because when I don't run the `servo.attach(servo_pin)`  code everything works fine.

  [1]: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/
  [2]: https://i.stack.imgur.com/ccwHt.jpg
  [3]: https://i.stack.imgur.com/DznXd.jpg
  [4]: https://i.stack.imgur.com/Vhond.jpg

body:
My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.

The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.

You could try a different Servo library.

This [article][1] is useful to understand the timer/pwm/pin relationships

  [1]: https://stackoverflow.com/questions/18705363/arduino-uno-pwm-pins-conflict


body:
Here are a few suggestions that might help:

1. **Provide its own power supply to Arduino UNO**, so that no voltage drop can occur on the board itself due to high energy consumers as servos and DC motors. As someone suggested in an answer, a voltage drop on Arduino MCU may trigger the Brown-Out Detection (BOD) which will stop the MCU until voltage rises up again, above a given threshold. You could for instance power the UNO with a 9V battery (or the equivalent 7.2V rechargeable pack). Those batteries don't have much energy but it should be OK as long as they are not used for powering motors. Of course, then you'll have to remove the `Vin` wire to your 8-batteries pack.

2. **Add decoupling caps** (between **V+** and **GND**) as near as possible to every energy consumer: that means adding decoupling for each **motor driver** power-in pins, for each **servo** power pins, and ALSO for the **HC-SR04** sonar sensor (in my experience, it can drop voltage a lot, more than you could expect); note that you may also need decoupling for the **camera**, but I'm not sure on this one, because I have never used one yet.

**Note on decoupling caps**:

The value of caps to use depend on many factors, which would be too long to explain here (and I admit that I don't necessarily understand each of these); but typically, you would use **a small cap (100nF)** when you expect **fast (and short) voltage drops**, and **a bigger cap (>=10uF)** when you expect **longer voltage drops**.

When you don't know, you can just experiment and see what works best.

Using both kinds of caps at the same time (in parallel) does no harm (I have done this in several situations).

For higher caps, you will have to use an **electrolytic cap**, which is polarized: **do make sure that you wire them correctly (+/+, -/-) otherwise they may blow up**.

Also, choose a **breakdown voltage** for the cap that is much above (I'd say 50% above is fine) your power voltage; **16V** is a common value that would fit your needs; of course, you can use higher breakdown voltages as well.


body:
From the [Servo library documentation](http://arduino.cc/en/reference/servo):

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

This is, as has been suggested, because of conflicting usage of the timers. You should just move your DC motors to other PWM-capable pins.


body:
I know this is after the fact but "Back EMF " is more than likely the issue with the starting and stopping of the servo's and most likely the DC motors.
The power supply could receive a pulse 4 to 5 times its supply voltage. The cpu could be scrambled or reset. Or pulses sent to servos corrupted. Divert the energy of a motor's collapsing magnetic field back into itself with a diode, cathode to the positive supply rail. Basically any time you stop or start a motor its magnetic field has to go somewhere.Digital hates that.


message:
Programming arduino with Objective-C

Can you use `clang`, with `--mpu=arm`, etc. and `avrdude` to program an Arduino Due (Arm Cortex M3)?

body:
Theoretically, many things are possible. There is an easy way to code Arduino on Xcode with EmbedXCode (http://playground.arduino.cc/Main/EmbedXcode), but in C and CPP.

You need a compiler that will compile your Objective-C to for the AVR (if you are using an AVR-based Arduino), this may be difficult to find. Once your code is compiled, then you need to upload it to the Arduino.

So in any reasonable means, it is at least very challenging.


body:
Simple version: No, you cannot program Arduino using Objective-C.

Long version:
The Arduino IDE uses avr-gcc as it's compiler, and avr-gcc is a C/C++ compiler, not an Object-C compiler. The Arduino libraries are written in C/C++.

There are other compilers that exist for _AVR_ processors, and so it is possible to use other languages for the _AVR_.

However, if you switch to a different compiler for your code, you will not be able to use the Arduino libraries with it, because they are written in C/C++ for the avr-gcc compiler. (It may be possible to compile the Arduino libraries with avr-gcc, and then link them to your code using external language linking methods, but that could be a significant challenge.)

Also, I do not know of any existing Objective-C compilers for AVR; it's possible one may exist, but after a quick web search, I didn't find any.


body:
It can be done, however, it is inadvisable. In order to implement this, one must implement the Objective-C runtime, which, though not insurmountable, is very near insurmountable as far as difficulty is concerned. Perhaps someday some brave soul will see fit to grace the world with their custom Arduino Objective-C runtime, but until that day, the rest of us mere mortals have naught to do but wait for the coming of the Objective-C prophet.

If there are any brave souls in the audience who wish to take on this ultimate challenge, then let them. But otherwise, keep the code in C and hold your peace.


message:
How Do I Send An Email WITHOUT An Ethernet or WiFi Shield

I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

body:
If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.

You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.

Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.


message:
ISR executes even though an interrupt is not triggered

I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.

    typedef void (*funcptr)(void);
    TPrioQueue *queue = NULL;

    void int1ISR() {
      if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
        enq(queue, (void*) int1task, 1);
    }

Next, I execute the function in loop() by:

    typedef void (*funcptr)(void);

    void loop(){
      funcptr func = (funcptr) deq(queue);
      if (func != NULL)
        (*func)(); // Stuck in a loop
    }

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?

When I remove the line below, the ISR works properly.

    enq(queue, (void*) int1task, 1)

The relevant sections of the code:

    int debounce(unsigned long *debTimer) {
      unsigned long tmp = *debTimer;
      unsigned long currTime = millis();

      if ((currTime-tmp) > 500){
        *debTimer = currTime;
        return 1;
      }
      else
        return 0;
    }

    // Flashes LED at pin 6 five times at 2 Hz
    void int1task(){
      for(int i=0; i<5; i++){
        digitalWrite(6, HIGH);
        delay(250);
        digitalWrite(6, LOW);
        delay(250);
      }
    }

    void setup() {
      pinMode(6, OUTPUT);
      attachInterrupt(1, int1ISR, RISING);
      Serial.begin(115200);
    }

[Code I used for the queue](https://www.dropbox.com/sh/l6byqdd4r32rapd/AAD8Pxj7iiSoRjQvksr_U3o8a?dl=0)

Here is the [schematic][1] I am using:

![Enter image description here][2]

  [1]: https://www.dropbox.com/s/51f8174815zycrg/schematic.pdf?dl=0
  [2]: https://i.stack.imgur.com/WJRhr.png

body:
ISRs have flags, typically an enable flag and a pending flag.

The enable flag needs to be set true for the interrupt to occur at all.

The pending flag is set when the interrupt event occurs.

Within the interrupt function, the pending flag must be cleared,

otherwise the the interrupt function will immediately be executed again (and again and again and ...)


body:
After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the `enq` and `deq` functions, which is a **must-have** if you use any of these functions from **within an ISR**.

I would suggest the simplest changes to these functions as follows:

    void enq(TPrioQueue *queue, void *item, int priority)
    {
        TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

        if(newEntry != NULL)
        {
            newEntry->item=item;
            newEntry->prio=priority;
            newEntry->prev=NULL;
            newEntry->next=NULL;

            // Protect against concurrent accesses starting here
            uint8_t sreg = SREG;
            cli();
            if(queue->head==NULL)
                queue->head=newEntry;
            else
            {
                // Find insertion point.

                // First special case: Item at head has lower priority
                if(queue->head->prio > newEntry->prio)
                {
                    // Insert item at the start of the queue.
                    newEntry->next=queue->head;
                    queue->head->prev=newEntry;
                    queue->head=newEntry;
                }
                else
                {
                    // Find your insertion point
                    TPrioQEntry *trav= queue->head;

                    while(trav->next!=NULL && trav->prio < newEntry->prio)
                        trav=trav->next;

                    newEntry->prev=trav;
                    newEntry->next=trav->next;
                    if(trav->next != NULL)
                        trav->next->prev=newEntry;

                    trav->next=newEntry;
                }
            }

            queue->itemCount++;
            // Protect against concurrent accesses stops here
            SREG = sreg;
        }
    }

    void *deq(TPrioQueue *queue)
    {
        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        // Return NULL if queue is empty
        if(queue->head == NULL)
        {
            // Protect against concurrent accesses stops here
            SREG = sreg;
            return NULL;
        }

        void *ret=queue->head->item;
        TPrioQEntry *tmp=queue->head;

        if(queue->head->next!=NULL)
            queue->head->next->prev=NULL;

        queue->head=queue->head->next;
        free(tmp);

        queue->itemCount--;

        // Protect against concurrent accesses stops here
        SREG = sreg;

        return ret;
    }


body:
Although you did not clearly mention nor show your wiring, it is possible the problem comes from here.

Barring **real concurrency issues** with your queue implementation, which I already mentioned in another answer, for which fixes have to be implemented anyway, there are two potential wiring problems in your circuit:

1. You use **INT1** interrupt; that means you must connect your button to **PIN 3** for a UNO, any other pin won't work.
2. You did not specify `pinMode(3, INPUT_PULLUP)` in your `setup()`, which means **you MUST use an external pullup resistor** to force a `HIGH` value, and connect the other pin of the button to `GND` (or conversely: put a pulldown resistor and wire the other pin to `5V`); otherwise, while the button is left unpressed, you will have a **floating input**, which means its value will vary randomly between HIGH and LOW, triggering your `int1ISR` many times when you don't expect it.

The simplest way to solve point 2 (floating input) is to use internal pullup resistors:

    void setup() {
      pinMode(3, INPUT_PULLUP);
      pinMode(6, OUTPUT);
      attachInterrupt(1, int1ISR, RISING);
      Serial.begin(115200);
    }

and connect one button pin to Arduino PIN 3, and the other button pin to `GND`.

That will remove floating input and its consequences.


message:
Stable frequency generation

I'm trying to work out the best way to generate a stable frequency with my Uno R3

I'm using interrupts to generate an approximately 40KHz frequency which drives some ICs/MOSFETs to effectively generate 40KHz AC which powers a transducer.

I need to receive the frequency at a second transducer and calculate any frequency shifts.

 - The problem is that the generated frequency drifts a little bit off of 40KHz. Is there a way to lock it in at 40KHz via software? I'm receiving approximately 40KHz output (as measured using PicoScope software) with this code:

        #define LEDPIN 13
        void setup()
        {
        pinMode(LEDPIN, OUTPUT);
        // initialize Timer1
        cli();          // disable global interrupts
        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B
        // set compare match register to desired timer count:
        OCR1A = 24;
        // turn on CTC mode:
        TCCR1B |= (1 << WGM12);
        // Set CS11 for 8-bit prescaler:
        TCCR1B |= (1 << CS11);
        // enable timer compare interrupt:
        TIMSK1 |= (1 << OCIE1A);
        // enable global interrupts:
        sei();
        }

        void loop()
        {
        // main program
        }

         ISR(TIMER1_COMPA_vect)
        {
        digitalWrite(LEDPIN, !digitalRead(LEDPIN));
        }

 - If there isn't a way to lock it in, is there atleast a way for the Uno to accurately display/store the frequency of the signal it generated at a given time?

   Or is this not plausible because the Uno would "think" it is generating 40KHz?

Thanks for  any hints or suggestions.

**EDIT:** @RussellMcMahon pointed me in the right direction for this, so I accepted his answer. However, I wanted to share my final code and my misconceptions I encountered. Hopefully this will assist someone else in the future. I'm obviously by no means an expert, and I will try to not give any misleading information here.

My original goal was, although poorly stated, to generate as clean a 40KHz PWM with 50% duty cycle as possible.

Problems with my original code above were:

 - Using an 8-bit pre-scaler
 - Using an interrupt
 - Using digitalWrite()

**8-Bit Pre-Scaler**

      The problem here was that the counter only ticked over once every 8 clock cycles. *16MHz clock / 8 (pre-scaler) = 2MHz clock* When I asked one of my professors about this he stated something along the lines of "a cycle could be missed due to an interrupt, and would cause it to wait 7 more cycles to 'tick'". Indeed I was originally using interrupts, and when we did the calculations it seemed like it could plausibly cause up to a a 1KHz swing at 40KHz.

      To rectify this I took out the pre-scaler, and ran straight at the base clock speed to increase resolution.

**Using an interrupt**

      Essentially the interrupt could cause clock cycles to not be counted, further complicated by using an 8-bit pre-scaler. If one clock cycle was missed, with a 2MHz clock (after pre-scale), you add 5E-7 seconds to the counter, changing the output frequency.

**Using digitalWrite()**

      The digitalWrite function is pretty slow. I'm not a guru, but I read this in multiple places and there seems to be a good comparison of methods here: [Digital Pin Oscillation][1] To get around this problem it had been suggested I toggle a single bit, which is what I set out to do in my final code. (It is worth noting, now that I've completed this project, that the previous link also makes reference to a [library addition][2] for faster digitalWrite/Read/etc....)

I went through a few variations and scrounged code from all over, and made a couple working examples but they didn't do it the way I wished. I believe part of the project I based this version off of was a melding between a previous version I had working and a class example I found online.

Without further ado, I present the code that took me an embarrassing amount of time to write from numerous sources... I really should tinker with this stuff more often:

    #include <avr/io.h>
    #include <avr/interrupt.h>
    void setup()
    {
    //Disable interrupts
    cli();
    // Clear Timer1 registers
    TCCR1A = 0;
    TCCR1B = 0;
    // Set OCR1A (TOP): 16MHz/40KHz /2 = 200 steps.
    // Divide 200 by 2 = 100 because waveforms are centered around OCR1A (because toggle)
    OCR1A = 100;
    // Configure Timer/Counter 1
    // Select P & F Correct PWM Mode, and OCR1A as TOP. Use WGM Bits 10 and 13.
    // WGM Bits are in TCCR1A and TCCR1B. Any previous settings are cleared.

    // Enable COM1A0 to toggle OC1A on compare match
    TCCR1A = _BV(WGM10) | _BV(COM1A0);
    // CS10 to enable base clock without pre-scale
    TCCR1B = _BV(WGM13) | _BV(CS10);

    //Set OC1A (Digital Pin 9 / Port B Pin 1) to output
    DDRB |= _BV(1);
    }

    void loop()
    {
    }

 For reference, here is the clock frequency formula. In this instance, I had to divide the result by 2 again since I am toggling.

![Clock frequency formula](https://i.stack.imgur.com/g1u6n.png)

Resultant output verified by PicoScope:
![Picoscope Oscilloscope Trace](https://i.stack.imgur.com/NdgbK.png)

In closing, you will notice that it isn't exactly 40KHz. Research turned up that the Arduino Uno makes use of a less accurate ceramic resonator to clock the ATMEGA328P (although a 16MHz crystal oscillator is onboard to clock the USB). To further increase accuracy in a generated signal will require the Arduino to be driven with an external clock source.

  [1]: http://www.billporter.info/2010/08/18/ready-set-oscillate-the-fastest-way-to-change-arduino-pins/
  [2]: http://forum.arduino.cc/index.php/topic,46896.0.html

body:
You can use a timer/counter to output a square wave signal of your choosing without processor intervention or use of interrupts.

In data sheet
[**"ATmega48A/PA/88A/PA/168A/PA/328/P"Atmel-8271I-AVR- ATmega-Datasheet_10/2014**](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)

page 142  it says

 - The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. **The result of the compare can be used by the Waveform Generator to generate a** PWM or **variable frequency output on the Output Compare pins (OC2A and OC2B).** See ”Output Compare Unit” on page 143 for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which **can** be used to generate an Output Compare interrupt request.

The interrupt CAN be generated and used but is optional.
It looks like relevant material extends as far as page 159.


body:
I know this thread may be dead but if it happens to somebody, the aformentioned method works perfectly fine. You just need to disable timer0 (power_timer0_disable();) and then your 40kHz signal will not fluctuate (in frequency).

In any case, yeah try to avoid digitalWrite if you want speed.


body:
PWM is the solution.

Russel's answer is proper. My contribution here is a simplification and to relay my observations. I made a [QA about PWM][1] recently and can affirm that "bit banging" and interrupts are not going to be stable. I observed digital writes to be roughly 1 microsecond, so toggling a pin is 2 µsec. This did not affect my project, so no further tests performed about the `digitalWrite()` function. Writing changes to the port macro as a whole is much faster than using `digitalWrite()`, however this still will not have the inherent stability setting up the PWM and its output pin will provide. *Anecdotally, analogRead() is roughly 100 µsec.*

I set up my timer with a prescaler and then applied a count to `OCRxA`. Via my prescaler and `WGM` bits, it turns out that the `OCR` registers were 1:1 for microseconds. `OCRxB` perfectly set the pulse width I was seeking.

Observing the period on an o'scope, it might have been off from the exact integer in `OCRxA` but did not drift. The error I observed was in the tens of microseconds and the values in `OCRxB` were between 6300 and 63000. Code examples are in aforementioned link to my QA. From researching my own solution, I learned this error is likely within tolerance of the crystal providing CPU freq.

  [1]: https://arduino.stackexchange.com/questions/68106/set-pwm-by-period-and-have-it-variable


message:
I2C hookup - sketch just crashes

I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following [these instructions (the hardware setup I have is like in the schematic)](https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide#basic-arduino-example) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from [this page](http://www.gammon.com.au/i2c-summary) it seems something basic with I2C must be wrong. The code from there I am using is:

    // I2C Scanner
    // Written by Nick Gammon
    // Date: 20th April 2011

    #include <Wire.h>

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

      // Leonardo: wait for serial port to connect
      while (!Serial)
        {
        }

      Serial.println ();
      Serial.println ("I2C scanner. Scanning ...");
      byte count = 0;

      Wire.begin();
      for (byte i = 8; i < 120; i++)
      {
        Wire.beginTransmission (i);
        if (Wire.endTransmission () == 0)
          {
          Serial.print ("Found address: ");
          Serial.print (i, DEC);
          Serial.print (" (0x");
          Serial.print (i, HEX);
          Serial.println (")");
          count++;
          delay (1);  // maybe unneeded?
          } // end of good response
      } // end of for loop
      Serial.println ("Done.");
      Serial.print ("Found ");
      Serial.print (count, DEC);
      Serial.println (" device(s).");
    }  // end of setup

    void loop() {}

Instead of this suggested sample output:

    I2C scanner. Scanning ...
    Found address: 42 (0x2A)
    Done.
    Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:

    ù
    I2C s

With other examples I have tried I have similar results. As soon as something calls `Wire.endTransmission()` things start to crash and burn.

Any ideas what this could be or how to debug it?

body:
`Wire.endTransmission()` is where the action is. Nothing is actually sent until that point. `Wire.beginTransmission` just gets ready for sending and `Wire.write` (if used) adds stuff to an internal buffer.

If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).

Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.

I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


message:
PWM pins weird on Arduino Mega, works on Arduino Uno

I've bought one of those cheap 2.4" TFT LCD resistive touchscreens, one of these: ![2.4" TFT LCD resistive touchscreens.][1]

It works great on my Arduino Uno, using the code from [this github repository][2].  Now I'm trying to get this to work on my Arduino Mega.

On the Arduino Uno, the LCD controller data lines are configured as:

    data[0:7] = PORTB[0:1] | PORTD[2:7]

ie. data pins 8, 9, 2, 3, 4, 5, 6, 7 make up the LCD controller data lines.

On the Mega, the pin numbers are the same but the ports are configured differently, so that:

    data[0:7] = ((PORTH >> 5) & 0x03)
       | ((PORTH << 3) & 0xc0)
       | ((PORTG >> 1) & 0x10)
       | ((PORTE >> 2) & 0x0C)
       | ((PORTE << 2) & 0x20)

I've rewritten the `TFTLCD::read8` and `TFTLCD::write8` functions accordingly.

The screen doesn't work, though.  I've cut example code down to just resetting the LCD controller and reading the chip ID register, ie:

    Tft.writeData(0);
    Tft.writeData(0);
    Tft.writeData(0);
    Tft.writeData(0);

    Tft.writeCommand(0);
    unsigned id = Tft.readData();

Now, 9 times out of ten, this obtains the correct device ID, `0x9325`.  But the other time, it obtains the device ID of `0`.

I initially suspected that this was due to the Mega running somewhat faster, but liberally sprinkling `delayMicroseconds(10)` through the `writeData`, `writeCommand` and `readData` functions doesn't seem to make any difference.

Is there something that I'm missing that is messing with the use of the PWM lines on the Arduino Mega as ordinary digital port pins?

  [1]: https://i.stack.imgur.com/aBGLH.jpg
  [2]: https://github.com/johnmccombs/arduino-libraries

body:
Never mind; this was me making a mess of the bit masking.

See [this github repository][1] for working code with Arduino Mega.

  [1]: https://github.com/tomkcook/arduino-libraries


message:
arduino webserver serves single web page to WAN/Internet very very slowly

I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.

It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the  WAN/Internet.

I have port forwarding set-up on the modem router so that the Arduino web page  can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.

(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).

Has anyone any ideas what might be wrong ?

Thank you

body:
I haven't used the ethernet library for a while, but I remember that it served up tiny packets - basically each write call went in its own TCP packet. It sounds like you may have latency issues across the WAN.

You could try using your Apache instance to proxy the Arduino pages. Details are at http://httpd.apache.org/docs/current/mod/mod_proxy.html I have this running but all my pages are small so I'm not sure how it would behave on larger pages.


body:
The answer is :

I combined all my

    client.println("Some text here
");

html statements into much longer statements eg

    client.println("Some text here
All On   All Off
Socket 1 On   Socket 1 Off
");

This reduced the number of client.println("  ");  statements by about one third, which resolved the issue.


body: This would be a good place to get out tcpdump or WireShark (or any other tool that will let you observe network traffic). If you watch the traffic while you're making the a request that goes to the Arduino (perhaps use a phone to make the request so that it comes from outside) you will be able to observe the TCP/IP transactions and see where the delays are.