text:
433Mhz transmitter interference when using long cable, only on Arduino Due
When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:
-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).
-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from 0.1 uW/m2 to 3 mW/m2 a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.
The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.
I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.
I'm using the RCSwitch library. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

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

  // Transmitter is connected to Arduino Pin #8
  mySwitch.enableTransmit(8);
}

void loop() {}

Why am I having this strange behavior? Do you have any suggestions on how to fix it?

Try adding a decoupling capacitor between VCC and GND on/near the transmitter. You could also try shielded wires. It might be helpful to know what specific kind/model of transmitter you use.

I just tried adding a 1uF decoupling capacitor, and it didn't seem to have an effect on the problem. One new thing I learned is that when the above code is run on the Due, the output pin is constantly outputting 3 volts. The same code on the Uno doesn't cause the pin to output voltage.

I found someone else who had the exact same problem on the Arduino forum: http://forum.arduino.cc/index.php?topic=215385.0 . Nobody responded to his question.

I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0
Likewise this page suggests the problem is a bug with the wiring_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0
In RCSwitch.cpp, this is the enableTransmit code:
void RCSwitch::enableTransmit(int nTransmitterPin) {
  this->nTransmitterPin = nTransmitterPin;
  pinMode(this->nTransmitterPin, OUTPUT);
}

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.
I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?
Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?

It just sends a 433Mhz signal, all the time. Which would explain why all other receivers/transmitters don't work any more. These modules send data by turning the signal on an off (On-off keying).


text:
How to read the serial data from a ATMEGA8 on a PC using Arduino?
I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?
I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?
I have the AVR code which was burned on the IC, so I can provide you with more information if you need.

Connecting to the RX pin on the Arduino will let the AVR chip receive the data, but not the PC. Try connecting to the TX pin, and making sure the Arduino isn't running anything that would initialize its own UART.

@NickJohnson Thanx, would Serial.begin() be what would initialize it's own UART.

That's right. Best option is to load an empty sketch, or the 'blink' sketch.

@NickJohnson Thank you, and it works perfectly. Can you convert it into an answer so that I can accept it?

If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.

Or just tie the reset pin low so that the serial pins go high-impedance.

You can download this example code to your Arduino UNO...
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
Make sure the baud rate on the line mySerial.begin(4800) to match the baud rate your device is sending.
Then run "Serial Terminal" from the Arduino IDE and connect the output of your device to pin 10 on the Arduino.
If the baud rate is correct, you should see the Serial output from your device in the serial terminal window.
Why you might not want to direct connect
Here is the schematic of the serial port section of the Arduino UNO...

The TX pin on the header is connected directly connected to the TXD/PD1 pin on the ATMEGA chip as highlighted in red. This pin will be actively driven if any of the following happen...

There is a sketch running on the Arduino than enables the serial port (i.e. includes Serial.begin()).
There is a sketch running on the Arduino that enables pin 1 as output (i.e. includes pinMode(1,OUTPUT);).
The Arduino reboots and runs the bootloader, which always briefly enables the serial port on startup.

There are some devices that can be permanently damaged by having their serial output tied to an actively driven signal, especially a +5 volt one like we have here. The BBB is one of them (I know from experience!).
One response suggested downloading the BlinkMe sketch into the Arduino, presumably to make sure there is not another sketch running that could enable the serial port. This is the right idea, but you have to keep in mind that the UNO will reboot anytime the RTS line is toggled. Here is a not-so-far-fetched scenario...

You load BlinkMe into the UNO.
You connect the device to the TX pin on the UNO.
You launch Tools-Serial Monitor from the Arduino IDE to see the serial data.
The Serial Monitor window opens and toggles the RTS line (does this every time you launch it).
The UNO reboots.
The bootloader runs and enables the serial port on the ATMEGA.
The connected device is cooked.

Also keep in mind that even if the attached device can tolerate being connected to an actively driven signal, once you connect another signal to the Arduino TX pin then you loose the ability to communicate with the Arduino.
Loading the Softserial sketch takes the same number of steps as loading the BlinkMe sketch, reduces the chance of of damaging the connected device, and also allows you to keep access to the Arduino while you are doing all this.

That really isn't necessary, when he could just hook his UART up to the pins used by the Arduino for hardware serial.

source: Stack Exchange

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

sort: votes


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!!!

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


text:
Debouncing a limit switch in Arduino ISR with delays
I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.
As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.
const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
    pinMode(lsOuterLeftIn, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void  loop() {
    if (lsEngaged) digitalWrite(LED, HIGH);
    else digitalWrite(LED, LOW);
}
void ISR1(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}

But, here is my problem. I came upon this Arduino documentation page, and it says
"Since delay() requires interrupts to work, it will not work if called inside an ISR. "

But, I do make use of delay() inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the delay() function could malfunction on me as the documentation says?

What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.
Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.

Of course there are much nicer ways to deal with the problem, but they tend to be more complex (you could read about bottom halves, for example) than what you might be willing to spend time on.


text:
Requesting references for learning about the upload process
I would like to know of references that discuss the process of uploading code onto an Arduino board. I have read this reference on hacking the Arduino and an outline of the build process. I also found this segment on creating Arduino libraries informative.
Overall I am interested in tracing through an upload process to learn more detail about how the programming works. I would like to understand which C-libraries are used. I would like to understand how the code is uploaded onto the Arduino. One example that I would like to see is an direct upload of C or C++ code without using the IDE gui. I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++). I would ideally like to read about something like this which makes use of the Arduino libraries.
Looking forward to hearing back responses, and being a part of this community. Any references and comments appreciated.

Edit #1 (request for more information from the accepted answer):
How does the main sketch trace through the C/C++ code?
For example, in the make file shown in the accepted answer:
$(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o

Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
I would think so, being that it is compiled every time we change the main sketch.
Lastly, how is the outputted .hex file uploaded to the board?

Edit #2 Trouble compiling with make method
I am having issues with the manual compiling process, I am using Arduino 1.6.5 r5. It seems that malloc.c and realloc.c are not in the same place as they were in IDE 1.0.6.. Here is the makefile.
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

The build fails unless the lines involving those two functions are commented out. I searched in the directories but had no luck in finding the libraries, so I decided to move forward in testing things out.
Here is the file I am using as Blink.cpp.
#include <Arduino.h>

void setup(){
    pinMode(13, OUTPUT);
}

void loop(){
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);              // wait for a second
}

Again, the build does compile ignoring malloc and realloc. I am unsure of whether these are critical libraries as I am not very familiar with C/C++. While the libraries do compile, there is an error derived from the delay() function in Blink.cpp.
Here is that:
"/home/wiz/programs/arduino-1.6.5-r5/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o Blink.cpp.elf Blink.cpp.o core.a -lm
core.a(wiring.c.o): In function `delay':
/home/wiz/programs/arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/wiring.c:113: undefined reference to `yield'
collect2: error: ld returned 1 exit status
make: *** [build] Error 1

I am unsure at this point whether or not this error is related to the fact that malloc and realloc have not been compiled. I have traced back into the wiring.c file to find out where yield() was. That file starts with an #include "wiring_private.h" and here is the delay function and yield:
void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                yield();
                if (((uint16_t)micros() - start) >= 1000) {
                        ms--;
                        start += 1000;
                }
        }
}

Here are the include statements from the wiring_private.h header.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <stdarg.h>

#include "Arduino.h"

Perhaps on of these contain the yield() function, which is not being seen correctly?
Does anyone have any advice for what I am doing wrong regarding building manually with 1.6.5? Any comments or further comments will be appreciated.

Edit #3 Identified where yield() function is located.
Project directory:
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── Blink.cpp
├── Blink.cpp.d
├── Blink.cpp.o
├── CDC.cpp
├── CDC.cpp.d
├── CDC.cpp.o
├── Client.h
├── core.a
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.cpp.d
├── HardwareSerial.cpp.o
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── HID.cpp.d
├── HID.cpp.o
├── hooks.c
├── IPAddress.cpp
├── IPAddress.cpp.d
├── IPAddress.cpp.o
├── IPAddress.h
├── main.cpp
├── main.cpp.d
├── main.cpp.o
├── new.cpp
├── new.cpp.d
├── new.cpp.o
├── new.h
├── Printable.h
├── Print.cpp
├── Print.cpp.d
├── Print.cpp.o
├── Print.h
├── run.mk
├── run.mk~
├── Server.h
├── Stream.cpp
├── Stream.cpp.d
├── Stream.cpp.o
├── Stream.h
├── Tone.cpp
├── Tone.cpp.d
├── Tone.cpp.o
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.cpp.d
├── USBCore.cpp.o
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── WInterrupts.c.d
├── WInterrupts.c.o
├── wiring_analog.c
├── wiring_analog.c.d
├── wiring_analog.c.o
├── wiring.c
├── wiring.c.d
├── wiring.c.o
├── wiring_digital.c
├── wiring_digital.c.d
├── wiring_digital.c.o
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.c.d
├── wiring_pulse.c.o
├── wiring_pulse.S
├── wiring_shift.c
├── wiring_shift.c.d
├── wiring_shift.c.o
├── WMath.cpp
├── WMath.cpp.d
├── WMath.cpp.o
├── WString.cpp
├── WString.cpp.d
├── WString.cpp.o
└── WString.h

yield() is located in hooks.c. I do not understand why the function is not available to wiring.c.

Edit #4 Compilation working
Structure of arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino:
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── CDC.cpp
├── Client.h
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── hooks.c
├── IPAddress.cpp
├── IPAddress.h
├── main.cpp
├── new.cpp
├── new.h
├── Printable.h
├── Print.cpp
├── Print.h
├── Server.h
├── Stream.cpp
├── Stream.h
├── Tone.cpp
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── wiring_analog.c
├── wiring.c
├── wiring_digital.c
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.S
├── wiring_shift.c
├── WMath.cpp
├── WString.cpp
└── WString.h

The reason the yield() function was not recognized was because I was not compiling with 1.6.5 correctly. Below is an updated makefile that compiles the Blink.cpp seemingly correct. I have yet to verify the sketch works on upload to the Arduino (via avrdude). The mistake was that I did not compile abi.cpp, HardwareSerialx.cpp(0-3), and hooks.c. hooks.c is where the yield() is located.
Updated makefile:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)hooks.c -o hooks.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)abi.cpp -o abi.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial0.cpp -o HardwareSerial0.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial1.cpp -o HardwareSerial1.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial2.cpp -o HardwareSerial2.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial3.cpp -o HardwareSerial3.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a hooks.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a abi.cpp.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HardwareSerial0.cpp.o
    $(AR) rcs core.a HardwareSerial1.cpp.o
    $(AR) rcs core.a HardwareSerial2.cpp.o
    $(AR) rcs core.a HardwareSerial3.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

Are malloc.c and realloc.c being used anymore? I searched across 1.6.5 for a directory similar to avr-libc, I couldn't find anything. I'm guessing they are no longer in use.

Edit #5 Upload via avrdude
Basically this command worked for my board (Arduino Uno SMD):
avrdude -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:/path/to/Blink.cpp.hex:i

This is all to say that the latter makefile in this post correctly builds the .hex file. Which can then successfully be uploaded onto the board. (Using Arduino 1.6.5).

I am interested in tracing through an upload process to learn more detail ...

I covered the uploading process in some detail here: What happens when code is uploaded using the bootloader?

I would like to understand which C-libraries are used

See my post about How the IDE organizes things

One example that I would like to see is an direct upload of C or C++ code without using the IDE gui.

I wrote a simple Makefile on the Arduino Forum:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

There are quite a few more complex ones around.

I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++).

Here:
int main ()
 {
 }

Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
I would think so, being that it is compiled every time we change the main sketch.

I'm not sure I understand the part about "transfer through" but basically functions which are needed in the main sketch are linked into the combined file by the linker.
Effectively these are the main parts:
# Compile main sketch
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o

# Compile libraries
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
...

# Remove temporary "combined libraries" file
    rm core.a

# Add compiled libraries into combined file "core.a"
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
...

# Link main sketch to combined libraries (linker will discard things not needed)
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm

# Make an .eep (EEPROM) file
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep

# Make the main .hex file
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

Lastly, how is the outputted .hex file uploaded to the board?

There are various ways of achieving this. The IDE calls the program avrdude which is designed to upload a .hex file to a processor. You can also just copy the .hex file to an SD card and upload it using a board programmer.

Are malloc.c and realloc.c being used anymore?

They are being used, the trick is to find them.
I can't see them being directly linked in a 1.6.5 compiler output, so I am assuming (I can't prove it right now) that they are linked in by default from libc.a (the default C library). Being a default library it is not mentioned on the linker line.
In my (Linux) installation I found that library here:
~/Development/arduino-1.6.5-r5/hardware/tools/avr/avr/lib/libc.a

If you do a nm on it you find this (amongst other things):
malloc.o:
00000002 C __brkval
         U __do_clear_bss
         U __do_copy_data
00000002 C __flp
00000146 T free
         U __heap_end
         U __heap_start
00000000 T malloc
00000000 D __malloc_heap_end
00000002 D __malloc_heap_start
00000004 D __malloc_margin
0000003e a __SP_H__
0000003d a __SP_L__
0000003f a __SREG__
00000000 a __tmp_reg__
00000001 a __zero_reg__

From man nm:
  "D"
  "d" The symbol is in the initialized data section.
 ...
  "T"
  "t" The symbol is in the text (code) section.

See http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html :

The C standard library itself is stored in '/usr/lib/libc.a' and contains functions specified in the ANSI/ISO C standard, such as 'printf'---this library is linked by default for every C program.

I am guessing here that malloc and free moved into the standard (default) library since version 1.0.6 (or they wanted to override it with a bugfix) and it is now being found, by default, in the standard C library as described above.
You should be able to find more about AVR libc at its page: http://www.nongnu.org/avr-libc/

Please see my edits. I am looking for a bit more information. Thank you for the answer. It is very helpful.

See amended reply.

I am not too familiar with C terminology. Are the INCLUDE_FILES in reference to the headers? While the LIBRARY_DIR is in reference to the c and cpp file? I've looked in the directories and see those types of files. I just want to understand the distinction. I also found some assembly code (.S), is that file used in INCLUDE_FILES or LIBRARY_DIR?

The INCLUDE_FILES is the path to the .h files used in the compilation process (eg. Arduino.h). If you include other libraries (like SPI) more include files paths are added to the compile line for the main sketch. These locations may vary a bit from IDE to IDE, I think the one I quoted was form IDE 1.0.6. Assembly code would be assembled as a separate compilation unit (ie. another compile) since one compiler doesn't compile both C++ and assembler. The best way to examine this is to turn on verbose compiling, try some compiles, and see what gets generated.

Hi, again. Please see the edits to my post. I hope the forums don't mind me amending the post as much as I have.

See my amended reply.

I figured that they likely were moved. Thanks for confirming this. The build process works for my setup now. The gcc reference will be helpful. Thanks, again.

authors: Мишаков Максим


text:
Math with analog input values coming out wrong
Im getting stuck in a while loop because Im having trouble running a calculation on some sensor values. When I read my four sensors values and compare the ratio of the first two to the second two, I keep getting 0.00, no matter what the values are. Here's my code:
while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

    Serial.print("Backleft Reading: ");
    Serial.println(backleft);
    Serial.print("\n");
    Serial.print("BackRight Reading: ");
    Serial.println(backright);
    Serial.print("\n");
    Serial.print("Frontleft Reading: ");
    Serial.println(frontleft);
    Serial.print("\n");
    Serial.print("Frontright Reading: ");
    Serial.println(frontright);
    Serial.print("\n");
    float ratio = (frontleft + frontright) / (backleft + backright);
    float math = (5 + 6) / (4 + 5);
    Serial.print("Math: ");
    Serial.println(math);
    Serial.print("Ratio: ");
    Serial.println(ratio);
    Serial.print("\n");
    delay(500);

  }

Im getting values for my sensors (backleft, backright, frontleft, frontright), but 'ratio' always comes out 0.00. Because of that, Im getting trapped in the loop I believe. What's going on here?
Also, just to check, I added 'math' float as that quick calculation, but I'm getting a value of 1.00 in Serial Monitor. Why? It should be 1.222.

Read this: Integer arithmetic and overflow.
float math = (5 + 6) / (4 + 5);
Serial.print("Math: ");
Serial.println(math);

The compiler is treating your expression (the RH side of the "=" sign) as integers. Thus it is working out:
11 / 9 = 1

Then you assign that 1 to a float. Too late to make it a float! It is already truncated.
Try:
float math = float (5 + 6) / float (4 + 5);
Serial.print("Math: ");
Serial.println(math, 4);  // 4 decimal places

You get:
Math: 1.2222

This also looks wrong:
while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

How many backleft variables do you have? The one in the while instruction will not be the one you are doing the analogRead on. It doesn't "forward read" variables. I bet you have a different frontleft / backleft etc. set of variables declared earlier. These will not be updated inside the loop.
(To make them get updated drop the word int from inside the loop).


text:
atmega328 raspberry pi 2 communication
I have an atmega328p (running on it's internal 8mhz clock) receiving data over rf. I need the data received to be communicated to the raspberry pi 2 using its gpio pins, I cannot use USB. I don't have the budget for a gertduino. Is there any way to do this directly? I only need to be able to receive serial output on the pi, no uploading sketches.

Both the Arduino and the Raspberry PI have interfaces like SPI, I2C and UART. These interfaces will make it easy for you to communicate between the two. I suggest you search for UART unless you need a very high data throughput, then you need to go for SPI. But unless you want to send over a thousand messages per second UART will work just fine.

Just remember that if you power your uC with 5V you will need to level translate it, otherwise you can fry the raspberry and/or the atmega will not hear the rPI


text:
Dimming 6W (24V DC 0.25A) LEDs using Arduino
I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A
I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.
Would a TIP122 transistor be ok?
Any tips for keeping the transistor off until the dimming process starts?

I'd suggest using MOSFETs. The TIP122 has a 2V drop, so it will dissipate 0.5W worth of heat. MOSFETS will only dissipate a few milliwatts. To turn of the leds set the output pin to low. To make sure the led stays off on powerup, add a pull-down resistor to the PWM output-pin.

I would suggest using the CAT4101 constant current sink PWM LED driver.  It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you.  You can then control it through the PWM input pin direct from the Arduino.

very interesting option, thanks! Would the NCP3065PG work as well? http://pdf1.alldatasheet.com/datasheet-pdf/view/196869/ONSEMI/NCP3065PG.html It's just because it would be easier for me to source it

I have not used that chip and not in a position to look right now.

just got the CAT4101 but I am a bit confused about how to calculate the resistor setting. The datasheet states that the LED current is mirrored from the current flowing from the RSET pin and then there's a table listing a few values matches. So I guess having 250 mA means I need a resistor around 2000 Ohm. Is there anyway to calculate the exact resistance?

I use 1.2 / (led current / 400) - it's not exactly like the table but close enough.  I have it as an online calculator: http://majenko.co.uk/?page=cat4101 The 400 comes from the datasheet: "RSET to LED Current gain ratio" on page 2.

All working pretty good. I just get a minuscule amount (almost of light from LEDs when the PWM is set to LOW. Could this mean that I need a slightly bigger resistor?
Also, having a problem of Arduino freezing after a short time, http://arduino.stackexchange.com/questions/18307/arduino-is-freezing-after-a-10-15-minutes could this be due to CAT4101?


text:
How to access parse cloud functions using arduino?
I have created rest service using .js file on Parse.com.
I want to access cloud function from arduino.
i tried this
client.get(https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello");
i am getting error "Method not allowed".
Solution :
Somehow i got the answer which is as follows.I hope it will help others.
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(function_name);  //string ("hello")
 cloudFunction.add("light_sensor", light); //pass parameter to cloud

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());

What is a rest service?

REST api i have written on Parse side that i want to access from Arduino sketch.

I read api of Parse and there i got the class to call cloud function from
Arduino.I hope it will help others.
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(fnname); //String ("hello")
 cloudFunction.add("light_sensor", 139); //parameter

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());


text:
Arduino Uno + Adafruit Ultimate GPS Shield Serial issue
I've had an Arduino Uno for a couple of months-making basic sketches-and recently purchased an Adafruit ultimate GPS shield and attached with soldered headers. This shield has 2 options for reading data, direct and soft serial.
I can sit near a window in my house and receive data using the direct method. This is just due to uploading a blank sketch and reading the serial window. Next, I tried to use one of the examples included in the Adafruit_GPS library and the serial window shows a bunch of nonsense updating.
Has anyone else seen this problem? I'm wondering if its the digital pins on the Arduino that I may have damaged since the example code has a simple phrase to display at the start, and I don't even get this.
Code eg: Serial.println("Get version!").
Just to verify, both boards have power and the direct method was giving me good GPS readings, the serial method gave me junk (not even a simple printed phrase to start), and I verified the Soft Serial switch was flipped and the baud rates matched in code and serial window.
I've attached pictures of the direct method results from that in the serial window, and then the junk results using an unaltered sample serial code. Any help with this would be appreciated.

It looks like you are using the wrong baud rate somewhere.
You mentioned that you had checked your baud rates but check again because the second terminal window looked as if the baud rate was wrong.
In your terminal window. Go to bottom right hand corner where it says 9600 and change it to match the serial speed set in your arduino code.
Or it could be that you are receiving too much data as per the bottom of this article:  https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/soft-serial-connect

Definitely a baud rate problem. The GPS is sending at 9600.
When you use a sketch to receive the data, the SoftwareSerial .begin should be set to 9600. The Serial.begin should be set to a rate higher than 9600, so that the Arduino cannot fall behind in relaying the data to the PC.
If this does not solve you problem, please post your sketch and a wiring diagram so we can analyze it further.


text:
Are DAC pins useful for anything besides working with audio?
Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?

DACs have many uses outside the realm of audio.
Basically a DAC is used any time you want to generate a specific voltage for whatever you need it for - that could be to generate a waveform for audio, or it could be for any other situation, such as:

Setting an offset point for an op-amp
Creating a comparison voltage for comparing another signal to
Controlling the bias voltage of a transistor
Generating a specific reference voltage for an external (or even the internal) ADC

The list goes on.  There are many places you would want to use a DAC.  And why a DAC above PWM? Well basically it boils down to:

Precision - the DAC can generate a more precise voltage than a filtered PWM signal
Noise - the DAC generates a much smoother voltage with better response than filtered PWM which either has switching noise and fast response or less switching noise and delays in voltage level changes.

Thanks. Out of curiosity, would there be any benefits to using DAC for dimming LED bulbs, instead of just using PWM outputs?

No. LEDs work best with PWM.

They are incredibly useful.  They are essentially how you deal with the analog world.
For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna...  The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!
So, yes, they are very useful. :)


text:
How to put arduino in sleep mode?
I need to put arduino in sleep mode. I did not find the library avr/sleep.h . From where to download it.

Just use #include <avr/sleep.h>.

Why didn't you find it? Please post your code that proves this point.

avr/sleep.h is part of the compiler. You don't need to download it.
There are other libraries that act as a wrapper to it to make life easier:

https://github.com/lowpowerlab/lowpower
https://github.com/rocketscream/Low-Power


text:
Cast from long to int
How does arduino uno cast from long to int?
Does it truncate the bits? (Does it just delete the 16 most left bits?)

Yes, it just blindly chops off the upper 16 bits.  That means that the sign can change between the two.
For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.
To see that in more detail, look at the binary.  123456789 in binary is:
0000 0111 0101 1011 1100 1101 0001 0101

Truncate that at 16 bits and you get:
1100 1101 0001 0101

And of course the high (sign) bit is set, so the value is negative.


text:
Arduino port recognition
New Arduino Uno, Arduino 1.6.3, MBP running 10.10.5.
The Arduino IDE is running, I connect to the laptop via usb. The green LED is on the amber light is on but it's not blinking.
I attempted to upload the blink file from File>Example>Basic>Blink. It compiles without issue but won't upload. I get the can't open device "/dev/cu.usbmodem1421" : No such file or directory...
I have attempted using the reset button, changing ports, cycling the IDE and the computer. The killer is that I've had an Arduino on this laptop before.
Any suggests for getting the Arduino linked and operational.

If the serial port is correct (it looks odd to me, check that /dev/cu.usbmodem1421 is the right port), then I think that the problem is the bootloader. Try flashing it again if you have a programmer or another working arduino (search for ArduinoISP tutorials)...

Have you confirmed you have the right Arduino and Port selected in the IDE Tools menu?

Sorry to dredge up an old thread (well, really only replying to one that got robo-dredged :), but maybe this will help someone someday.
A /dev/cu.<something> is a unix port designation. "cu." meant a port used for modems, back in the mists of time but probably isn't relevant today. But what we do learn from it is that the OP is probably using a Mac, and for sure, not Windows.
"/dev/cu.usbmodem1421" is a typical device name for an Arduino as seen by a Mac on a particular one of its USB ports - the numeric part varies according to which Mac USB port the Arduino is connected to each time.
Arduinos & FTDI devices do not need additional drivers on Mac OS (that may not be true for other, non-FTDI USB-to-serial devices).
In this case, the OS already reports seeing (what looks like) an Arduino. The suggestion already put forward, checking the board-type and port selections in the IDE's 'Tools' menu, is the place to start.

I think you may not install arduino hardware and ftd drivers,
Follow the steps given here and then check,

Download the latest version of Arduino software and install it.
Open windows device manager - You can open windows device manager by right   clicking on 'My Computer' and choosing Properties. In the new Window, Click on    Device Manager
Now Scroll Down the List of Devices in the Device Manager till you come to a Device or expand Ports (COMM).
Now you should see Arduino hardware with warning icon or without.
Now do right click on arduino hardware name. Now, Windows will provide you two options, Choose the one that says “Locate and install drivers manually from a specific Location.”
By browsing locate arduino installed folder, then update.

If you previously done these procedure or now, then open arduino software

Go to tools and choose board as what you have like (arduino uno, mega, due etc....)
then in tools menu you should choose serial port (example comm 10, comm 21, comm 8 etc...) in which the arduino board connected, some time the board name displays with serial port otherwise you can observe from device manager ports list.
now upload blink example and check.


text:
Humidity values returned by DHT22 sensors failing after some time
I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.
I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).
Then all of a sudden, they dropped to 1% again.
If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.
 DHTxx test!
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?
Any ideas?
I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?
 // Example testing sketch for various DHT humidity/temperature sensors
 // Written by ladyada, public domain

 #include "DHT.h"
 #define DHTPIN 2     // what pin we're connected to

 // Uncomment whatever type you're using!
 //#define DHTTYPE DHT11   // DHT 11
 #define DHTTYPE DHT22   // DHT 22  (AM2302)
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
 // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
 // to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

 // Initialize DHT sensor.
 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
   Serial.begin(9600);
   Serial.println("DHTxx test!");
   dht.begin();
 }

 void loop() {
     // Wait a few seconds between measurements.
     delay(2000);
     // Reading temperature or humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old'
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);

     // Check if any reads failed and exit early (to try again).
     if (isnan(h) || isnan(t) || isnan(f)) {
         Serial.println("Failed to read from DHT sensor!");
         return;
     }

     // Compute heat index in Fahrenheit (the default)
     float hif = dht.computeHeatIndex(f, h);
     // Compute heat index in Celsius (isFahreheit = false)
     float hic = dht.computeHeatIndex(t, h, false);

     Serial.print("Humidity: ");
     Serial.print(h);
     Serial.print(" %\t");
     Serial.print("Temperature: ");
     Serial.print(t);
     Serial.print(" *C ");
     Serial.print(f);
     Serial.print(" *F\t");
     Serial.print("Heat index: ");
     Serial.print(hic);
     Serial.print(" *C ");
     Serial.print(hif);
     Serial.println(" *F");
}

Try the sensor resetting procedure.

my current workaround is to connect the DHT with a screw terminal instead of soldering them in, and then just swap them out when they start to fail

This is how it looks when they fail.
The DHTxx are very low cost sensors, optimised for cheap volume production.
We don't know under what condition you actually use your sensors. Also, there's the phenomenon of knock-offs and low-grade selling.
In his comprehensive test, Robert J. Smith found a failure rate of 33% and concludes a mean life expectancy of one to two years.
A slightly more expensive alternative is the SHT series of temperature and humidity sensors. My personal experience is that they tend to tolerate some abuse (i.e. complete submersion in water) and don't age as quickly.
Link:

failure analysis: http://www.kandrsmith.org/RJS/Misc/Hygrometers/dht22_first_failure.html
general writeup: http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_dht22_dht11_sht71.html#conclusions

I have had the exact same experience using a DHT11 with Huzzah. I found that the problem tends to happen after high humidity conditions (>85% relative), my solution was to place silicone caulk and heatshrink tubing around the connections to prevent dew buildup. That solved my problem with my third replacement. It has been two months now with no issues.

Can't really help as I have the same problem ! , DHT22 on an ESP8266 has failed twice , while a DHT11 on a similar system has worked faultlessly for months (Thingspeak 27272) , DHT11 is inside the house while the DHT22 is below the house in the carport, Only thing I have come up with is that the DHT22 MAY be failing due to exhaust/hydrocarbon fumes from the car startups
Art

This should probably be a comment.


text:
Accuracy of liquid level measurement using sonar sensor
Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?
I have a cylinder shaped horizontal 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen.

UPDATE! Today I found this helpful page: Home Heating Hacking Part 1 or How to Measure an Oil Tank.
I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.

How is this cylinder placed? Horizontal, or standing upright.

Water tank is placed horizontally.

Sounds like an interesting project - you might just have to try it!

Since you seem to have everything... Just test it :)

I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good.
Couple of points:
1.polling occurs hourly.
2.I only power the ultrasonic sensor just before taking a reading.
3.Has a sound detection sensor to alert on water pump overrun, ie a leak.
good luck

So it works.
I wonder maybe it's possible to increase the accuracy of the measurement  by putting two ~15cm PVC pipes on transducers. It could avoid receiving echo signals. What do you think?

Maybe the pipes would help? Basically you want good echos off the waters surface so mount the sensor firmly as square on to the surface as possible. I would be more inclined to buy a more accurate Ultrasonic sensor. The HC-SR04 have a resolution of 1 cm but others like the US-100 are down to the 1mm and have built-in temperature adjusted readings.


text:
what is the fastest shield to add to the sparkfun v3.2 Arduino Uno that will enable me to playback and record hour of short audio dictation
I have almost no eexperience building electronic kits. I just buoght and began tinkering with sparkfun 3.2 and want to adapt its simon sketch to real audio files
What isis theeasiest to assemble add on shield or breakout not surew hat you call this looked at this one
VS1053 Codec + MicroSD Breakout - MP3/WAV/MIDI/OGG Play + Record - v4


text:
Can BUS Shield on Arduino Leonardo - Can't init CAN
I'm hoping to get some help with this as I am unable to get the CAN to Initialize.
I have the sparkfun Can-Bus shield: https://www.sparkfun.com/products/13262
and an Arduino Leonardo board.
I'm using the following code to try to connect my 2008 Audi S6 to the Arduino board:
#include <Canbus.h>
#include <defaults.h>
#include <global.h>
#include <mcp2515.h>
#include <mcp2515_defs.h>
#include <Canbus.h>
char UserInput;
int data;
char buffer[456];  //Data will be temporarily stored to this buffer before being written to the file

//********************************Setup Loop*********************************//

void setup(){
Serial.begin(9600);
while(!Serial);
Serial.println("CAN-Bus Demo");

if(Canbus.init(CANSPEED_500))  /* Initialise MCP2515 CAN controller at the  specified speed */
  {
Serial.println("CAN Init ok");
  } else
  {
    Serial.println("Can't init CAN");
  }

  delay(1000);

Serial.println("Please choose a menu option.");
Serial.println("1.Speed");
Serial.println("2.RPM");
Serial.println("3.Throttle");
Serial.println("4.Coolant Temperature");
Serial.println("5.O2 Voltage");
Serial.println("6.MAF Sensor");

}

//********************************Main Loop*********************************//

void loop(){

while(Serial.available()){
   UserInput = Serial.read();

if (UserInput=='1'){
 data=Canbus.ecu_req(VEHICLE_SPEED, buffer);
 Serial.print("Vehicle Speed: ");
 Serial.print(data);
 Serial.println(" km/hr ");
 delay(1000);
}
else if (UserInput=='2'){
 data= Canbus.ecu_req(ENGINE_RPM, buffer);
 Serial.print("Engine RPM: ");
 Serial.print(data);
 Serial.println(" rpm ");
 delay(1000);

}
else if (UserInput=='3'){
 data= Canbus.ecu_req(THROTTLE, buffer);
 Serial.print("Throttle: ");
  Serial.print(data);
 Serial.println(" %% ");
 delay(1000);

}
else if (UserInput=='4'){
 data =Canbus.ecu_req(ENGINE_COOLANT_TEMP, buffer);
 Serial.print("Engine Coolant Temp: ");
 Serial.print(data);
 Serial.println(" degC");
 delay(1000);

}
else if (UserInput=='5'){
 data=Canbus.ecu_req(O2_VOLTAGE, buffer);
 Serial.print("O2 Voltage: ");
 Serial.print(data);
 Serial.println(" V");
 delay(1000);

}
else if (UserInput=='6'){
 data=Canbus.ecu_req(MAF_SENSOR, buffer);
 Serial.print("MAF Sensor: ");
 Serial.print(data);
 Serial.println(" g/s");
 delay(1000);

}
else
{
  Serial.println(UserInput);
  Serial.println("Not a valid input.");
  Serial.println("Please enter a valid option.");
}

}
}

Overall, I just can't get the CAN to initialize. I've looked online and just can't seem to find a solid solution. I've tried other libraries as well to no avail.
Please assist!

Leonardo has SPI pins on the ICSP header. Your shield expects SPI pins on pins 11,12 and 13. Maybe this will help: http://www.seeedstudio.com/wiki/CAN-BUS_Shield#How_to_Compatible_With_Arduino_Mega_and_Leonardo

I got that far; The strange part is that even if I bring the SPI pins to pins 11,12, and 13 it still doesn't work.. are there more pins I need bring over?

Had this problem myself. Found this fixed it
Change the following line...
_delay_us(10);

To...
_delay_us(50);

In the MCP2515.c file in the library

Increasing that delay in the MCP2515.c file also fixed this issue for me.
I am running the sparkfun Can-Bus shield on an Arduino pro-mini, and here is my serial monitor output before the change, and after:
12:56:38.580 -> CAN Read - Testing receival of CAN Bus message
12:56:39.556 -> Can't init CAN
13:01:40.992 -> CAN Read - Testing receival of CAN Bus message
13:01:42.016 -> CAN Init ok

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


text:
Intercept Data being sent to XBee Module via UNO
An XBee Pro S1 module sits on a DIP socket on-board a Personal Weather Station (PWS) to transmit data.
Instead of letting the station transmit data wirelessly via the XBee, I would like to read that data off the socket pins on which it sits, via an Arduino UNO.
Is this possible? If so, what should I look into?
I am new to wireless communication with a µC, so any help would be appreciated.

If i am getting you right, try connecting the tx pin of Xbee with the rx of UNO and then read the data coming in to the serial UART.

@AnumSheraz: thanks for that. I tried but Arduino did not pick up any data off pins 2 & 3 of the XBee socket (Tx & Rx pins). I'm guessing the settings (baud rate, parity, etc.) need to be known first before any meaningful data can be captured.


text:
How to switch program in arduino using android app?
I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze.
                   Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

Why don't you make just one program to run all?

Never mind I just found the solution.Thank you for your reply though.

If you know the solution you should post it as an answer.

The answer is a little bit complicated.I'll post it as soon as possible.

Once I made a sketch to run multiple programs. I wrote a setup and loop function for every different "program", (e.g. setup_p1, setup_p2, ... loop_p1, ...) and then wrote a simple main sketch to handle them all.
In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.
I choose to use a callback because it's faster than just checking the mode every time, at least in my case
// callback for loop function
typedef void (*loopfunction)();
loopfunction currentloop;

void setup()
{
  // Set dip-switch pins as input
  pinMode(MODE_PIN2,INPUT_PULLUP);
  pinMode(MODE_PIN1,INPUT_PULLUP);
  pinMode(MODE_PIN0,INPUT_PULLUP);

  // Concatenate the dip-switch values
  byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

  // choose the correct mode
  switch(mode)
  {
    case 0: // Shutdown - do nothing
            break;
    case 1: // Program 1
            setup_p1();
            currentloop = loop_p1;
            break;
    case 2: // Program 2
            setup_p2();
            currentloop = loop_p2;
            break;
    ...
  }

  // Not a valid program: halt
  if (!currentloop)
  {
    while(1);
  }
}

void loop()
{
  // Execute the current loop
  currentloop();
}


text:
Can anyone explain how this code can be converted to work on a Arduino Uno
I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time

# this many mm per bucket tip
CALIBRATION = 0.200
# which GPIO pin the gauge is connected to
PIN = 17
# file to log rainfall data in
LOGFILE = "log.csv"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# variable to keep track of how much rain
rain = 0

# the call back function for each bucket tip
def cb(channel):
    global rain
    rain = rain + CALIBRATION

# register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

# open the log file
file = open(LOGFILE, "a")

# display and log results
while True:
    line = "%i, %f" % (time.time(), rain)
    print(line)
    file.write(line + "\n")
    file.flush()
    rain = 0
    time.sleep(5)

# close the log file and exit nicely
file.close()
GPIO.cleanup()

What have you tried? What part of it are you having problems with? If you don't know where to start then start at the very beginning - don't try and do it all at once. Get the Arduino to (for example) light up an LED when the reed switch closes, and build up from there. Read tutorials on how to read inputs. Read examples on how to deal with RTC and SD. We aren't a code conversion service.

This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes.  if there is a specific programming problem it should be addressed separately instead of handing out working code.
const int CALIBRATION = 0.200;   //Calibration Constant
int pin = 2;                     //Pin it's on, this is int0 for uno.
volatile int rain = 0;           //Used in interrupt routine

void setup() {
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
}

void loop() {

     /* Output OR LOG DATA HERE
        Also You need a Time Library and RTC (Real Time CLock) the above
        code is for a raspberry pi that has all that. */

}

void cb() {
    rain = rain + CALIBRATION;
}


text:
Arduino keypad matrix example? ( teensyduino )
I'm a beginner using Arduino with a Teensy 3.2 board and programming it as a usb keyboard. I have two 4 button membrane switches. Their button contacts are on pins 1-8, and the 9th pin holds a soldered together wire of both membrane switches' "ground" line or whatever it's true name is; the line that completes the circuit.
Basically when you press the buttons they are supposed to simply type "a, b, c..." respectively. I've been told I need to use a matrix for this.
I'm looking for an example of how to code a keyboard matrix that effectively supports a one row/9 column line (or vice versa?) I've been unable to find that solution online.
All I have so far is this code which, when the button on the second pin is pressed, sends tons of "AAAAAAAAAAAAAAAA" keystrokes.
void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send an ASCII 'A',
    Keyboard.write(65);
  }
}

Would anyone be able to help?

How long do you hold the button down for? Half a second? How many "A" do you think you can print in that time. You need to detect a transition from button-not-down to button-down and then send the "A".

By your description, you don't have a matrix.  You have them wired as just 8 straight switches.
A matrix would be if you had the 4 switch pins of one keypad wired to the same switch pins of the other keypad, and the two common connections from the keypads wired to two separate IO pins.
At the moment your code is responding whenever a button is in the low state. Instead it needs to respond only when the button transitions from the high state to the low state.  To do that you need to know what state all the buttons were in the previous pass through loop to compare them to what they are in this pass through loop - and if any have changed then they have either been pressed or released.
You should also implement debouncing to that you don't get false presses.
If you don't want to learn how to do all that yourself I have a handy library that will do it all for you:

https://github.com/MajenkoLibraries/DebouncedInput

If you want to convert your setup to an actual matrix to save on IO pins you want to read the Arduino Keypad tutorial:

http://playground.arduino.cc/Main/KeypadTutorial

I'm using 2 of these: http://s1250.photobucket.com/user/09016/media/1_zps7b32fbcc.jpg.html Everyone I spoke to on forums (and my testing) concluded that I couldn't get the buttons to function without taking those 5th connections and merging them.  I'm too new to get much done with what you've said. Compiling your program can't find the DebouncedInput.h include and while it's in there I'm not sure where to copy it. (tried many) I've read the Matrix tut thrice and tried it with no success when I press the buttons. The only thing that has displayed anything was my example code and it was a mess~

Follow this guide to install a library: https://www.arduino.cc/en/Guide/Libraries I know those keypads well - I have one stuck to the top of my home-made keyboard (old Amiga A500). They are just 4 buttons with one common connection, not a matrix.


text:
Sending data from Arduino to the server where arduino (sketch) acts as a client
I want to make simple client-server program where arduino behave as a client. For example I have a LED connected in arduino board that is controlled by a switch. With the switch I can turn off and on the LED. Now I want to send the status of that LED to another computer wirelessly (let's say within the Local network). That computer will act as a server and update the change as soon as the LED changes its status. I am not expecting any complete code, I just want to know how could it be done in general? May be some links can help me? Because this is my first time working with client-server in arduino sketch, I need some kind of guidelines. Thank you.

There are example client-server sketches included in the IDE. Did you look at those?

When you say "Local Network" - do you mean over Wifi ?

A simple HC-05 module will give you a wireless bluetooth connection.  They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console.  Obviously they can read data too.
SoftwareSerial bt_serial(2, 3); // RX | TX
bt_serial.begin(9600);

[...]

if (led_state != last_led_state)
{
    if (led_state == HIGH)
        bt_serial.print("1");
    else
        bt_serial.print("0");
    last_led_state = led_state;
}

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job.  For example, some python code:
import serial
import sys

serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

try:
    serial_port.open()
except:
    print("Failed to open port")
    sys.exit(2)

while (True):
    try:
        led_state = serial_port.read()
        if (led_state != 0):
            print("LED is on")
        else:
            print("LED is off")
    except:
        pass

serial_port.close()   # yes, it never gets here

Even though I like Kingsley's answer I thought I'd add to this using Wi-Fi becuase you had mentioned LAN.
These two links should be enough to help you:
WifiChatServer
and C# Telnet Library
Those links can sort of be dissected to fit your needs, but if you need some actual code just tell me.
Now I am aware that the Arduino is acting as a server and the computer acts as a client, but I believe this setup is better because it's easier to manipulate connecting to servers on the computer rather than on the arduino side.


text:
Is there a way to use functions defined in a library in any class?
I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.
So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?
Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.
I've tried a bunch of different things but I've come to a dead end.
EDIT:
main program:
#include "_v0_0_0.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

#include "Point.h"
#include "Rectangle.h"
#include "SomeView.h"

#define     TFT_CS  4
#define     TFT_RST 0
#define     TFT_DC  10

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
SomeView a_view;

void setup()
{
    tft.initR(INITR_BLACKTAB); // initializes the display
}

void loop()
{
    a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
    while (true) {}
}

SomeView.h:
#include "Rectangle.h"

class SomeView {
private:
    Rectangle a_rectangle;
public:
    SomeView();
    void draw();

    const Rectangle& getRectangle() const {
        return a_rectangle;
    }

    void setRectangle(const Rectangle& rectangle) {
        a_rectangle = rectangle;
    }
};

SomeView.cpp:
#include "SomeView.h"

SomeView::SomeView() :
        a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
}

void SomeView::draw() {
    a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
    a_rectangle.draw();

    a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
    a_rectangle.draw();
}

Rectangle.h:
#include "Point.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

class Rectangle{
private:
    Point p1;
    Point p2;
public:
    Rectangle();
    Rectangle(Point& p1, Point& p2);
    void setCorners(const Point& p1, const Point& p2);
    void draw();

    // ... getters and setters for the points
};

Rectangle.cpp:
#include "Rectangle.h"

Rectangle::Rectangle() : p1(), p2()
    {
    }

Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
    {
    }

void Rectangle::setCorners(const Point& p1, const Point& p2) {
    this->p1 = p1;
    this->p2 = p2;
}

// this is where I want to use a function from the adafruit library
void Rectangle::draw() {
    Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

}

So are you asking how to pass the tft to a class after creating this object ?.... Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);

There are two basic methods to do what you want:

Inheritance
Pointer passing

Inheritance involves making your new class a child class of the Adafruit TFT class.  You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class plus your extra functions overlaid over the top:
class Rectangle : public Adafruit_ST7735 {
    ...
};

You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class instead of the Adafruit class in your sketch.

Inheritance tutorial: http://www.cplusplus.com/doc/tutorial/inheritance/

That is fine if you just want one class that uses the functions from the Adafruit class.  The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time.  For instance, you might have:
class Rectangle {
    private:
        Adafruit_ST7735 *_tft;

    public:
        Rectangle(Adafruit_ST7735 &tft) : _tft(&tft) {}
};

Then in your function you can use:
void Rectangle::draw() {
    _tft->drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);
}

You would, of course, construct your class with:
Adafruit_ST7735 myTFTScreen(blah blah blah);
Rectangle myRect(myTFTScreen);

Then call myRect.draw();.

Yes, there is a way.
However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.
Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.
Your PC, for example.
C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly.
From that perspective, C++ can be seen also as a superset of C, only much more complex.
Have a look at this explanation, for example.
It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.
If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.
For a more systematic approach, try this.

Thank you for your advice! Though this was the kind of answer I was afraid I'm going to get. It's not that I'm not willing to learn. I've read most of the material on [link]http://www.learncpp.com/ but it's like with learning... a new language :D In the beginning you start to grasp the meaning of single words or expressions but it's hard to form a meaningful text - there will be lots of grammar mistakes and cases of misused words. So I understand what you we're saying but you're also suggesting that I should put this project aside. That won't happen.

Sure, it's your time after all and a lesson is not fully learned till one has paid the price for it. But you know the saying: the wise man learns from own mistakes, while the smart one learns from others'  ;-)

More to the point of the question you asked: you got my answer because you question is too generic and doesn't show exactly what you are trying to do, why, how and what error you get. Lacking that, you get the rubber stamp answer.

I thought my question was descriptive enough (though a bit emotional while still trying the best to express myself) but I didn't provide any concrete examples of what I have been doing because my last experiments have become so desperate and ridiculous that these won't have any descriptive value to my problem. I tried to keep it generic also to strip away details which I thought of as being trivial. Also I feel like none of your answers have been more on point than my question.

Indeed. That's what you get for not being clear/precise enough.
How do you think that the answer could be more precise than the question? If I had a working crystal ball, I'd be hitting a different type of website. The type specialized in trading stocks.

Can you be more clear about what was not so clear in my question. I don't own a crystal ball either :D I'm not writing this in my fist language and I'm asking about a programming language that I'm still new to. I'm really OK with providing more info, but I'm not OK with noob-shaming or degrading attitude towards someone who is willing to learn, but needs a little push.

I don't see what noob shaming there is in my answer. It's a heartfelt advice about how to optimize your progress.
Btw, you already got an answer by OP but, as expected, it was not what you wanted. If you only would post the code you are trying to run, even as an example, as long as it represents what you really want to do, it would be possible to have a concrete discussion. Without that, it will be just frustration from both ends.

I don't think Igor's answer was noob-shaming or degrading at all. I looked at your question and couldn't really see what you were asking. You said I've tried a bunch of different things but I've come to a dead end. - is the problem a compile error? If so, what is it? Is it compiling but not working? Your topic is Is there a way to use functions defined in a library in any class? - well, yes there is a way. Otherwise there wouldn't be much point in having libraries, if they couldn't be used anywhere. Can you post a more specific question?

authors: Κωνσταντίνος Πλατσατούρας


text:
What is the purpose of the howMany integer in the wire.onReceive() function from the example code?
In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.
 void setup() {
   Wire.begin(8);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Serial.begin(9600);           // start serial for output
}

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
   char c = Wire.read(); // receive byte as a character
   Serial.print(c);         // print the character
}
 int x = Wire.read();    // receive byte as an integer
 Serial.println(x);
}

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

The description of the wire commands are extremly poor. For me there is also a lot of guessing involved. Without example codes from foren for me it is not possible to generate a running code.
For that reason the question for the sense of how many is very valid.

It tells you how many bytes have been received, and consequently how many you can read with Wire.read().
Before you have read anything with Wire.read() Wire.available() will return the same value.  As you read from the buffer Wire.available() will decrease, but howMany will stay the same.

The reference page https://www.arduino.cc/en/Reference/WireOnReceive states:

Parameters
handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: void myHandler(int numBytes)

I suggest you look at the reference pages for the functions in future before asking what they do.


text:
H-Bridge L298N motor driver
I have 2 motors connected to a dual H-Bridge motor driver and the H-bridge connected to an arduino uno, It was working fine at first but now my motors are spinning very slow and the car bearly moves, I have changed the batteries  but still moves slow and with no power, please help

What motors? What driver? What batteries? Try to give a bit more detail.

I am also facing the same issue with my motor driver. Initially I ran the code and connected the L298N with arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver. I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver? One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine. Somebod

You can try to bisect the problem.
Remove the Arduino and drive the motors with wires: replace the input for the pwm signal with a +Vcc and you will get the same as if the Arduino was outputting a PWM with 100% duty cycle.
This should allow you to diagnose if there is a problem with the driver/motors.
If that shows no problem and the wheels spin as expected, then you have some issue (either sw or electrical with the Arduino).
But at least you can halve the complexity of the problem.

My motor has 2 wires and to run it through the H-bridge i use 3 wires, IN1,IN2 and ENB(PWM),so are u saying I should remove the H-bridge completely or leave the motor connected to the H-bridge just remove the wire connected to ENB and connect it to +Vcc?

(IN1,IN2) work like this: when they have different values, they make the motor rotate left or right., when they are the same value they erither let the motor free and unpowered or locked and powered. You can use wires to test the 4 combinations. the En/PWM can be set and left at high value (probably 5V in your case). So yes, I'd say you could drive manually IN1, IN2, EN. If that still shows problem, then you can consider breaking down that block.

I have EN connected to +Vcc and I have IN1 and IN2 connected to D5 and D6, one set at high and the other set at Low and nothing is happening

My point was that you do not need to connect IN1 and IN2 to the Arduino: just wire them to Vcc/GND and see if the motors move.

oh k, yeah the motor works and I have actually resolved that issue, now I need help with the ublox neo-6, I get 2812989, -2591969 and it keeps going up and down, how do i configure it to give me a fixed value, I am using TinyGPS library

This now seems like a separate question, I suggest you create a new one. You will get also more attention. I wouldn't know how  to solve this new problem you described.


text:
Relay doing opposite to digital pin
I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.
I'm trying to connect to a computer's power button so I can turn it on remotely.
I have found out that the relay basically does the opposite to the digital pin's output
Normally open Relay
HIGH = Open
LOW = Closed
I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.
Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.

It sounds like you have a relay module with an opto-coupler that is wired so HIGH = IR LED on = Phototransistor ON = power transistor OFF.  Either that or the IR LED is wired so that HIGH = OFF and LOW = ON.  You will have to show your schematic and relay module for us to be sure.

@Majenko Yes I think your right, I can't find a schematic but here's the link to it.
http://www.amazon.co.uk/gp/product/B009P04ZKC?psc=1&redirect=true&ref_=oh_aui_detailpage_o05_s00

What you actually have is one of these: http://www.sainsmart.com/arduino/arduino-components/relays/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html

I've solved the problem,
Thanks to everyone who helped.
I don't need a NOT gate anymore, here's what I added to make it work:
void setup() {
  startup();

}
void  startup() {
  digitalWrite(relay1, HIGH);
  digitalWrite(relay2, HIGH);
}
void loop() {
}
(I removed the rest of the code to keep it simple and easy to understand)

The relay module you have is this one from SainSmart:

http://www.sainsmart.com/arduino/arduino-components/relays/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html

The schematic is like this:

As you can see you connect VCC to +5V and IN2 to your IO pin.  Setting the IO to LOW will then turn on the LED and the optocoupler together.
But that's not the only way you can connect it up.
Connect VCC to the IO pin and IN2 to GND instead.  Then you set your output HIGH to turn it on.
The arrangement shown in the schematic is commonly done because some MCUs are able to sink more current than they can source thorugh an IO pin.  That is not the case with an Arduino which has symmetric IO pins that can sink and source the same amount of current.

You could use a less invasive way to turn on your computer: wake on LAN. In this case you only need to generate the magic packet.
It won't work in forcibly turning off the PC, but it's more generic and doesn't require HW hacking.

The motherboard is too old to support Wake On LAN (it still has a floppy disk driver on it :D )
By the way, can a Arduino be used to send Wake On LAN packets?

Did you check in the BIOS? I can't remember having a PC without this feature, for at least 15 years. If you check the link I provided, you will see that you only have to generate an UDP packet with the specific content described and send it in broadcast mode. I have not tried it, but I do not see why it shouldn't work.

To ensure that relay doesn't switch between NO-NC when controller is away relay will need some memory.
Imagine having a 1 bit memory driving relay. If arduino dies/restart, its own GPIO may change, but relay's memory will remember last state and stay there, till controller instructs otherwise, granted relay circuit and its memory element don't lose power.
This also means there will be at least 2 lines required from uC to control this relay now.
I'd prefer to use some kind of serial shift register, e.g. CD4094, CD4042, CD4099 etc because that allows me to control more than one relays from same 2 lines on uC.
You may find some other part more suitable for your application.

I could also think of an alternate. If instead of BJT, you were using a mosfet, with low gate capacitance, you could just keep a capacitor at the gate to hold the charge, in absence of driving inputs from uC. This design would require that uC's lines go tristated when not driven, e.g. restarts. Such a capacitor would be able to hold the charge for a limited time, so your uC must reappear within some time limits.

Great idea, however I was trying to operate the relay with having a circuit between the Arduino and Relay board. At the moment I've build an NOT gate on a bread board which seems to be working.

Try This:
const On  = LOW;    // For non inverted logic swap on and off.
const Off = HIGH;
const pump = 5;

void setup() {
  pinMode(pump, OUTPUT);    // sets the digital pin 13 as output
}

digitalWrite(pump, On);
digitalWrite(pump, Off);