text:
Listen for USB "TX signal received" response on RX
Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.
To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified USBAPI.h and HID.cpp files. It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.

All but two of your tags do not belong, but apart from the obviously inapplicable "signal processing" only you know which.  Delete the ones that don't belong.

The atmega32u4 is the chip the arduino micro uses and I mistakenly thought that was also what the uno uses. Signal processing was included because I expect the solution involves measuring the raw signal from the computer but until that is confirmed I'm happy to leave it off.

That is not what "signal processing" means.

Is "signal processing" not taking analog signals or digital voltages, cleaning them up, and extracting meaning from them? A solution need not use the communication standard to achieve the goal in this case.

None of which you would be doing in this case, as you are not implementing a USB transceiver yourself, but merely using someone's working chip, USB stack, and apparently protocol driver.  And even if you were implementing it yourself (think V-USB), it is arguably too trivial a case to qualify.  Go try to find signals or patterns in noise you have to reject and we can start applying the term.

I don't understand the question, to be honest. Please read How do I ask a good question?.

If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond.  I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.
Going a step further, in the Arduino API an if (Serial) test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it.  Again, this only applies to those that implement USB within the chip on which the sketch is running.
Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in USBCore.cpp Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset.  In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you.  See for comparative example the implementation details behind the if (serial) and create something similar for your chosen USB mode.

if (Serial) is not what is needed here I think as that looks for a connection to the arduino serial terminal and the keyboard (which I am using) library does not depend on that. IE, (Serial) may be perpetually false but various Keyboard functions might or might not work.

I only included the Serial check as an optional more specific extension.  The SoF case should catch anything.  If you are implementing a keyboard in particular, that protocol may have more specific interaction too, indicating that the host operating system has decided to accept you as a keyboard, and not merely noted your presence on the bus.

Can you provide any further reading references on how to use this possible interrupt? I am not aware of any USB related interrupts in the standard arduino micro development environment.

You may well need to dig into the source code of what Arduino normally does behind the scenes below the sketch level.  You may find they have exposed something for the mode you are using compared to the "if (serial)" that is exposed for the usual USB-serial mode, if not you can fix your issues in the source.  Or even more simply, just make sure you don't wait forever for something that may not happen.

I actually have looked at the source code and modified it so the original keyboard library supports proper media keys and such. The problem is rewriting the USB interface is probably 20K LoC in an area I have no expertise in for a problem entirely unrelated to my actual work. My arduino sketch right now is only 175 LoC + ~20 added to the Keyboard/mouse library.

Also when I originally checked into the source code for the library the constructor/deconstructor functions called in the source appear very half baked or non existent. IE calling them or not made no difference to the functioning of the arduino as a USB device. What I'm getting from all this is that the solution to all this might be "go rewrite the keyboard library from scratch." If that's the case, well shit, I'll buy a Teensy, replace the Arduino, rewrite my code and still be done with less time, effort, and frustration.

No, the solution is probably adding 1-3 lines of code, maybe 10 tops, as it is simply checking a condition and returning early if there is no USB.

As I understand, you are trying to implement some peripheral device based on AtMega 8-bit micro-controller that uses USB1.1 interface (FS or LS) to connect to USB host. Your problem seems to be that your host computer (unspecified) puts the port into SUSPEND (sleep), and does not wake up when you try to activate your device (button or something).
First, the USB2.0/1.1 interface does not have any "Tx" or "Rx", it is a half-duplex bi-directional bus. It has D+ and D-, and VBUS. But it is true that a USB peripheral device can generate a bus event called RESUME.
You have two choices. (1) either you make your host computer to never sleep or put USB ports into SUSPEND, or (2) make your device to support RESUME (aka "remote wake-up") function in full compliance with USB specifications.
In case (2) the driver for your device (on host computer) must support remote wake-up function, and this function must be enabled. Then when the host computer is planning to go into one of various sleep modes and decides to SUSPEND your device, it must send special control command to your device which should arm it for wake-up, and the host will be expecting it. In this case the host will never remove VBUS ("passively from computer"), so the device will be able to wake the bus up.
Is this your question about?

No, the question is about a device which should behave differently when it is connected to an operating computer vs. a non-operating computer or simple power supply.

Yes what Chris said is true. The solution should be OS agnostic (IE no modifying of drivers on host computer). That said, if I can make the arduino listen for the SUSPEND and RESUME commands the computer might already be sending, I might be able to achieve the goal anyway.

Then I am confused. On operating computer, your device will connect and will be enumerated and maintain active status as long as host sends SOFs or keep-alives. On non-operating computer the device will not receive any responses from host, and should fall into SUSPEND state (without being armed for remote wake-up). When connected to a charger, this will be similar to non-operaing computer. This behavior is defined in USB2.0 specifications. So what is your question then?

@amoose136: it is not "if you can make the arduino listen to SUSPEND", you must make it so, so your device conforms to USB specification. The SUSPEND function is one of basic USB function. You might elect to do nothing if bus suspend happens, but your interface must wake-up and start responding to host packets if host decides to resume port's activity.

Yes this would probably solve the issue if the device is initially plugged into a computer that is turned on but what if the power goes out? Then no suspend signal is sent and the arduino will try and do the handshake before the OS has had time to boot up so nothing will work.

The goal isn't to have it suspend, the goal is to have it not get stuck waiting for a computer that isn't there or isn't awake.  Of course, the fact that it is apparently getting stuck is purely a problem in how the device side USB code is dealing with USB, not one with USB itself.

@amoose136: When a USB port has no power, it means that the host is not ready to connect and communicate. The "suspend signal" cannot be sent, the SUSPEND happens when NO SoF SIGNAL IS SENT. A USB device must not pull up any data wires (aka "connect signaling") or start any "handshake" until it receives a valid VBUS signal (even if the device is self-powered). This is a major USB requirement. Overlooking VBUS functionality as a logical signal to start communication is a very common mistake in USB design.

@AliChen - what you keep missing is that the problem occurs when there is no active USB host to talk to, but power is present.  Stop thinking about the USB spec, and think instead about what the poster's device will experience if connected to a phone charger instead of a computer.  Of course this has simple solutions, if one is willing to spend some time understanding and modifying the code which implements USB peripheral functionality.

@Chris: yes, I am missing the problem statement. A powered USB port on non-operating computer is no different from a wall charger, so the USB device should not behave any differently, unless OP means charging functionality. By a set of functional explanation of how a normal USB interface works, I am trying to obtain clarification to the OP question, but apparently I have little success. If you have a firm grasp on the essence of the question, please provide a proper edit and make a clear statement of the problem. So far I failed to see any problem, except of brutal misuse of USB terminology.

The problem is that the poster's software hangs when it is not serviced by an operating USB host.  The problem arises because they are using a USB peripheral code library written by someone else, with internal workings they haven't really studied.

@Chris: Thank you for the clarification. Ok, then the device driver on Arduino side is totally botched - the support for fundamental USB suspend-resume functionality is missing. This is what happens when someone resorts to half-baked software disregarding interface protocol specifications.

No, it has nothing to do with suspend-resume.  You are still assuming that there ever was a functioning USB host.  There might have been, or there might never have been.  The poster's device needs to deal with both.

Let us continue this discussion in chat.

Upon having a clarification on what the problem essentially is, the answer is as follows:
(1) There is no way of knowing if the port is a wall charger or inactive computer port, initially. Therefore the initial device behavior must be identical in both cases – asserting pull-up on D+ (assuming it is USB 1.1 FS interface);
(2) However, if the port belongs to a computer, the connect event will awake the host, and the host will issue USB_reset, and perform device enumeration. There is no need to “send any Tx signal” or else, the host will perform this activity by itself. The Arduino software must remember this.
(3)  If the host decides to suspend the port (fell asleep), the device must transition into SUSPEND state, and Arduino software must remember this.
(4) If the port was initially in a state with USB totally disabled and does not wake up upon cable attach, see scenario (1);
(5) When/if the host computer is awaken, it will see USB attach status (D+ is up), and will start scenario (2).
In summary, the device (upstream facing port) must implement port functionality in full accord with port state machine described in USB2.0 specifications, Section 9 (Figure 9-1) and Appendix C.2 , Figures C-2 and C-3. As one can see, contrary to the assumption of OP, the port can be in more than two states, and Adruino software must have several different behaviors. Any half-baked implementation of the port state diagram is unacceptable and will cause some functional problem sooner or later.

Wow! Downgrade! I guess some people prefer hacking over engineering here. Amazing.

I did not downvote your answer. While I think this is probably the right approach, I'm wondering about the specifics of implementation and why the provided mouse/keyboard library doesn't implement any of this; is there some hardware limitation I don't know about maybe? (https://www.arduino.cc/en/Reference/MouseKeyboard) Secondly, given my know how, I don't know if I have the time or experience to implement something so complex. That sounds like several hundred lines of code just for proper USB spec adherence while my actual sketch is probably only 175 LoC in the first place.

The provided library doesn't implement this because it is not actually necessary for most purposes.  What is proposed here is a far, far, far larger task than needed.  The is issue is nowhere near as complicated as Ali insists on makes it out to be, but if you want to get distracted into pursuing this, that is your choice.

@Chris: As an engineer with 20+ years in semiconductor industry, yes, I insist that the USB device protocol must be implemented in full accord with specifications, with all states and transitions. The suspend-resume state of USB device are not designated as "optional", their implementation is a "must". If not, the device loses an ability to distinguish an active (but sleepy) host from a dumb charger, or exactly as the OP's situation illustrates. Specifications are written and world-wide adopted for a reason, they represent collective wisdom and experience of many seasoned engineers.

@amoose136: The reference list of Arduino kbd/mouse functions clearly lacking any interface calls to get the USB link status. Apparently the designers of this HID class did not consider the case when USB host might suspend the USB port. As I firmly believe, adherence to USB specifications is your solution. Yes, it is a serious effort. As far as I see, the USB hardware in ATmega32u4 does support "suspend/resume interrupts", so I guess the hardware is USB compliant.

Obviously, rewriting the entire USB implementation is uncalled for here.  If you really want to do that, you could consider making the changes to the upstream code yourself and submitting a pull request to the Arduino folks, but it is not going to get the asker of this question a solution in a reasonable time frame.  You seem somewhat ignorant of the fact that many devices on the market do not implement the full USB specification, but rather only the parts they practically need to.

It is not "re-writing", it is WRITING a CORRECT SOFTWARE. You seem to be ignorant of normal engineering practices if you insist on making a software that does not conform to mandatory USB requirements. You admitted that you are not familiar with USB hardware in Atmega processors, yet you are offering a hacking advice. Why would you suggest to take interrupts every 1ms from SOFs when the hardware already has a 3-ms "watchdog" timeout and can generate proper interrupt on bus suspend?   But then what you would do? Invent your own suspend-resume algorithm instead of following specifications?


text:
Is Sparkfun's MicroView OLED Arduino module a shield?
I'm getting confused by the Arduino terminologies:  shield, breakout, module.
Is this MicroView an Arduino compatible shield that will plug into Arduino's or Adafruit's Uno?

From the project page: The MicroView is a chip-sized Arduino with a built-in OLED.

BTW, it started as a kickstarter project.

No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.

Can shields plug into the MicroView?

I would say no because not all the Arduino Uno pins are exposed on the Arduino MicroView.  The MicroView only has 16 pins.  However, if you take the time to find out if the pins used for a particular shield are exposed on an Arduino MicroView and you create an adapter as the pins are likely in different physical locations, then you might get the Arduino MicroView to work with an Arduino Uno shield.

No,  you can't plug in Arduino shields to MicroView. Pin arrangements of Microview  and Arduino shields are different so it is not possible.

source: Stack Exchange

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

sort: votes


text:
Missing Libraries make no sense
I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

I'm loading RCLib which is part of this ArduinoLibraries family
RCLib requires PinChangeInt

So everything is in my sketchbook location right? Arduino > Preferences > Sketchbook Location
Still I'm getting compiler errors about missing libraries:
/Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
 #include "PinChangeInt.h"

I've even tried #include <PinChangeInt.h> Which makes more sense since this is a system library.
What is going on here?
The sketch I'm trying to run:
/**This is an example of using the RCLib with a mega and pinchangeint
 * This example isprovided as is by Jantje
 * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
 **/

#define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
#include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
  A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
#include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

Arduino v1.6.9 | OSX 10.11.4

The libraries should be in sketchbook location -> libraries. Try using #include <PinChangeInt.h> (note the less-than / greater-than).

I had downloaded PinChangeInterrupt through Arduino
Sketch > Include Library > Manage Libraries... > Filter your search... > PinChangeInterrupt > Install
I thought this is all I needed but I was wrong. This differs from the popular PinChangeInt library. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.

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


text:
arduino ethernet run php from sd card
I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.
does anyone know of a library that would let me do this?

Please clarify, are you expecting to run PHP code from the Arduino too? Because that won't work.

I want to be able to have a php document on the sd card, and the arduino to run it.

Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.
I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.
However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.
If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.

Thats not possible, only if you write yourself a PHP interpreter, which I suspect won't fit inside an Arduino.
You might be able to create your own interpreter for simple Get and POST requests, but bear in mind that HTTP, and even TCP are very sophisticated protocols to run on an AVR. You might want stick with simple things, preferentially with small messages as you also have very little RAM on those MCUs.


text:
How do I connect components to the Arduino with a motorshield?
How would I connect components to the Arduino with this motor shield?

Thanks :)

What components? I don't understand your question.

@NickGammon for example if i wanted to hook up a rc reciever? or just something to the arduino e.g. i want to use the pins of the arduino? thanks

If you are up for a little soldering, look into stackable Arduino headers. (Feel free to shop around for those, adafruit was just the first result.) You could then use male jumpers and a breadboard to connect anything that fits in a breadboard.
Just be careful to avoid pins that the shield is already using.

How would I attach them to the shield?

First, desolder the old headers on the shield, then follow the Make It section of this tutorial to attach the new headers.


text:
Getting "Undefined reference to vtable for {classname}
I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:
CommandPattern3.cpp.o:In function `DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
collect2.exe*:error: ld returned 1 exit status

Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

I have been through the code with a fine toothed comb, but cannot see what references are undefined.
Is there some Windows 10 utility that can examine the vTables and help me find what is missing?
The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.

The linker is trying hard to help you. Check DualMotorRomeo.h and that there is a destructor (might need to be virtual depending on the inheritance?).

I don't have the header file for DualMotorRomeo, but the linker is saying that a destructor has been declared (~DualMotorRomeo()) in the class header, but no destructor has been defined. If you didn't write DualMotorRomeo then the library needs to be updated.
Until then, simply add the following to one of your source files:
DualMotorRomeo::~DualMotorRomeo() {
} // DualMotorRomeo::~DualMotorRomeo()

That will also fix the vtable linker errors - the vtable will be included in the compiled file with this declared in it.


text:
Arduino wait for change in value
I am currently working on a project that involves steering wheels, and I would like a way for Arduino to wait for a change in value. A potentiometer is used and I would like a program to run (say, like lights blinking ) until there is a change in value of the potentiometer ( like an increase in 300).
Thanks in advance.
EDIT
I realized that I did not give enough information about what I want, so here is the actual task I am trying to achieve :
The lights goes on when :
Button is pressed
The lights goes off when :
The button is pressed again
or
Another button is pressed
or
Potentiometer increases or (only one of it) decreases by 300
Plus I didn't mention that the value of the potentiometer will be constantly changing so the old value for the potentiometer should be the one right after the button press.
Soooo sorry for the inconvenience caused. ( I am really bad at programming)

int oldValue;
void setup()
{
    oldValue = analogRead(A1);
}

void loop()
{
    int value = analogRead(A1);
    while( abs(value-oldValue)<300 )
        delay(1);
    oldValue = value;

    // start blinking lights here, as the value has changed by at least 300

}

Gerben thank you but I would like to wait for a change in value, and from my understanding analogRead just reads the value of the pin. Very sorry I didn't mentioned earlier that the analog value must not be zero at the start.

See my edit. It will trigger when the value is increased or decreased by at least 300.

Soo sorry but I updated the question

That's not really how this works (-:  First give it a try yourself (more than 30 minutes). If you can't figure it out, come back, and we'll gladly help.

A change in value is nothing more than that.  A change between a value then and the value now.
All you need to do is remember what the value used to be, and compare it with what the value is now. If the two have changed, and the change is big enough, then you do something.
And of course you have to remember that "now" will be "then" "next time".

Thank you Majenko !! ( Gerben basically put your words into c++)

No, Majenko put my code into words q-; (just check the timestamps)

Soo sorry but I updated the question

@SeeJianShin You might find this useful for introducing you to the concepts you need: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/

Figured it out in the end. Although my solution doesn't exactly fit what I wanted but it works in this case. I used the FMS Majenko mentioned like this :
Wait for potentiometer value to go beyond a certain value, then wait for it to come back to the value. If that happens then the lights stop blinking. Thanks guys( this is quite different from what I initially wanted but it is enough for what it is meant to do)


text:
Custom ATMega 2560 board won't execute Arduino code
I have a custom PCB with an ATMega 2560 microcontroller on it. To test if the ATMega was working properly, I uploaded the following code:
void setup() {
  Serial.begin(9600);
  Serial.println("Test setup");
  pinMode(6, OUTPUT);
  pinMode(30, OUTPUT);
  pinMode(31, OUTPUT);
  pinMode(32, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  digitalWrite(30, HIGH);
  digitalWrite(31, LOW);
  digitalWrite(32, HIGH);
}

The mentioned ports are connected to LEDs, 6 to an external LED and 30, 31 and 32 to LEDs on the PCB. Each connected in series with a 220 Ohm resistor.
The board is setup like this:

When uploading I am using a Arduino UNO as ISP and after uploading the Arduino IDE says 'Done uploading' without any errors, but the board is not showing any sign of executing the code. I have checked that VCC is 5V and RESET is HIGH after uploading. The text "Test setup" is also not shown on the serial monitor.
Does anybody have a clue why the board is not working?
Thanks on forehand.

There could be many reasons - the most common of which is that your crystal isn't running right. You'll have to show us your schematic and images of your PCB for us to help you.

Edited, good point on the crystal, I will check if it is functioning well.

Also make sure that your fuses are burned correct for your crystal source.

The crystal itself is working. I have added a picture of the board as well. A problem I found myself is that maybe the loop of the crystal and its capacitors is rather large, which may cause the problem.

As was pointed out the first time you posted this, your description doesn't really make sense.  If you are using ISP, then what does the bootloader have to do with it?  If you loaded the bootloader via ISP, you don't have a test program on there, and if you loaded the test program via ISP, you no longer have a bootloader...

Edited, I understand the confusion. I did not understand that the bootloader was not needed if I was using the Uno as ISP anyway. It is still strange that the code lighting up the LEDs is not working. Right?

When using an empty ATMega2560 you need to change the fuse settings, otherwise it will just upload your code but it won't execute.
This tutorial explains it very clearly:
Programming ATMega 2560 with Arduino UNO


text:
Arduino due + mcp2551
I am currently using an atmega328 along with the mcp 2515 and the 2551 for CAN communication in my systems.
However, I've now decided to upgrade to the arduino due for my operations. Can anybody tell me if the arduino due along with it's inbuilt CAN controller be used with the mcp2551 transciever to operate CAN successfully.
If not, can somebody also tell me if there are other alternatives I should look into. Thanks :)

The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN_TX and Can_RX and it's fine to use a 5V Transceiver like the MCP2551.
Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter,  like one of the following:

MCP2562
ATA6561
SN65HVD256
NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.
Cheers

The Arduino Due is definitely not 5V tolerant. From https://www.arduino.cc/en/Main/ArduinoBoardDue: "The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board."


text:
Neopixel Painter - Need to change few lines. Not sure where to start
My name is Maria and I'm learning programing in high school.
I'm working on a birthday present for my mom, want to make a mood light. Using light painter, a neopixel strip, and an arduino.
https://github.com/adafruit/NeoPixel_Painter
I found the part, which reads the bmp line by line a very innovative way to make custom animations.
But some tweaks are needed. (I've tried to make them, believe me, oh I've tried.) So, i was wondering if i can ask someone a favor and teach me how to modify the code (like, comment on parts that been changed.)
Basically, what I want to be changed is, to loop the current bmp until 'next' button is pressed, rather than hold the trigger. Also, I'm not sure if the code try to save power, but it can be disabled since it will run from a power supply.
Here is the part that makes you hold the trigger button (i think)
  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line
    if(stopFlag) break;                        // Break when done

    if(++block >= nBlocks) {                   // Past last block?
      if(digitalRead(TRIGGER) == HIGH) {       // Trigger released?
        memset(sdBuf, 0, N_LEDS * 3);          // LEDs off on next pass
        stopFlag = true;                       // Stop playback on next pass
        continue;
      }                                        // Else trigger still held
      block = 0;                               // Loop back to start
    }
    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }

And the complete code: https://github.com/adafruit/NeoPixel_Painter/blob/master/NeoPixel_Painter.ino
Anyway, Since I'm talking to an experts right now, I have this idea to remote control the code! from  another arduino!
My, probably retarded idea is, to run an IR remote code on a second arduion, than when it receives a signal, send a simulated button press to the first ardu playing the bmp! Is that even possible? Just wondering.
Cheers
Maria

I can't see anything there that tries to save power. Remote controlling should be easy enough, grab some IR transmitter examples. It should be easy enough to set up a transmitter on one Arduino, and a receiver on another. Experiment with that first, before trying to control lights.

I think you need something like this.
  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line

    if(++block >= nBlocks) {                   // Past last block?
      block = 0;                               // Loop back to start
    }

    if(digitalRead(NEXT_PIN_OR_SOMETHING) == LOW) {       // Next button pressed
      break; // Break out of for-loop
    }

    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }


text:
Do I need resistors or capacitors on this relay?
I'm using my Arduino to control a relay switch, which has an extension cord attached to it (see photo).
The relay is connected to the Arduino via pin 9, which is set to pinMode(9, OUTPUT);
Do I need any resistors or capacitors or diodes attached to this? Almost feels too simple, given I'm running AC power through the relay. But maybe no?
It definitely works, but I want to make sure I'm not going to burn something out (or down).

Majenko's answer describes how to switch a relay. However DO NO DO THIS. Breadboards are not designed for mains voltages or currents. If you are playing with mains power you need proper isolation.

Yes, that is too simple.
The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.
Google for "Arduino Relay" and you will find hundreds of thousands of examples.
In short, the circuit you need to create is this:

What's the purpose of the transistor?

It acts as a switch turning the relay on and off.

Is that not the function of the Arduino? Sending digitalWrite(RELAY, HIGH); through one of the pins to the relay switches the relay.

No. The arduino isn't powerful enough to switch a relay reliably. It can switch the transistor and then the transistor switches the relay. Technically the transistor is acting as a current amplifier..

I'm definitely successfully switching the relay with just the Arduino. So, if it's functioning, is there any real reason to use the transistor (for, say...safety purposes)?

The key word that I used was reliably. You are most likely drawing too much current from the port for sustained operation. That is bad. You have no back emf protection. That is even worse. I'd give it a week tops before you have to throw your Arduino away.


text:
How to detect cancelled download?
I have a server with files that may be downloaded.
How do I go about detecting when a download is cancelled by a client?
The function that handles reading files for download:
void readFile()
{

EthernetClient client = server.available();

// Open file for Reading.
SdFile webFile;
webFile.open(&root, &MyBuffer[1], O_READ);
if (!webFile.isOpen()) error("readFile");

do   // @ adafruit_support_rick's do-while loop
{
    int count = 0;
    char buffers[BUFSIZE];
    bool done = false;

    while ((!done) && (count < BUFSIZE) && (webFile.available()))
    {
        char c = webFile.read();
        if (0 > c)
        done = true;
        else
        buffers[count++] = c;
        delayMicroseconds(1000);
    }

    if (count)
    client.write( buffers, count);

} while (webFile.available());

webFile.close();

fileDownload = 0;  //File download has finished; allow logging since download has completed

delay(500);

MyBuffer[0] = '\0';

}

Well, assuming cancelling a download == incomplete download == client disconnected before server was done, you could create a flag like this at the top of the function:
bool dload_cancel = false;

Change the IF block, below the innermost WHILE loop, to this:
if (count){
  if (client.connected())
    client.write( buffers, count);
  else {
    dloadCancel = true;
    break;
  }
}

The flag will be set once your server checks and discovers that the client has been disconnected. You can check the state of the flag outside the DO-WHILE block to know if the download was completed or not.
if (dloadCancel){
  // client was disconnected; download did not complete
}

dloadCancel is also a better indicator of a completed download than your fileDownload flag.
You should also know that this:
if (0 > c)
    done = true;

is redundant. Its already taken care of by webFile.available().


text:
How do you change the state of an image on a TFT display when the associated pin changes state?
I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:
Example:
When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:
****myFiles.load(20, 55, 130, 130, "Power Medium.raw");****
So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.
Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.

It's quite silmple: just draw a box over the image the same colour as the background.
Either that or draw a different image over the top of the existing image.


text:
Chinese CH340 Arduino Uno - Burning stand allone chip
I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this CH340 UNO and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.
So what I tried was to use my FTDI cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.
So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.
As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...
UPDATE
Here's how my board look like:

Update 2:
OK, everything works great now! I just needed one pull-up resistor for reset pin.
Thanks everyone!

you also need to physically connect Reset (RST/DTR)

What is DTR I don't see that pin on my FTDI cable. So that is RTS pin from here ?
http://www.canadarobotix.com/serial-ttl/ftdi-cable-5v-vcc-3-3v-i-o

some FTDI breakouts/cables use RTS, others use DTR. Both ~kinda~ do the same thing: reset your MCU before uploading the sketch. (So the bootloader will know to expect something from the serial port). Note that some breakouts will need a 100nF cap in series with this connection, others wont.

Same thing, I'm still getting the same error.

How do you connect DTR or RTS?  Did you follow the full guide with pullup resistor and series capacitor?  When you switch from one serial device to another, you probably have to point the IDE at the new port, did you do that??  In theory you could use your CH340 board if you hold its onboard ATmega in reset.

I tried both scenarios but keep getting the same error. I put 100nF in series with RTS and Reset but nothing is changed. I don't have any resistor for reset... Do I need any? And yes I pointed in IDE to new port...and I also tried with all of these programmers.

I have updated my original question with my board image, please take a look.

What should be the value for that pull-up resistor?

Try Arduino ISP to flash standalone chip. Try to flash bootloader first as you didin't mention anything about it and bare chips are just empty.

I was able to successfully burn bootloader, I just had an issue with uploading sketch later, but that was my fault. I put pull-up resistor on wrong pin :) Everything is ok now.

I copy-paste your own answer. Please, accept it to close this question.

No problem, I will accept it. :-)

You said:
It just need a pull-up resistor for the reset pin!

authors: Илья Паймушкин


text:
VGAX library only allows 4 colors, library or hardware limitation?
I'm working with VGA DSUB-15 output, however VGAX only allows for 4 colors. I'm using an Arduino Nano that uses an 8-bit atmel chip, and I've seen many 8-bit computers of which have a bit more than 4 colors.

Is there any form or shape of VGA that uses composite output? The usual 15-pin VGA connector has separate analogue (baseband) signal lines for the red, green and blue components.

@HenningMakholm Ah, no. Will edit.

Google RGBI for more in-depth information about this phenomenon and how old computers with CGA graphics worked this way.

@winny RGBI has 16 colors.

@pipe Sure, but the principle of limited color space is transferable.

It's a memory limitation. The ATmega328 has 2 KB of RAM, and a 120x60 framebuffer at two bits per pixel (four colors) uses 1.8 KB. There's no room for more.

Thanks, is there any way i can get around this? Other than heavy optomization.

Use another microcontroller with more memory.

Are you using the Arduino to directly drive the VGA, or are you using a shield. If you're directly driving the display, I think the limitation is on the Arduino because with only 2kb or RAM, you can't really store all the pixel data. And the duino is also generating the high frequency vsync and hsync signals.

Try this: http://www.gammon.com.au/forum/?id=11608. Note: the code didn't work for me, but try it.

The link in the question leads to schematics that show the VGA output pins being driven directly by the digital output pins of the Adruino, with just some bridging resistors.

That's how you drive VGA directly without a shield.

So it may be possible to have more colours at a lower resolution.

That's what gammon said

The VGA interface uses full analog signals for Red, Green an Blue video. There is no limit to the color levels in the VGA standard.
However, it is not unusual to find that minimalist implementations of VGA in microcontroller products use Digital to Analog Converter (DAC) techniques with a limited number of bits of resolution.  For example, using two bits of resolution for Red and Blue, and three bits of resolution for Green so that the pixel information will fit into an 8-bit byte, etc.

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


text:
SIM808 module GSM working fine, GPS not working (No GPS ready message on power on)
I powered on my SIM808 module. It showed me following output:
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

It supposed to show GPS ready also.
I sent AT command and return ok.
However AT+CGPSPWR=? returns error. All GPS command showed error.
I think GPS is not initialized at all as i didn't see GPS message when module powered on.
Why is the GPS not working?

GPS Power On Command: AT+CGNSPWR=1 Get location: AT+CGNSINF

I am using sim 868 but when i give command AT+CGPSSTATUS, Its give me +CGPSSTATUS: Location Unknown
I tried to reset it to factory default and follow the command AT&F or ATZ
AT+CMGF=1
AT+CGPSPWR=1
type AT+CGPSRST=0
but still getting that error.
Why is the GPS not working?

You have a version2 module. Use AT+CGNSxxx instead of AT+CGPSxxx

AT+CGNSPWR=? workinf but AT+CGNSRST=? not working throwing error. similarly AT+CGNSSTATUS=? retunring error but AT+CGNSINF=? returning +CGNSINF: 1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,, which is wrong.

The version 2 module has a different instruction set so there are no AT+CGNSRST or AT+GNSSTATUS, see this pdf with the instruction set.

reference to code or datasheet could make this a good answer which could lead to upvotes and the ability to comment. Please consider adding to this to make it that little bit better. Thanks for your contribution!

Use AT+CGNSxxx instead of AT+CGPSxxx commands
ATGNSPWR=1 and ATCGNSINF to get location.
if you get following output
1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,,
It means your GPS is not set.
Try to put GPS antenna outside your room, on open space for 10-15 minutes.
GPS bulb will start blinking to confirm it is now ready for use.
Then use AT+CGNSINF.
Good luck.

Had the same problem with a Simcom868: AT+CGNSPWR=1 (for the GLONASS) and the most common AT+CGPSPWR=1 didn't work giving me back an ERROR. The Simcom808 needs 2A peak current so check if your power supply unit can reach that power and in case replace it;
then try the AT+CGNSPWR=1 or AT+CGPSPWR=1 again.

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


text:
Arduino uno unexpected void loop stop
I have a trouble with following, few lines code.
For some reason after few seconds Arduino uno stops responding into void loop section of code.
I tried to remove serial communication, all print and println without any success. Is the problem comming from MMA_7455.h?
#include <MMA_7455.h>
#include <Servo.h>

int servoPin = 9;
int servoAngle = 0;

Servo servo;

MMA_7455 accel = MMA_7455();
char yVal;
char yVal_bkp;

void setup() {
    servo.attach(servoPin);
    accel.initSensitivity(2);
    accel.calibrateOffset(1.0, 26.0, -69.0);
}

void loop() {
    yVal = accel.readAxis('y'); //Read out the 'y' Axis

    if(yVal_bkp != yVal + 2 || yVal_bkp != yVal -2)
    {
        servo.write(90 + yVal);
        yVal_bkp = yVal;
    }
}

P.S. Servo is normal G90

accel.readAxis() returns unsigned char. You are using char which is signed in AVR GCC https://gcc.gnu.org/wiki/avr-gcc

Yes, it returns only positive values, I alredy verified, but if you assign this value to char yVal it returns signed value (ex -12) in Serial.print(yVal, DEC);

Have you checked that MMA_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.

Thanks for reply. After delay(20); add, correct execution is going for much more time, but anyway stops after. Increased also to 40, same result...


text:
Servo Speed Changer with Buttons
ok so yesterday i was in trouble with the buttons, with help from you i got over it and everything worked fine with the 1st speed of the servo, then i added the other 2 speeds and it looks like it all messed up... the buttons don`t respond as they should and the servo moves very weirdly.
Here is the code:
const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
#include <Servo.h>
Servo servo1;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  servo1.attach(9);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int position;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

      if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
            x++;
            Serial.println("on1");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x--;
            Serial.println("on2");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
       }
          delay(1000);

lastButton1State = button1State;
lastButton2State = button2State;

  if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position < 360; position += 2)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position <360; position += 5)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
        for(position = 0; position < 360; position += 10)
          {
            servo1.write(position);
            delay(20);
          }
    }
}

There may be better ways to mitigate button bounce. Check this link for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.
Determine if the servos you are using are capable of the range you are demanding.  Some servos only travel from 0 degrees to 180 degrees.  Your code is asking the servo to travel from 0 degrees to 360 degrees.  Also, it is unlikely that any normal servo can travel this far.  Most servos use a potentiometer as a feed back sensor.  And most potentiometers can only be turned to something less than 1 full revolution.
It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops.  Understand that normal servos can not make complete revolutions.  They need to stay within their designed limit of rotation.  If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.
Consider your last loop.  You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps.  You are allowing 20ms per step.  That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second.  Some but not all servos can move that fast.

so i should add more delay? another way to button bounce i don`t really know... can you tell me more?

If the code restricts you pressing the button no faster than once a second and you are fine with that, you can leave that part for later.  (Unless there is another problem with that bit of the code.) However you need to tell the servos to go to zero degrees & give the servos some time to do this before each of the 3 loops.  Finally, you need to determine how fast the servo can actually respond.  I might try increasing the 20ms delay for all loops equally until I noticed a speed difference for the 2 fastest loops.

that is actually a good idea, i just got home and i`m gonna try this out and tell you how it worked out

ok so trying this out still not a solution, i tried removing the servo part of the code and it looks just fine, the buttons work perfectly and the leds light up corespondingly. I think that the problem stands in making the servo rotate endesly. At the start x = 0 so nothing happens, i press the button once so it adds 1 to x, x = 1. After the x = 1 the code enters a loop from which it cant get out, it must move the servo continously so it doesnt allow any other functions to work out, like the buttons. Just an idea i don`t know if this is true.

The stack exchange format is not well suited for code debugging.  Unless there is a specific question about the code, it is difficult to adhere to the 1 specific question and 1 concise answer format.  That said, there may be problems with you code.  For instance, I would be annoyed that nothing happens after pressing a button for at least a second.  Second, you never control your "x" counter. It could get very large or it could also go negative.  And who knows what may happen if you told the servo library method to set the servo to a negative angle. Did you at least try to add the new delays?

i know it's not the best for that but it's my only solution. I don't know any other forum where i could find people that could help and i don't know irl people with programming experience. I'm willing to help and work a lot but i sometimes need some help :) I did everything that you said, adding the delays, lowering the servos speed and giving them time to go to 0 degrees. Although i think it would be pointless to tell the servo to go everytime to 0 when i actually want it to make it spin continously how it does for a fan for example. Thanks for taking your time and helping me man!

and for the X counter, this would be permanently controled by a human so i didn't want to make the code more complicate by adding some limits to x

Ah, I think I see the problem.  A normal servo can not rotate more than once!  There is a POT or potentiometer inside the servo and, as the volume control in an old amplifier, can only be rotated about 300 (maybe 330) degrees.  There is something called a Continuous Servo.  Instead of position, you control the forward and reverse speed.  That is to say, you will know how fast a Continuous Servo is rotating but you will not know its position at any given moment. For your code to work, you need to start thinking about moving your servo like the wipers move on your car's windscreen or windshield.

You should also be aware that some servos will not rotate more than 180 degrees.  If you have such servos they may act unexpectedly if asked to go beyond their physical limits.

Ah, I understand. I think i need to go get a Continuous Servo as you said. I hope i find one soon and buy it. When i do so i will redo the code and update you on the situation. And yes i think my servos go only to 180, i just tried a simple code to make it to 270 and it didn't work that far. Thank you very much for talking your time and helping me kind sir! Have a great day and I`ll update you if it works with the other Servo. (also sorry for my bad English, not my 1st language)

Just to be clear, normal servos are used to position things.  Like steering a robot.  Continuous servos are used to propel things.  Like pushing a robot.

yeah yeah I got the idea, this servo came in the box with the arduino as a starter pack. I thought I couldn't control a normal motor so I chose this one instead. Never thought i couldn't actually fully rotate it at different speeds and could only do it until a certain point. Thanks for clearing that out for me! :D


text:
How to convert char[] to int with fail\success control?
this is more like C question, but i failed to google this.
i expect a command parameter in char[], but there may be no argument passed at all, so i need to try to parse this char[] to int and if there is garbage instead of a number, notify user.
i also need to be able to parse negative (with -sign char) numbers from char[].
how can i do this? thanks.

Try http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga3a1fe00c1327bbabc76688a7a1d73370.html

Alternatively http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdio_1ga5507d0e1bbfd387fbb2ffcfd8f5dca6f.html that will allow fail\success control.

Easiest is maybe http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1gaf8ce3b8dae3d45c34c3b172de503f7b3.html then you can check that 1) a number was parsed, 2) if there are any extra characters, etc.

It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it did or did not parse, but not necessarily whether it is valid in some respect.
If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.

but sscanf did nice job, returning 0 if it can't fill the int variable, thus telling that there is no valid int argument passed.


text:
What does 16u and 128u mean?
The below is a snippet of a code for operating SI4455 Rf module with Arduino. I have some doubts which I'd like to seek some help in clearing.
byte numOfBytes = *pSetPropCmd++;

    if (numOfBytes > 16u) // What does this 16u mean?
    {
        /* Initial configuration of Si4x55 */
        if (SI4455_CMD_ID_WRITE_TX_FIFO == *pSetPropCmd)
        {
            if (numOfBytes > 128u) // What does this 128u mean?
            {
                /* Number of command bytes exceeds maximal allowable length */
                return SI4455_COMMAND_ERROR;
            }

            /* Load array to the device */
            pSetPropCmd++;
            WriteEZConfigArray(numOfBytes - 1, pSetPropCmd);

            /* Point to the next command */
            pSetPropCmd += numOfBytes - 1;

            /* Continue command interpreter */
            continue;
        }

In the above snippet, what does 16u and 128u mean?. I think its meaning u for unsigned, but still not clear as what does 16u and 128u mean.
Rgds
VD

It means that it is a unsigned value. Because the compiler checks for signed and unsigned in the same operation this is used (amongst others) to avoid warnings.
This is explained on stackoverflow here https://stackoverflow.com/questions/14844119/define-foo-1u-2u-4u-what-does-1u-and-2u-mean

ok does it mean an unsigned int with a decimal value 16 for 16u and unsigned int with a decimal value of 128?. And is it valid to perform "numofBytes > 128u" check in the snippet, since numofBytes is a byte?

Please ckick the answer is usefull :-)

The u just types the value as unsigned. You also have f which is float. which makes 1.0 and 1f the same thing.


text:
Sending data via SoftwareSerial results in garbled reception
My overall goal is to have an Arduino Uno with an Ethernet Shield send a short (5-character) string via a SoftwareSerial connection and a UDP packet when I press a button.
The device which is receiving the serial message is fixed at 9600 baud, no parity, one stop bit.
For the purposes of debugging my serial problem I have removed the Ethernet Shield. I mention it above only so that potential responders understand my intended final hardware configuration.
I am using a USB/serial adaptor and Kermit to check the serial output.
C-Kermit>show communications

Communications Parameters:
 Line: /dev/ttyUSB0, speed: 9600, mode: local, modem: none
 Parity: none, stop-bits: 1 (8N1)
 Duplex: full, flow: none, handshake: none
 Carrier-watch: off, close-on-disconnect: off
 Lockfile: /var/lock/LCK..ttyUSB0
 Terminal bytesize: 8, escape character: 28 (^\)

My first job on receiving garbled characters was to test my test rig. I connected the predecessor device and was able to receive the expected characters. (It cannot send the UDP packet, which is why it is being replaced.)
One button on the original device sends "X0401", exactly as expected:
$ od -b oldserial⋅
0000000 000 130 060 064 060 061
0000006

Another button on the original device sends "X0402" (which I expected) and also a whole bunch of nuls, which I didn't expect:
$ od -b oldserial⋅
0000000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
0000020 000 000 000 000 000 130 060 064 060 062
0000032

In any event, it seems that the terminal is actually receiving 8N1 data at 9600, so I can trust what it shows me.
I was going kind of nuts trying to figure out what was the problem, because nothing I sent from the Arduino came through properly. Then I stumbled on a suggestion that 'U' made a good test character because an ASCII 'U' is 0123 or 01010101. Indeed, I am able to send sequences of arbitrary length and so long as they contain only the 'U' caracter, they come through correctly.
(I've got three buttons and three different sets of messages, so my tests tend to run in sets of three attempts.)
Next step is to reintroduce a little bit of variety and see what comes through:
Here I send "UUUUU", "UUEUU", and then "UUQUU". 'E' and 'Q' were chosen because they are each just one bit different from 'U'.
What I saw when I sent the first message was:
UUUUU

Then sent the second:
UUUUUUU]UU

Then the third:
UUUUUUU]UUUUWUU

Kermit was also storing the session to a log file, which looked like this:
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125
0000005
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125 125 125 135 125 125
0000012
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125 125 125 135 125 125 125 125 127 125 125
0000017

Somehow, 'E' (0105) turned into 0135 and 'Q' (0121) turned into 0127. In each case, a sequence of three 0 bits were turned into 011, while no 1 bits were changed.
Sending:
UUAUU

Got me:
$ od -b serialUsequesnce2⋅
0000000 000 125 125 137 125 125
0000006

The five consecutive 0 bits in 01000001 were turned into 01111 to give me 01011111 or 0137
Longer strings get weirder.⋅
Test strings of:
UU0123456789UU
UUABCDEFGUU

Got me:
$ od -b serialUsequesnce3
0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 000
0000016
$ od -b serialUsequesnce4
0000000 125 125 137 257 335 325 315 305 125 125 001
0000013

Now I'm seeing not just bits being replaced, but I'm getting fewer characters than I'm sending.
Since I wasn't getting good data from my SoftwareSerial port, I thought I would listen in on the USB traffic, which is also set to 9600 baud.
This text from the Arduino monitor:
UUAUU
Start button pressed
UU0123456789UU
Stop button pressed
UUABCDEFGUU
Light button pressed

Came through as this:
$ od -b serialUSB
0000000 125 125 137 125 125 171 275 165 324 332 027 277 073 025 027 027
0000020 041 043 277 037 031 031 065 067 345 353 000
0000033
$ od -b serialUSB2
0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 345 353 131
0000020 027 041 037 277 073 025 027 027 041 043 277 037 031 031 065 067
0000040 345 353 000
0000043
$ od -b serialUSB3
0000000 125 125 137 257 335 325 315 305 125 125 225 353 147 055 061 057
0000020 027 277 073 025 027 027 041 043 277 037 031 031 065 067 345 353
0000040 000
0000041

I'm guessing that I'm doing something wrong with the hardware, but my serial connector simply has pin 5 connected to ground and pin 2 connected to digital 6 (or 2 when watching USB traffic).
I'm powering the Arduino Uno via its USB connection. When I checked the voltage at Vin and the adjacent ground, I got 4.51 volts.
/*
Listens on three buttons:
 - Start
 - Stop
 - Lights

Sends serial messages to a Color Kinetics iPlayer 2
9600 baud, 8 data bits, no parity, 1 stop bit
Commands are
 - X0100 Lights Off
 - X0288 Lights at half
 - X02FF Lights at full
 - X0401 Set Show #1

Created 2016-07-13
by David H. Silber
(Cribbing extensively from the Arduino examples.)
*/

#include <SPI.h>         // needed for Arduino versions later than 0018

#include <SoftwareSerial.h>
SoftwareSerial softSerial( 5, 6 ); // RX, TX

const int noButton = 100;
const int startButton = 2;
const int stopButton = 3;
const int lightButton = 4;
bool startTriggered = false;
bool stopTriggered = false;
bool lightTriggered = false;
int lastTriggered = noButton;
unsigned long lastButtonTime = 0;

const char startSerial[] = "UUUUU";
const char stopSerial[]  = "UUEUU";
const char lightSerial[] = "UUQUU";

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  pinMode(lightButton, INPUT);

  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Starting");  // prints hello with ending line break⋅

  // set the data rate for the SoftwareSerial port
  softSerial.begin(9600);
  delay( 1000 );
}

void loop() {
  // read the state of the pushbutton value:
  startTriggered = ( HIGH == digitalRead(startButton) );
  stopTriggered = ( HIGH == digitalRead(stopButton) );
  lightTriggered = ( HIGH == digitalRead(lightButton) );

  if ( startTriggered && (startButton != lastTriggered) ) {
    action( "Start button pressed", startSerial );

    lastTriggered = startButton;
    startTriggered = false;
  }

  if ( stopTriggered && (stopButton != lastTriggered) ) {
    action( "Stop button pressed", stopSerial );

    lastTriggered = stopButton;
    stopTriggered = false;
    }

  if ( lightTriggered && (lightButton != lastTriggered) ) {
    action( "Light button pressed", lightSerial );

    lastTriggered = lightButton;
    lightTriggered = false;
  }

  buttonTimeout();
}

void action( const char usbMessage[], const char serialMessage[] ) {
    Serial.println( serialMessage);⋅
    Serial.println( usbMessage);⋅

    softSerial.write( serialMessage );

    lastButtonTime = millis();
}

void buttonTimeout() {
  if ( millis() - lastButtonTime > 2000 ) {
    lastTriggered = noButton;
  }
}

A friend came and visited me with his oscilloscope and we determined that the 'serial' output from the Arduino was not actually RS-232. It was only an accident that any data came through at all.
I think my answer will be to add https://www.arduino.cc/en/Main/ArduinoBoardSerial or something like it.
One of our realizations was that we needed to level shift the output, searching on "arduino serial level shifter" led me to http://forum.arduino.cc/index.php?topic=18689.0 which in turn led us to the MAX232 chip and boards that provide it.
It would be a good thing if there were some mention in the Arduino documentation that the 'serial' connection one would get from it was not actually RS-232.

RS232 is old. And people have implemented it in many ways.  So we are all bound to have problems with RS232 at some point.  Depending on where you got your RS232 signal from, it could have swung as high/low as 15V / -15V respectively.  So do check to make sure your Atmel processor is still working as expected.  Good luck

Arduino serial is UART 5V Logic. Just in case.

Of course, its not RS232. That protocol defines mark and space voltage levels, as well as other signals to be used in asynchronous serial communication. RS232 does not define the actual signalling protocol used on the TX/RX lines. That protocol is a lot older and encompasses more than RS-232. The Uno is a 5V device and has no built-in RS232 level shifter, so the serial output is directly from its UART peripheral or in your SoftwareSerial case, merely a result of toggling the pins at the desired baud rate. Not unlike digitalWrite().


text:
Best way to read CSV from SD card and store values by date
I am starting a project in Arduino and I need to read data from an CSV stored in an SD card. The data is stored as the following:
id, value, date
What I want to do is read the file, filter by date and then store the values by id. Each id will correspond to different values from that same date.
Is it possible to do something like this?
Thank you very much for your advice.

Since and Arduino does not know about SDCards you will have to use an SDCard shield and that shield's library to access the card.  Once you have decided on which shield / library you are using - modify your question identifying which you picked.  Then people can answer your question specifically.

Also, most Arduinos run on embedded processors with very limited RAM.  So there is an upper limit on the size and number of variables you can keep at hand.  For example, you probably could not read and keep 100,000 of your records at hand.  But you could read 100,000 records and keep, say, 100 records or maybe even several thousands at hand.

It scarcely matters which hardware is used.  But it is true that limited RAM may mean the algorithm has to read through the source data many times, pulling out only what is of interest for one iteration at a time.  Or else, the destination data will have to be written with large gaps between each distinct set - in effect, it could be like sorting things into boxes, but having to be sure that your boxes are big enough that none of them will end up heaped aboved the rim.  Generally speaking, an Arduino is a poor  choice for data processing.

This is not arduino-specific. Have you tried searching for "parse csv c++"?

Actually, you can sort 100,000 records, given enough time, and being able to save them back to the sd-card. But it may not be as efficiënt and also wear out the sd-card raster. You could check every two records, and swap them if the second is higher than the first. If you keep doing this until nothing has to be swapped in a whole iteration, it's sorted.

I highly suggest checking out this YouTube video (https://www.youtube.com/watch?v=5v5A3j7Rrco), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:
float id = 0; //used to provide a numbered ID to each data point

void setup(){
//initialize all your once-run variables and such
}

void loop(){
  //Write Log File Header
  File logFile = SD.open("NAME.csv", FILE_WRITE);

  if (logFile){
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

    String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }

  else {
    Serial.println("Couldn't open log file");
  }
}
}

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:


text:
calling a timer when a button is pushed
I'm trying to call a function to keep an LED on for a certain amount of time. The function is called when the button is pushed but the LED stays on. I used the same code in the void loop before moving it into a function and it worked.
const int ledPin2 = 2;
const int buttonPin7 = 7;
const unsigned long onTime = 1000;
unsigned long previousMillis = 0;

//
void timer(){
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    if (currentMillis - previousMillis >= onTime){
        digitalWrite(ledPin2, LOW);
        previousMillis = millis();
    }
}

void setup(){
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(buttonPin7, INPUT);
}

void loop(){
    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timer();
}

Are you trying to create a monostable multivbrator?

When your code:
if (currentMillis - previousMillis >= onTime){
    digitalWrite(ledPin2, LOW);
    previousMillis = millis();
}

was in the loop, it was executed multiple times, so when if (currentMillis - previousMillis >= onTime) eventually became true, it would set ledPin2 LOW again.
Now that you moved it to the timer funtion, it only gets executed once (and if (currentMillis - previousMillis >= onTime) never gets a chance to become true).
You need to introduce a loop in the timer function. It also looks like you have your currentMillis / previousMillis messed up. I think you are looking for something like this:
void timer(){

    unsigned long previousMillis = millis();
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    while((currentMillis - previousMillis) < onTime) {
        // wait for a bit
        sleep(10);
        // update currentMillis
        currentMillis = millis();
    }

    digitalWrite(ledPin2, LOW);
}

This did work really well. I do have an issue though. I setup another button and LED and used the same code while changing the variable names. If the second button was pressed when the first LED was on the second LED wouldn't turn on. If the first LED was off then the second would turn on if the second button was pressed.

Ask a new question, and post your code...

Your code says
if (buttonState == HIGH) timer();

So... what will it do if buttonstate is LOW? Sorry, but the answer is "nothing". You don't have any code to tell it what to do when the button is in the opposite state.
What you should do is check the button, and if it's pressed (whether that's HIGH or LOW depends on your circuit), then light the LED and start the timer (assign to previousMillis).
Then, regardless of the state of the button, check to see if currentMillis - previousMillis >= onTime. If it is, then turn off the LED.

I had the LED write low in the timer function. The button was just calling the function and when the time elapsed it would tell the ledPin to write LOW.


text:
Manually Declare Global Variable
Is it possible to manually declare a global variable that is inside of a function. The only current way I know how to do so is to declare that variable within the setup() function or simply outside of any function, but I was hoping there was a way to manually declare a variable as global so that I may call one variable from within one function in another function.

You need to research 'Scope'.
Your variable has to be at the same level as all functions that will use it.  So at a simple level the answer has to be no.
int variableOne = 0;
void setup ()
{
  variableOne = 1;
}
void loop ()
{
  variableOne = 2;
}

The above code will work, but if you move int variableOne = 0; inside either function then it won't work, because the variable will not be in scope in the other function.
You can use parameters to functions.
void AFunction (const int& variable);

Will let you pass a single integer value to the function from the parent.  You can't change that value, because of the const qualifier.  If you remove the const then the & means pass the parameter by reference, which means you are passing in a reference (pointer) to the variable in the parent function and you can change it.  A better way to change the parent's value is to return a value from the call.
int AFunction (const int& variable);

So you could use this like this:
int AFunction (const int& variable)
{
  return (++variable);
}
void loop (void)
{
  int value = 0;
  value = AFunction(value);
  // value now == 1.
}

You could use a Singleton class, but this is hardcore and I'm not sure you would see any real benefit on an Arduino.  A class is a grouping of related function and variables that you see in libraries and a Singleton class means there will only ever be one during the lifetime of the program.  In this way you can declare an instance of the class (i.e. CSingleInstanceClass onlyOne;) and then retrieve/set data from the setup and loop function, i.e.
void setup ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  onlyOne.SetVariableOne (1);
}
void loop ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  Serial.println(onlyOne.GetVariableOne());// Prints 1
}

Hope that helps.

Thank you so much! I have decided to declare the types above the setup function, even though I understand this takes up a bit of dynamic memory, but not  much to worry about. I really appreciate the thoughful response, and will definitely come back to this post in the future!

@JonathanA: Types do not consume memory.

Global variables use 731 bytes (35%) of dynamic memory, leaving 1,317 bytes for local variables. Maximum is 2,048 bytes. This is what I was referring to.

Types are the type of the variable, so int or char.  It is referring to what you think, its just the word you used was a bit wrong.  If memory is that much of an issue (I don't think it is yet) then you could look at using external RAM, an additional IC, but that will be slow compared to main RAM.

even though I understand this takes up a bit of dynamic memory

There is no way around that. They have to go somewhere and that place is RAM (exception: constants could be stored in flash).
Another variation (which goes beyond your question) is that a parent function could declare and build a collection of data in a local array or struct and pass a pointer to it to any sub-functions. It still takes RAM, but it will be on the parent function's stack, so only for the duration of parent function's execution(s); it will be released when the parent function exits.

Appreciate it JRobert!

Please note that 'Scope' of a variable is limited inside the block ( a block starts at { and ends at } ), and that variable cant be accessed outside the block.
consider life time of a variable as well. using the keyword static may can help you some times. refer this link.


text:
Read and write on the same node (central) using an RF24 network on Arduino
I want to send and receive on the same node using the RF24Network library, but I'm unable to do so even when I use radio.StopListening().
Here is the code:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 0);
}

void loop(){
  network.update();
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
    // I WANT HERE TO SEND BACK TO THE TRANSMITTER but I'm unable to do that
    radio.stopListening();
    payload_t payload = { 2000, 15444452 };
    RF24NetworkHeader header(2);
    network.write(header, &payload, sizeof(payload));
  }
}

Second Node:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};
firstExec = 1;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 2);
}

void loop() {
  network.update();
  if(firstExec) {
    radio.stopListening();
    payload_t payload = { 2000, 5555555 };
    RF24NetworkHeader header(0);
    network.write(header, &payload, sizeof(payload));
    radio.startListening();
    firstExec = 0;
  }
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
  }
}

Could you post the part of your code you are having problems with?

How about including your attempt to send data so we can see where you went wrong?

Sorry for that, here is the full script with the sending code.

How about the code for the other node?

Sorry for missing the network.update() because i copied just the necessary code and as I always put this in the top of the loop I missed it up when I copied

I'm voting to close this question because it has been abandoned in unanswerable form for over a year.

The library says you must include network.update() in loop() for the nodes to be in sync. Place that call at the top of loop() in both nodes.


text:
Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer?
I looked up the question before, but they only gave answers for boards that are not the Uno. Is there any way to make it so when I press a button on my board, it registers as a key press on my computer? I'm trying to make a flight controller for PC sims.
Thanks!

We already have a question on this very topic, we really don't need to cover it again.

Not without extra software on your computer side.
However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.

Or you could change the firmware on the ATMega16u2 on the UNO. But that isn't for the faint of heart.

Yes, it came to my mind too, but FT232 or CH340 can be used in some cases (mainly if it's clone)

You'll need something on the Arduino that sends an event to your PC whenever the button is pressed. The easiest version of this would be the Serial channel over USB.
Second, you'll need a program running on your PC that receives that Serial message and generates your desired keyboard and mouse events.
In Windows, you can generate system wide keyboard and mouse events fairly easily using the Windows API. This would allow you to click a mouse, or keyboard button when inside of most programs written in Windows. https://msdn.microsoft.com/en-us/library/ms171548(v=vs.110).aspx
That said, you can have problems sending spoofed events to video games that don't use standard Windows forms. You might find this answer helpful from StackOverflow - https://stackoverflow.com/questions/7320424/c-win32-simulate-keypress-with-directinput

EDIT: check @JohnBurger 's comment. THIS is NOT good for the UNO.
You can connect your Arduino as a keyboard to the computer. There is a Keyboard Arduino library you can use. Here is a reference:
KeyboardWrite
For example this line of code will react just like you pressed A on your keyboard:
Keyboard.write(65);

Note the first line of the parent Keyboard [https://www.arduino.cc/en/Reference/MouseKeyboard] reference page: "These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer" - in other words, not the Uno that the questioner was asking about.

@JohnBurger sorry, you are right! my mistake....

You can do USB HID device on any AVR or Arduino chip without USB hardware interface by bitbanging on any 2 DIO:
https://www.obdev.at/products/vusb/index.html
Supports 4 endpoints (like 2 mouse and 2 keyboard, if makes sense :). Sure no additional software or driver is needed on OS side (default drivers shall be ok if correct VID/PID specified).
EDIT:
Seems 2 endpoints are required for USB HID keyboard. If remaining 2 is enough for USB HID joystick, it could be useful for flight sim.


text:
Wifly Library that works with RN171
Does anyone know of a library that works with the WiFly-RN171?
I've tried all that I could find (WiFly, WiFlyHQ and WiFlySerial) but none of them work.
WiFly and WiFlySerial both hang on WiFly.begin().
WiFlyHQ fails to enter command mode and hence proceeds no further.
I'm using the WiFly-RN171 with an Arduino Uno and Communication Shield (XBee, Bluetooth, RFID) - XBee Shield as seen below.
Has anybody gotten this configuration to work?

I have the same configuration and it works (Arduino UNO rev3)
I used WiFlyHQ library. Just be carefull with the serial.
Serial.begin(9600);
...
if (!wifly.begin(&Serial, NULL)) {
   ...

Upload with serial select then put it on USB and then open the monitor.


text:
Constantly read analog in in SWITCH/CASE setup
I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.
CODE HAS BEEN UPDATED
//-------------------------------------------------------
// BUTTON AND POT - TEST
// KNOWN ISSUE - POT ONLY TAKES ON READING
// vonderasche
// 7/28/2016
//-------------------------------------------------------

const int BUTTON_PIN = 9;
const int LED_PIN = 3;
const unsigned long DEBOUNCE_TIME = 50;

int val = 0;
int pot = 0;

int state = 0;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

bool button_press()
{
    static bool last_state;
    static unsigned long last_state_change;
    unsigned long now = millis();

    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

void loop()
{

    unsigned long now = millis();
    static enum { OFF, ON, POT } state;

    if (button_press()) switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        state = ON;
        Serial.println(state);
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        state = POT;
        Serial.println(state);
        break;
    case POT:
        Serial.println(state);
        int Mode = button_press();
        while (val < 1023) {
            val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            state = OFF;
            break;
        }
    }
}

The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.
So, you might do something like this:
case POT:
int Mode = digitalRead(BUTTONPIN);
while(Mode == LOW) {
    val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        state = OFF;
        break;
        Mode = digitalRead(BUTTONPIN);
    }
}

If you want to use the debounce, do something like this:
static enum { OFF, ON, POT } state;
unsigned long now = millis();
int x = 0;

while (x == 0) {
    switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        if (button_press()) {
        state = ON;
        }
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        if (button_press()) {
        state = POT;
        }
        break;
    case POT:
        val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        if (button_press()) {
        state = OFF;
        }
        break;
    }
}

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.

Is there another option for the while condition. I have my button press setup as a boolean function for debouncing.

You could potentially put the while switch statement in a loop. That way, it would read the whole code every time it goes through the loop, so if you press down the push button, it will switch the state, and if you don't press the push button, it will just do the same state again. That way, it WILL change the LED based on the potentiometer every time you adjust it, AND it ill work with a software debounce. Hope this helps!

Im sorry can you please be more specific. Maybe some pseudo code.

I've edited my post. Please tell me if that works, and if it doesn't, can you post the code for "button_press()" so I can understand the code better.

i updated the post with the full code I have. It was interesting to see the use of a while statement. The LED would turn on but it wouldn't cycle thru the different states when the button was pressed.

authors: ธรัช กมลธนิศร


text:
Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno
I have an Arducam-Mini-5MP with Arduino UNO R3. I am running the unaltered example ArduCAM_Mini_OV5642_Video_Streaming to the arduino and am running ArduCAM_host_v1.0.exe on my PC with huge successes.
In this state, I can reliably take photos at low resolution (up to 1280x720) in all tested settings. However, when I go to higher resolutions (2592x1944, 2048x1563, and 1920x1080), certain situations result in consistently corrupt images all with the exact size of 524288 bytes.
The images are corrupted whenever I point the camera outside my window, and images are fine when taking photos inside my house. At 1280x720, a typical photo inside my house is 80kb and a typical photo out the window is 190kb (more than double in size). I suppose some content of the photo is impacting the jpg compression?
Unfortunately, images are corrupt 100% of the time for the actual subject I want to take; but the camera works perfectly when I'm testing it indoors. In my scenario I can only capture 0.8MP before images become corrupt.
The frame buffer limit for Arducam is 512kb, so am I just running up against the constraints of the hardware? I feel a bit fooled because I bought a 5MP camera and can only take 0.8MP photos with it.
Is my understanding of this failure correct -- is this the frame buffer size being hit by conditions impacting jpg compression? Are there Arducam shields available with higher frame buffers? Can I avoid this situation somehow?

You're getting corrupted images of size 524288 bytes consistently. It so happens that 512 kB * 1024 bytes/kB = 524288 bytes. You said it already; you've most likely hit the buffer's limit. I suggest you contact the Arducam support team concerning other shields with larger frame buffers.

Thanks for confirming that. So I guess I just wonder why do they put a 5MP camera onto a shield that only reliably supports 0.8 MP image sizes? Also wondering if there is a way to increase compression ratio or if there is something I'm missing here to make this design make more sense.

Okay - I have reached out to ArduCam team. https://github.com/ArduCAM/Arduino/issues/66

The problem may also be on the Arduino side. E.g. The SD library might not support files larger than 512kb.

The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).
To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04.  myCAM.wrSensorReg16_8(0x4407,0x09);
To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf
Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.


text:
How to connect ESP8266 12e directly to Arduino Uno (without shields)
I have an ESP8266 12E module and I'm trying to connect it to arduino, without any shields or whatsoever. I've looked everywhere but all I can find is about ESP-01 or with a NodeMCU. I'd like to do the bridge manually, but I don't know which pins I should ground and which pins I should power.
This is my current setup:

And the following sketch:
#include <SoftwareSerial.h>

//RX pin 2, TX pin 3
SoftwareSerial esp8266(2, 3);

#define DEBUG true

void setup() {
  Serial.begin(9600);
  esp8266.begin(115200);
  sendData("AT\r\n", 2000, DEBUG);
  delay(1000);
  Serial.println("Firmware version:");
  delay(3000);
  sendData("AT+GMR\r\n", 2000, DEBUG);
  Serial.println("** End **");
}

void loop() {}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }
  if (debug)
  {
    Serial.print(response);
  }
  return response;
}

When run, I get the following output:
Firmware version:
** End **

On the module, the led flashes when I power it up, but after that it remains off. I've already tested the voltage regulator with ReadAnalogVoltage, and the output was 3.33v, so it is working.

For future reference, here's a link of my final (working) pinout

And just a heads up: if using Arduino Mega, not all pins can be used as Software Serial, see this post for more details. Currently I'm using pins 10 and 11 and it's working fine.

Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):
It is the ESP's Rx pin that needs the voltage divider.
Also pullup the ESP's reset pin.
Update:
ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

How can I pullup the reset pin? Also do I need to pullup it just for
  initial setup (changing baud rate and such) or should it be pulled up
  at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.
Update 2 (wiring):
You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.
I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.
Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.

I think I fumbled that too initially. How can I pullup the reset pin? Also do I need to pullup it just for initial setup (changing baud rate and such) or should it be pulled up at all times?

I've edited my question with my current setup based on what you and Len said, yet it still doesn't work.

Your comment pointed me in the right direction. After connecting all the pullups to the power supply, I had to ground/pulldown GPIO15 pin, and now it works! I'll attach a picture of my wiring as soon as I can. Thanks!

Oh boy, lot of things can be the problem here.
First of all: a voltage divider using 10k-10k has an output of 2.5V when the source is 5V. The ESPs run on 3.3V, so this effectively could mean the commands are completely scrambled when they arrive at the ESP.
The other way around and you're putting 3.3V comms into a 5V device. This isn't a problem per say, but it could definitely lead to problems. I suggest you use a bi-directional logic level converter which will transform a 5V command to the 3.3V ESP level, and back.
Your wiring between the Arduino and the ESP seems al right, but make sure TX~RX and RX~TX are connected, not TX~TX and RX~RX, but as I said above: use a bi-directional logic level converter.

From your code, I understand that you're setting the baud rate of the software serial pins as 115200. Software serial doesn't support speeds this high. You could set the baud rate of ESP8266 down to 9600 by using a USB to TTL converter and the AT command interface. Then you should try repeating this process using a baud rate of 9600 for the software serial. Or if you happen to have an Arduino Mega which comes with 4 serial ports, you can use the hardware serial pins which supports high speeds.


text:
Telit GPRS Module never returning and never timing out for command AT#FTPOPEN
Howdie!  I trying to run a GPRS modem on an Arduino. My full stack is Nimbelink's NL-SW-GPRS Modem (containing Telit GE910-QUAD GPRS module) with the Nimbelink Arduino Development Shield on an Arduino UNO R3.
My goal is to connect to an FTP server and upload a file. I am following this guide from Nimbelink and section 3.3 from Telit's user guide.
I am stuck because the AT#FTPOPEN command doesn't seem to ever timeout nor does it return any result (ERROR or OKAY).
Here is the AT commands I am running:
AT
> OK

AT+CGREG?
> +CGREG: 0,1
> OK

AT#SIMDET=1
> OK

AT+CGDCONT=1,"IP","internet.com","0.0.0.0",0,0
> OK

AT#SCFG=1,1,300,90,600,200
> OK

AT#SGACTAUTH=0
> OK

AT#SGACT=1,1
> <My IP Address>
> OK

AT#FTPTO=100
> OK

AT#FTPOPEN="209.86.62.76","anonymous","anonymous",0

Where 209.86.62.76 is the IP address of ftp.earthlink.net which I am just using for testing purposes, but I have tried several others. I have tried with FTP mode 0 (active) and 1 (passive) with no change in behavior.
The AT#FTPOPEN just never returns anything (no ERROR and no OK). I've waited up to 5 minutes. The command does returns "ERROR" if I deliberately mess up the syntax of the command (eg. AT#FTPOPEN="") but for any valid format it just seems to hang.
Is this a known problem or something I can easy work around? Am I doing something crazy with my timeout values? Is there an easy way to test the context that I activated with the SGACT?
This is more of a question for an M2M forum, but I'm on an Arduino and it seems like there are many people using GSM modules on Arduino - so I thought I'd post here because I am a bit desperate. Thanks :)

The example in the guide uses the URL and port number like this "ftp.earthlink.net:21". Try that instead of the IP address.

The issues were:

Pin 9 MSM_nRESET should be explicitly set to HIGH.
Pin 10 (DTR) and pin 11 (RTS) should be explicitly set to LOW.
The Nimbelink device requires 5V external power. With USB power, the modem can intermittently reset during period of high activity. If the modem resets, then the command can appear to run forever when nothing is actually running.
Must use FTPOPEN with connection type 1 (passive).