text:
Micro + restricted user Win XP = avrdude: butterfly_recv(): programmer is not responding
I have a Micro (original) and I am (trying to) using it under windows XP.
I was successful in installing its drivers (by swithching to ad Admin account) and uploading sketches to it, no problem. Even when I switched to my limited account, I was able to upload new sketches without error.
But...
Everytime I reboot my computer, as soon as I connect the Micro to the usb port, I get a "New hardware found" popup window from Windows. If I ignore the window I do not see the board in Arduino's IDE. If I choose to install the drivers (by loggin in that window as an admin and then fetching them from the Arduino folder) I end up seeing the board, selecting the COM port and then when compiling, getting the dreadful
avrdude: butterfly_recv(): programmer is not responding

If I press the reset button I get the "Found new hardware window" again and the cycle repeats.
To make it work again I have to log off, log in in an admin user account, and install the friggin drivers from there. After that, if I log off and enter into my limited account, I can see board, port and I can finally upload my sketches (or at least that was the case the last two times).
Is it supposed to work this way?
Can I make it work like a Nano: install drivers only once and then just use the board?
PS
I have to mention that I happen to have 5 compatible Nanos with a ch340G chipset that work like a charm (and cost one tenth of the Micro). I installed the drivers ONCE and forgot about that.
I also happen to have a keyboard and a mouse, and they do not require me to install their drivers every time I plug the USB connector off.
Why is the Micro misbehaving this way?


text:
LCD display connection without a resistor
Can run a LCD without a potentiometer or a resistor?
I don't have any.
Here it said to connect both:

It appears you circled the 220 ohm resistor used to limit the current to the LED back light. Unless you are using a constant current power supply, you generally need to use a current limiting resistor when powering an LED.
If you do not have a resistor, leaving this out should not stop the LCD from displaying properly under normal ambient lighting conditions. However, in a dark room, the LCD will not have a backlight.
The potentiometer is necessary to adjust the LCD contrast. At the extreme settings, most LCD pixels are either all transparent or all opaque.
Using an Arduino PWM output in an attempt to simulate a voltage between 0 and Vcc may be possible. But likely the PWM output should be passed through a filtering capacitor circuit to reduce the signal to only the DC component before connecting this to the LCD's contrast control pin. This option is discussed in this electrical engineering stack exchange Q/A.

Will it work properly in a normal room if I exclude the potentiometer and resistor?

Maybe you should buy OLED version there is no backlight (at all) and no contrast voltage either (potentiometer). You can see something without backlight, but without reasonable voltage at contrast pin you might not be able to see anything or black squares.

https://www.google.com/search?sca_esv=c7f8bf539794a7f6&sxsrf=ADLYWILGw4lncPp2f8HGUo6pSCWLrZO0NA:1729094875134&q=LCD+display+connection+without+a+resistor&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3J_86uWOeqwdnV0yaSF-x2jopn8p7xL4A1Dm_DA2mNSwQLS8ggX90aupvmBKa3yzs15Xg0CORqcq9l1Ydms6PrRPlmr1bkdnrPQy9Qv8nfJeUp9SNl8pfnFiL4i370Z78HhxKk1Q&sa=X&ved=2ahUKEwjzssKupJOJAxUqslYBHRodCHYQ0pQJegQIExAB&biw=1422&bih=621&dpr=1.35#
What about this?
they did it by connecting contrast to a digital pin.

Possibly yes, but it'd be better to filter PWM output by R-C Low pass filter :) But it might work

It will likely not work without a potentiometer to adjust the voltage at the contrast pin of the LCD. It will probably not hurt the LCD if you let the contrast pin float. But that decision is up to you. You can use a PWM output to try and simulate a voltage between 0 and Vcc. But you should probably filter that signal with a capacitor. That option is discussed in this electrical engineering stackexchange Q/A.

source: Stack Exchange

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

sort: votes


text:
ESP32 (Arduino): WiFi.softAPdisconnect(true) gives error + Heap Corruption issues
I have NodeMCU ESP32s and I am using Arduino framework.
I want the ESP to connect to local Wifi, so I set AP on ESP and send to it UDP packet with WIFI credentials.
I am doing it in a loop until sent credentials are correct so the board connects to local WIFI.
Here is a diagram with logic flow for visualization.

For full code reference GitHub link: https://github.com/bartex-bartex/AirQualitySensor-esp32-arduino
WifiManger class:
#ifndef WifiManager_H
#define WifiManager_H

#include "ConfigManager.h"

class WifiManager {
private:
    ConfigManager& configManager = ConfigManager::getInstance();
    const char* ap_ssid = "ESP32-AP";
    const char* ap_pass = "12345678";
    void getWiFiCredentials();
public:
    WifiManager();
    bool connectToWiFi(char* ssid, char* pass);
    bool connectToWiFi(ConfigManager& configManager, int maxUniqueCredentials);
};

#endif // WifiManager_H

connectToWiFi:
bool WifiManager::connectToWiFi(ConfigManager& configManager, int maxUniqueCredentials) {
    bool success = false;

    char ssid[32] = {0};
    char pass[32] = {0};

    configManager.load();

    while (!configManager.isDeviceConfigured()) {
        getWiFiCredentials();
    }

    do{

        configManager.getSSID(ssid);
        configManager.getPassword(pass);
        ESP_LOGI("CREDENTIALS", "SSID: %s", ssid);
        ESP_LOGI("CREDENTIALS", "Password: %s", pass);

        success = connectToWiFi(ssid, pass);

        if (!success){
            getWiFiCredentials();
        }
    } while(!success && maxUniqueCredentials--);

    return success;
}

connectToWiFi:
bool WifiManager::connectToWiFi(char* ssid, char* pass) {
    bool success = false;

    ESP_LOGI("WIFI", "Connecting to WiFi with SSID: %s", ssid);
    Serial.printf("Connecting to: %s\n", ssid);

    WiFi.disconnect();   // clears config, so it won't try to reconnect
    WiFi.mode(WIFI_STA); // this stops AP - THAT IS TESTED!

    WiFi.begin(ssid, pass);

    // try to connect to WiFi using saved credentials
    int time = 5;
    while (time--){
        if (WiFi.status() == WL_CONNECTED){
            success = true;
            ESP_LOGI("WIFI", "Successfully connected to SSID: %s", ssid);
            break;
        }

        delay(1000);
        ESP_LOGD("WIFI", "Attempt %d, still trying to connect...", 5 - time);
    }

    if (success){
        ESP_LOGI("WIFI", "Connected to WiFi SSID: %s", ssid);
    } else {
        ESP_LOGE("WIFI", "Failed to connect to WiFi SSID: %s", ssid);
        WiFi.disconnect(); // clears config, so it won't try to reconnect
    }

    return success;
}

getWiFiCredentials:
void WifiManager::getWiFiCredentials() {

    ESP_LOGI("WIFI", "Resetting WiFi configuration");

    configManager.reset();

    ESP_LOGI("WIFI", "Initializing Access Point (AP)");

    // create own network
    IPAddress local_IP(192, 168, 1, 1);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    WiFi.mode(WIFI_AP);
    WiFi.softAPConfig(local_IP, gateway, subnet);
    WiFi.softAP(ap_ssid, ap_pass);

   ESP_LOGI("WIFI", "Access Point created with SSID: %s", ap_ssid);

    // obtain and save data
    UDPMessengerService udpMessengerService = UDPMessengerService(1234);

    ESP_LOGI("WIFI", "Waiting for UDP packet containing WiFi credentials");

    UdpPacket packet;

    while (!configManager.isDeviceConfigured()) {

        // TODO: Sometimes without sending UDP packet the code moves on...
        if (udpMessengerService.readPacket(packet)){
            ESP_LOGI("WIFI", "Received UDP packet with content: %s", packet.content);

            // writes response message in packet.content
            CommandProcessor::processMessage(packet.content);

            udpMessengerService.sendPacket(packet);
        }
    }

    ESP_LOGI("WIFI", "WiFi credentials received and saved.");

    // false -> AP is turn off and immediatelly on (probably clear config or so)
    // true -> AP switches state 3 times: START STOP START / STOP START STOP -> if second then occure error after first STOP
    WiFi.softAPdisconnect();

    ESP_LOGI("WIFI", "Access Point disabled.");
}

Problems:
1) when I invoke getWiFiCredentials for the second time and execution reaches function end I receive bad head error and system reboots
I guess there is some memory corruption, but I really couldn't spot it in my code.
...
CORRUPT HEAP: Bad head at 0x3ffbad94. Expected 0xabba1234 got 0x0412c61c

assert failed: multi_heap_free multi_heap_poisoning.c:259 (head != NULL)

2) How to handle properly AP turning off + should I use WiFi.mode(WIFI_AP) or     WiFi.mode(WIFI_STA).
I don't get much from docs:
https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/api/wifi.html#softapdisconnect
I have found that WiFi.softAPdisconnect() did some kind of config clear, but doesn't stop the AP, rather RESTART it.
...
[  8693][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[  8715][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[  8726][I][WifiManager.cpp:124] getWiFiCredentials(): [WIFI] Access Point disabled.
[  8727][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  8741][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
...

However WiFi.mode(WIFI_STA) do stop AP.
WiFi.softAPdisconnect(true) should stop AP, but I received an error
...
[  4212][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[  4234][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[  4246][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
E (8622) wifi_init_default: netstack cb reg failed with 12308
[  4259][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  4266][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  4298][I][WifiManager.cpp:124] getWiFiCredentials(): [WIFI] Access Point disabled.
...

Full logs:
With: WiFi.softAPdisconnect(true)
[    78][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
[   215][I][ConfigManager.cpp:29] load(): [CONFIG] Loading config
[   231][E][ConfigManager.cpp:57] load(): [CONFIG] Config file is empty
[   238][I][WifiManager.cpp:82] getWiFiCredentials(): [WIFI] Resetting WiFi configuration
[   261][I][WifiManager.cpp:86] getWiFiCredentials(): [WIFI] Initializing Access Point (AP)
[   291][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 0 - WIFI_READY
[   372][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[   382][I][WifiManager.cpp:97] getWiFiCredentials(): [WIFI] Access Point created with SSID: ESP32-AP
[   392][I][WifiManager.cpp:102] getWiFiCredentials(): [WIFI] Waiting for UDP packet containing WiFi credentials
[  2657][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 12 - AP_STACONNECTED
[  2676][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 14 - AP_STAIPASSIGNED
[  4118][I][WifiManager.cpp:109] getWiFiCredentials(): [WIFI] Received UDP packet with content: { "cmd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[  4133][I][CommandProcessor.cpp:20] processMessage(): [UDP] Processing incoming UDP content
[  4142][I][CommandProcessor.cpp:32] processMessage(): [UDP] Received command: setWiFi
[  4150][I][CommandProcessor.cpp:58] saveWifiCredentials(): [WIFI] Setting WiFi credentials: SSID: Dom | pass: password
[  4170][I][CommandProcessor.cpp:41] processMessage(): [UDP] WiFi credentials saved successfully.
[  4179][I][UDPMessengerService.cpp:31] sendPacket(): [UDP] Sending UDP packet to IP: 192.168.1.2, Port: 60766
[  4189][D][UDPMessengerService.cpp:32] sendPacket(): [UDP] Packet content: {"tymd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[  4204][I][UDPMessengerService.cpp:38] sendPacket(): [UDP] Packet sent successfully.
[  4212][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[  4234][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[  4246][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
E (8622) wifi_init_default: netstack cb reg failed with 12308
[  4259][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  4266][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  4298][I][WifiManager.cpp:124] getWiFiCredentials(): [WIFI] Access Point disabled.
[  4306][I][WifiManager.cpp:65] connectToWiFi(): [CREDENTIALS] SSID: Dom
[  4312][I][WifiManager.cpp:66] connectToWiFi(): [CREDENTIALS] Password: password
[  4320][I][WifiManager.cpp:17] connectToWiFi(): [WIFI] Connecting to WiFi with SSID: Dom
Connecting to: Dom
[  4347][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 0 - WIFI_READY
[  4362][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 2 - STA_START
[  5379][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 1, still trying to connect...
[  6388][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 2, still trying to connect...
[  6791][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[  6799][W][WiFiGeneric.cpp:1062] _eventCallback(): Reason: 201 - NO_AP_FOUND
[  6806][D][WiFiGeneric.cpp:1082] _eventCallback(): WiFi Reconnect Running
[  7397][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 3, still trying to connect...
[  8406][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 4, still trying to connect...
[  9235][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[  9242][W][WiFiGeneric.cpp:1062] _eventCallback(): Reason: 201 - NO_AP_FOUND
[  9249][D][WiFiGeneric.cpp:1086] _eventCallback(): WiFi AutoReconnect Running
[  9415][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 5, still trying to connect...
[  9423][E][WifiManager.cpp:42] connectToWiFi(): [WIFI] Failed to connect to WiFi SSID: Dom
[  9432][I][WifiManager.cpp:82] getWiFiCredentials(): [WIFI] Resetting WiFi configuration
[  9449][I][WifiManager.cpp:86] getWiFiCredentials(): [WIFI] Initializing Access Point (AP)
[  9461][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 3 - STA_STOP
[  9469][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  9489][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  9661][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  9661][I][WifiManager.cpp:97] getWiFiCredentials(): [WIFI] Access Point created with SSID: ESP32-AP
[  9679][I][WifiManager.cpp:102] getWiFiCredentials(): [WIFI] Waiting for UDP packet containing WiFi credentials
[ 21588][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 12 - AP_STACONNECTED
[ 21612][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 14 - AP_STAIPASSIGNED
[ 23077][I][WifiManager.cpp:109] getWiFiCredentials(): [WIFI] Received UDP packet with content: { "cmd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[ 23092][I][CommandProcessor.cpp:20] processMessage(): [UDP] Processing incoming UDP content
[ 23100][I][CommandProcessor.cpp:32] processMessage(): [UDP] Received command: setWiFi
[ 23108][I][CommandProcessor.cpp:58] saveWifiCredentials(): [WIFI] Setting WiFi credentials: SSID: Dom | pass: password
[ 23128][I][CommandProcessor.cpp:41] processMessage(): [UDP] WiFi credentials saved successfully.
[ 23137][I][UDPMessengerService.cpp:31] sendPacket(): [UDP] Sending UDP packet to IP: 192.168.1.2, Port: 60766
[ 23147][D][UDPMessengerService.cpp:32] sendPacket(): [UDP] Packet content: {"tymd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[ 23162][I][UDPMessengerService.cpp:38] sendPacket(): [UDP] Packet sent successfully.
[ 23170][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[ 23192][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[ 23256][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
CORRUPT HEAP: Bad head at 0x3ffbada4. Expected 0xabba1234 got 0xabba1200

assert failed: multi_heap_free multi_heap_poisoning.c:259 (head != NULL)

Backtrace: 0x4008368d:0x3ffbbd80 0x4008be49:0x3ffbbda0 0x40091325:0x3ffbbdc0 0x40090f21:0x3ffbbef0 0x40083bfd:0x3ffbbf10 0x40091355:0x3ffbbf30 0x401029d9:0x3ffbbf50

With: WiFi.softAPdisconnect()
[    78][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
[   215][I][ConfigManager.cpp:29] load(): [CONFIG] Loading config
[   231][E][ConfigManager.cpp:57] load(): [CONFIG] Config file is empty
[   238][I][WifiManager.cpp:82] getWiFiCredentials(): [WIFI] Resetting WiFi configuration
[   261][I][WifiManager.cpp:86] getWiFiCredentials(): [WIFI] Initializing Access Point (AP)
[   292][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 0 - WIFI_READY
[   370][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[   392][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[   564][I][WifiManager.cpp:97] getWiFiCredentials(): [WIFI] Access Point created with SSID: ESP32-AP
[   565][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[   582][I][WifiManager.cpp:102] getWiFiCredentials(): [WIFI] Waiting for UDP packet containing WiFi credentials
[  7000][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 12 - AP_STACONNECTED
[  7015][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 14 - AP_STAIPASSIGNED
[  8600][I][WifiManager.cpp:109] getWiFiCredentials(): [WIFI] Received UDP packet with content: { "cmd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[  8614][I][CommandProcessor.cpp:20] processMessage(): [UDP] Processing incoming UDP content
[  8623][I][CommandProcessor.cpp:32] processMessage(): [UDP] Received command: setWiFi
[  8631][I][CommandProcessor.cpp:58] saveWifiCredentials(): [WIFI] Setting WiFi credentials: SSID: Dom | pass: password
[  8651][I][CommandProcessor.cpp:41] processMessage(): [UDP] WiFi credentials saved successfully.
[  8660][I][UDPMessengerService.cpp:31] sendPacket(): [UDP] Sending UDP packet to IP: 192.168.1.2, Port: 60766
[  8670][D][UDPMessengerService.cpp:32] sendPacket(): [UDP] Packet content: {"tymd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[  8685][I][UDPMessengerService.cpp:38] sendPacket(): [UDP] Packet sent successfully.
[  8693][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[  8715][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[  8726][I][WifiManager.cpp:124] getWiFiCredentials(): [WIFI] Access Point disabled.
[  8727][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  8741][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  8749][I][WifiManager.cpp:65] connectToWiFi(): [CREDENTIALS] SSID: Dom
[  8755][I][WifiManager.cpp:66] connectToWiFi(): [CREDENTIALS] Password: password
[  8763][I][WifiManager.cpp:17] connectToWiFi(): [WIFI] Connecting to WiFi with SSID: Dom
Connecting to: Dom
[  8774][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[  8781][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 2 - STA_START
[  9799][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 1, still trying to connect...
[ 10808][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 2, still trying to connect...
[ 11212][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[ 11220][W][WiFiGeneric.cpp:1062] _eventCallback(): Reason: 201 - NO_AP_FOUND
[ 11227][D][WiFiGeneric.cpp:1082] _eventCallback(): WiFi Reconnect Running
[ 11817][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 3, still trying to connect...
[ 12826][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 4, still trying to connect...
[ 13656][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[ 13663][W][WiFiGeneric.cpp:1062] _eventCallback(): Reason: 201 - NO_AP_FOUND
[ 13670][D][WiFiGeneric.cpp:1086] _eventCallback(): WiFi AutoReconnect Running
[ 13835][D][WifiManager.cpp:36] connectToWiFi(): [WIFI] Attempt 5, still trying to connect...
[ 13843][E][WifiManager.cpp:42] connectToWiFi(): [WIFI] Failed to connect to WiFi SSID: Dom
[ 13852][I][WifiManager.cpp:82] getWiFiCredentials(): [WIFI] Resetting WiFi configuration
[ 13869][I][WifiManager.cpp:86] getWiFiCredentials(): [WIFI] Initializing Access Point (AP)
[ 13880][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 3 - STA_STOP
[ 13942][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[ 13955][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[ 14134][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[ 14133][I][WifiManager.cpp:97] getWiFiCredentials(): [WIFI] Access Point created with SSID: ESP32-AP
[ 14151][I][WifiManager.cpp:102] getWiFiCredentials(): [WIFI] Waiting for UDP packet containing WiFi credentials
[ 20809][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 12 - AP_STACONNECTED
[ 20828][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 14 - AP_STAIPASSIGNED
[ 25837][I][WifiManager.cpp:109] getWiFiCredentials(): [WIFI] Received UDP packet with content: { "cmd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[ 25851][I][CommandProcessor.cpp:20] processMessage(): [UDP] Processing incoming UDP content
[ 25860][I][CommandProcessor.cpp:32] processMessage(): [UDP] Received command: setWiFi
[ 25868][I][CommandProcessor.cpp:58] saveWifiCredentials(): [WIFI] Setting WiFi credentials: SSID: Dom | pass: password
[ 25887][I][CommandProcessor.cpp:41] processMessage(): [UDP] WiFi credentials saved successfully.
[ 25896][I][UDPMessengerService.cpp:31] sendPacket(): [UDP] Sending UDP packet to IP: 192.168.1.2, Port: 60766
[ 25906][D][UDPMessengerService.cpp:32] sendPacket(): [UDP] Packet content: {"tymd": "setWiFi", "params": {"ssid": "Dom", "password":"password"}}
[ 25921][I][UDPMessengerService.cpp:38] sendPacket(): [UDP] Packet sent successfully.
[ 25929][I][WifiManager.cpp:118] getWiFiCredentials(): [WIFI] WiFi credentials received and saved.
[ 25951][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[ 25962][I][WifiManager.cpp:124] getWiFiCredentials(): [WIFI] Access Point disabled.
[ 25963][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
[ 25977][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
CORRUPT HEAP: Bad head at 0x3ffbad94. Expected 0xabba1234 got 0x0412c61c

assert failed: multi_heap_free multi_heap_poisoning.c:259 (head != NULL)

Backtrace: 0x4008368d:0x3ffb1cc0 0x4008be49:0x3ffb1ce0 0x40091325:0x3ffb1d00 0x40090f21:0x3ffb1e30 0x40083bfd:0x3ffb1e50 0x40091355:0x3ffb1e70 0x40145345:0x3ffb1e90 0x401451f9:0x3ffb1eb0 0x400d47fc:0x3ffb1ed0 0x400d5ac7:0x3ffb1ef0 0x400d5bd1:0x3ffb21c0 0x400d5c35:0x3ffb2250 0x400db3ae:0x3ffb2290

I think I have solved those problems:
Problem #1:
The line UDPMessengerService udpMessengerService = UDPMessengerService(1234) was causing heap corruption when the object was created multiple times. To resolve this, I moved the object creation to the connectToWiFi function and passed it by reference, which eliminates the issue.
Problem #2:
Although WiFi.softAPdisconnect(true) throws an error, it appears to successfully stop the AP eventually, so I consider this behavior acceptable.
[  4234][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 13 - AP_STADISCONNECTED
[  4246][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP
E (8622) wifi_init_default: netstack cb reg failed with 12308
[  4259][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 10 - AP_START
[  4266][D][WiFiGeneric.cpp:1040] _eventCallback(): Arduino Event: 11 - AP_STOP

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


text:
Reading the state of a pin at 35V using arduino at 5V
I have a gate controlled by a motorline MC2 motherboard. I want to add a distance sensor controlled by arduino so that I can give it the opening command when leaving the yard.
From what I have seen, the opening command is given on an input (PUL) that is grounded when the command is given. Otherwise, it is at 35V.
The problem is that I want to read the status of this input because the command can be given from 2 keyboards and when these are used I would like to disable the reading of the distance sensor.
I tried using an L7805CV regulator, but when I connect the input from the control board (PUL) to the IN of regulator, the opening command is given. I also tried using a 460Ω or 10KΩ limiting resistor but with the same result.
What other solution can I use in this case? Voltage divider, zener diode or something else?

I would like to disable the reading of the distance sensor ... why?

It has to do with the operation logic of the gate, irrelevant to the subject of the post.

Since the monitored input seems to have a really high input impedance, use a MOSFET to realize the same:

simulate this circuit – Schematic created using CircuitLab
The selection of the MOSFET is left as an exercise to the reader.

Thanks!
I'm not an electrician by trade, I only use elementary things as a hobby.
I think a mosfet with Vgs of 40V is needed? Should this be the voltage at which it is completely ON or the maximum voltage supported?
I have the IRFZ44N in the box, but it seems that it supports a maximum Vgs of a maximum of 20V.

To be honest, my hardware development skills are rusted. But yes, a maximum Vgs of 40V sounds needed.

Thank you!
I will test this solution in weekend if i find an right mosfet.

In many cases, when interfacing a micro controller to devices operating at different voltages, an optical isolator is employed. This is especially true when noise from unknown sources (long wires or questionable power supplies) or the risk of current loops (from multiple power supplies) is a threat to expected operation.
If an optical isolator is not an option, many designers use a resistor divider followed by some type of voltage protection such as a zener diode or a stack of enough common diodes to create create a forward bias of the desired voltage.
For example the nearest integer number of silicon diodes to have a forward bias of about 5 volts is:
5.0 / 0.7 = 7.14

So 7 silicon diodes each with a forward bias of 0.7 volts will not short to ground when arranged in series until the anode of the first diode reaches 0.7 x 7 or 4.9 volts.

By using a voltage divider isn't it like putting the input of the board to ground?
In this case, an opening command would be given, exactly as it happens using the voltage regulator.
Also, if I feed the optocoupler from the 35V input, does the closing not trigger?

The input of most microprocessors are high impedance. So the 2 voltage divider resistors can be rather large. Consequently, little current will pass from the input of the voltage divider to ground. Choose resistor values high enough not to influence the control voltage. But not so high that noise will cause the processor to falsely trigger. Most optical coupler inputs are simply LEDs that will require regulation down to a maximum of only a few volts and require a few mA to turn on. You need to choose resistors (voltage divider and current limiting) to accommodate the optical coupler.

It seems to last, it's a bit complicated especially since I don't have many resistors at hand and the location where the gate is does not allow me to move frequently. I need a solution that will work from the first, not through trials.
But thanks for the suggestion!

"I need a solution that will work from the first, not through trials." The problem here is that we don't know what is inside the equipment generating what looks to be a pull up to 35 volts. It might be through a 1K ohm resistor to a 35 volt power supply. It might be through a 100K ohm resistor to a 35 volt power supply. We don't even know if the 35 volt control line can handle a few extra milliamps of current to power an optical isolator. Unless you have a schematic of the equipment, the only help we can provide will be based on a bit of experience and a lot of guessing.

i understand it is not a reproach just that these are the conditions


text:
Nano destroyed?
Board: OE Gravitech Nano
Is it possible to destroy the board if there are a voltage on a Analog pin while the board is not powered?
I have a application that use a analog (speed) voltage 0-4,9 from a GPS module, this worked very nice for a hour of 10, after that the voltage seems to be not constant available.
Maybe the user have powered off the Arduino while driving the machine.
Regards,
Rien

Assuming you're talking about the device with this schematic (or similar), the "analog" pins go directly to Atmel AVR I/O pins with no series resistance, so yes, it's quite possible to damage the microcontroller. Add some series resistance of a few K and you'll have a better chance of the part surviving such an event.
The voltage on any pin should not, under any circumstances exceed Vcc+ 0.5V as the datasheet specifies, however it's usually okay under non-operational conditions if the current is limited to much less than the 40mA. A 4.7K resistor would limit the current to less than 1mA with a 5V input.

So if I understand this correct, if VCC are 0 (Arduino not powerd)a signal higher then 0.5V on a Analog input pin destroy the Arduino?

Sort of. I'm going to a be a bit persnickety about this. It says that if you keep the voltage less than 0.5V with Vcc = 0 you will not destroy the Arduino immediately. In fact you can exceed that voltage if the current is limited (series resistor) without immediately destroying the chip (the voltage might go up to 0.7V or 1V with a few mA flowing). Nothing is said about proper operation under these type of circumstances. The data sheet does not say this explicitly, but if you put several volts on the input with Vcc held to 0V, you will destroy the chip.

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


text:
send SMS for 1 time with arduino GPRS SIM900 if an iput is HIGH (4 Digi inputs)
I faced a problem to send 1 SMS if an input is HIGH,and if it is LOW==> no SMS to send,if LOW to HIGH==> send 1 SMS. this code not working,just sent SMS when I turn the GPRS on,and after nothing is happened.
Thank you for helping in advance.
 #include <SoftwareSerial.h>
 #include "TimerOne.h"

 const int DI = 2;
 const int DT = 3;
 const int DGP1 = 4;
 const int DGP2 = 5;
 const long interval = 100000; // in microseconds

 int value1 = 0;
 int value2 = 0;
 int value3 = 0;
 int value4 = 0;

 int value1_old = 0;
 int value2_old = 0;
 int value3_old = 0;
 int value4_old = 0;

 boolean changed1 = false;
 boolean changed2 = false;
 boolean changed3 = false;
 boolean changed4 = false;

 SoftwareSerial SIM900 (7, 8);

 void SIM900power(){
   digitalWrite(9, HIGH);
   delay(1000);
   digitalWrite(9, LOW);
   delay(5000);
 }

 void initia(){
   SIM900.print("AT+CMGF=1\r");
   delay(100);
   SIM900.println("AT + CMGS = \"xxxxxxxxxx\"");
   delay(100);
  }

 void Send_SMS(){
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

  }

  void isr_timer(){
    if (changed2) {
      initia();
      SIM900.println("Station 85: Defaut electrique");
      delay(100);
      Send_SMS();
      value2_old = value2;
      changed2 = false;
   }

   if (changed3) {
     initia();
     SIM900.println("Station 85: DefautGP1");
     delay(100);
     Send_SMS();
     value3_old = value3;
     changed3 = false;
   }

   if (changed4) {
     initia();
     SIM900.println("Station 85:DD>1000");
     delay(100);
     Send_SMS();
     value4_old = value4;
     changed4 = false;
   }
 }

 void setup() {
    pinMode(DI, INPUT);
    pinMode(DT, INPUT);
    pinMode(DGP1, INPUT);
    pinMode(DGP2, INPUT);

    SIM900.begin(19200);
    Timer1.initialize(interval);
    Timer1.attachInterrupt(isr_timer);
  }

  void loop() {
    value1 = digitalRead (DI);
    value2 = digitalRead (DT);
    value3 = digitalRead (DGP1);
    value4 = digitalRead (DGP2);

    if (value1 != value1_old && value1 == HIGH) changed1 = true;
    if (value2 != value2_old && value2 == HIGH) changed2 = true;
    if (value3 != value3_old && value3 == HIGH) changed3 = true;
    if (value4 != value4_old && value4 == HIGH) changed4 = true;

    value1_old = value1;
    value2_old = value2;
    value3_old = value3;
    value4_old = value4;

  }

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


text:
My button control working in reverse
I built this circuit to learn button control.

But my code (or button) is working in reverse. I want to initialize led flash effect when the button is pressed with this code
buttonState = digitalRead(8);
if (buttonState == HIGH)
  doFlash();

Instead the effect runs continuously and pauses if I push and hold the button. If change the condition as if (buttonState == LOW) code is working as expected. (Effect starts when I push the button.)
This is just the opposite of what I read in tutorials. What is wrong in my circuit or code?
Full code:
 void setup(){
  for(int i=2;i<=6;i++)
  pinMode(i,OUTPUT);
  pinMode(8,INPUT_PULLUP);
 }

 void loop(){
  int buttonState;

  buttonState = digitalRead(8);
  if (buttonState == LOW)
    doFlash();
 }

void doFlash() {
    int i;
    for (i=2;i<=6;i++) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
    for (i=6;i>=2;i--) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
}

Most tutorials will make the code more "intuitive" by adding additional components to the circuit. E.g.

Here you can see one end of the button is connected to 5 volt, will the other end is connected to a digital input, and via a (pull-down) resistor to ground.
If the button isn't pressed the pull-down resistor will make the input read LOW. If the button is pressed the input will go to 5v (overpowering the pull-down resistor) and the input will read HIGH.
Like you I found the pull-up version a bit weird. But once I figured out how both versions worked, I now prefer the pull-up one. For once, because you don't need an addition resistor. (And secondly because I don't like to use unrestricted 5v signals. If in the above example you accidentally set the input to an output, and press the button, you create a short, and could blow up the micro controller.)

This behavior is expected: INPUT_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.
With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).

There are two kinds of logic: "active high" and "active low". (At least that's one way to characterize it.) Your circuit is "active low", and there's nothing wrong with it. If fact, when you use the internal pull-up resistors of the microcontroller you're bound to use active low logic. (More modern microcontrollers have configurable pull-up or pull-down resistors.)
If this confuses you you can use a #define in your code:
#define ACTIVE LOW

if (buttonState == ACTIVE)
  doFlash();

i had the same problem and no body solved it for me.but i got the solution and it works.

This is a basic pulldown circuit, same as described in Geben's answer two years ago.  Given the duplication, and that you provide no explanation of how this works or changes the sense of the input, it's not a very helpful contribution to the site at this point.

Welcome to Arduino SE.  Please take the tour to get the most out of this site at https://arduino.stackexchange.com/Tour.  Meanwhile, note that the input to an Arduino input pin needs to be between 0-5 Volts and have about 10K or a bit more across it.  1K isn't enough.  Search on "Arduino input pull-down" and I think you will find what you are looking for.


text:
How shiftOut function works internally? (explanation on source code)
I were examining shiftOut() function code in wiring_shift.c and I didn't quite understand what is going in digitalWrite function. I see !!(val & (1 << i)) is taking the bit value from val but how exactly it works?
The whole function is below.
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

!!(val & (1 << i)) is the most complex part of this code. If you do understand this, then what is the part you do not understand?

@edgar-bonet Actually this was the question. I can see it somehow calculates the bit value, but I didn't understand how it do this.

You do understand the behaviour of the shiftOut function?
I mean, you do understand that it'll shift out a value (in binary form). And will give a clock pulse along with it.

I'll assume bitOrder == LSBFIRST.

i is the bit number, i.e. the “index” of the next bit to write
1 is 00000001 in binary
<< is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
1<<i is binary 00000001 shifted left by i positions, i.e. something like 0...010...0, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
& is the “bitwise and operator”, where any_bit & 0 is zero and any_bit & 1 is any_bit
val & (1 << i) is 0...0(i-th bit of val)0...0 in binary, where the i-th bit of val is in the i-th position of the result
!! is a double negation: it converts zero to zero and any non-zero value to one
!!(val & (1 << i)) is either 0 or 1, and is exactly the i-th bit of val

let me summarize what I understand. Let assume val = '10010111';
`for i=2`
  `!!(val & (1 << i))` = `!!('10010111' & '00000100')` = `!!('00000100')` = `1`

If i is = 3
!!(val & (1 << i)) = !!('10010111' & '00001000') = !!('00000000') = 0

This is correct!

And this means if I give 16bit or longer data to shiftOut, it will send least significant 8 bits and ignore the rest.

shiftOut() takes uint8_t data. If you call it with a 16-bit argument, the compiler will implicitly remove the 8 most significant bits before the actual call to shiftOut().

Thanks for the explanations above. This has been invaluable helping with understanding and re-using the code elsewhere. I see that double negation converts zero to zero and any non-zero value to one; I can't see what else it could be. Without double negation, wouldn't the output be the same anyway? What is it I am missing?

@SteveMcDonald: Yes, the output would be the same without the double negation, because digitalWrite() interprets any non-zero value (not just 1) as meaning HIGH. Apparently, the author of shiftOut() did not want to rely on this behavior, and instead wanted to always call digitalWrite() with either 0 (i.e. LOW) or 1 (HIGH).


text:
Why all blink tutorials use 330 ohm resistor
When I do the led calculation I found 150 ohm resistor is enough for 3mm red led. If so why all arduino tutorials, like this one, are suggesting 330 ohm resistor?
I assume V = 5 Volt, diode forward voltage = 2V and diode forward current 20mA

I guess most people are using 1% resistors these days, but if someone does happen to use a 10% resistor rated at 150 Ω the actual value could be as low as 135 Ω. The forward voltage can vary, too; a red LED I was using the other day had close to a 1.7 V forward voltage. Under those conditions, you'd be putting almost 25 mA through the LED, probably exceeding the recommended maximum forward current by a good margin.

150 Ohms may be "enough", but it's often still far too bright, so many tutorials keep a lower limit of around 10mA to help the LED live longer without affecting the application.
You'll probably find that red LEDs are still visible at 1mA and a 330 Ohm resistor with a 5V supply will give about 8.5mA (assuming a 2.2V drop), which is plenty.
It's really a "lazy" choice that will work well in "most" situations.

True. Almost anything up to 1K will work. I always use 470 Ohm resistors just because I have a lot of them.

An important consideration is that the chip cannot necessarily source 20 mA on all output pins at once. In fact pins D5 to D13 on the Uno (PD5 to PD7, and PB0 to PB5) cannot source more than 150 mA combined. Thus the maximum you could source on those pins, if you are driving them all at once, is 150 / 9 = 16 mA.
So, designing for 10 mA per LED is allowing a safety margin, possibly to save tutorials the complexity of explaining that 20 mA is OK for one pin, but not for all the pins at once.


text:
Sending data from txt file over serial connection
I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch
void setup(){
  Serial.begin(9600);
}

void loop(){
  while (Serial.available() > 0) {
    Serial.write(Serial.read());
  }
}

When I try to send serial data from bash by typing cat input.txt >> /dev/cu.wchusbserial1a1340 while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried cat input.txt >> /dev/tty.wchusbserial1a1340. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?

I don't know the details of why the hang is occurring.  However, the problem stems from serial ports being available to one process at a time.  When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash.  (To close the hung Arduino IDE process and the SPM, say ps aux |grep arduino and kill n, where n is the PID shown by the ps and grep.)
Here is a python program you can run, that sends and receives data:
#!/usr/bin/env python
# Send data to an Arduino and report responses.
from time import time, sleep, asctime, localtime
from serial import Serial
print 'Opening serial port'
ser = Serial('/dev/ttyACM0', 9600, timeout=3)
sleep(1)                      # Let board initialize
while 1:
    txt = 'It is about ' + asctime(localtime()) + ' now'
    print 'Sending  "{}"'.format(txt)
    ser.write(txt)
    s = ser.readline()          # Get result from arduino
    print 'Readback "{}" at {}'.format(s, asctime(localtime()))
    sleep(1)

Here is some sample output from it, with your sketch runing in a Mega2650.  (I'm not sure why the readback is taking so long as it apparently is.)
Opening serial port
Sending  "It is about Fri May  8 16:48:41 2015 now"
Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
Sending  "It is about Fri May  8 16:48:45 2015 now"
Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
Sending  "It is about Fri May  8 16:48:49 2015 now"
Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
Sending  "It is about Fri May  8 16:48:53 2015 now"
Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015

Your code was really helpful. Only think I didn't understand is sleep(1) command. Is this a part of Serial module?

Now I understand it was needed to wait for arduino.

sleep() is from the time module.  Its real-number argument is in seconds.  With the first sleep removed, the first send to the arduino gets dropped but it works ok after that.  Note, if you want to send a file, you can replace the txt = ... line with txt = raw_input() and pipe the file into the program, eg programname < fileoftext.  See  raw_input() writeup

As noted by jwpat7 the port can be accessed by one application at a time, so when the serial monitor is open no other application can access it.
The hang might happen because when first connecting to an arduino port the arduino gets reset and waits for a second or so for programming data (that's how a new sketch is updated). I don't know for sure, but this might mess up with cat and make it to hang up.
Best option might be to make a script like jwpat7's that would wait a second after opening the port and then send the file contents in.


text:
Powering arduino uno from Car's reverse light?
I am making a reverse sensing alarm system. I am using a HC-SR04, arduino UNo and a piezo buzzer. The programming was a success however i will like this circuit to be powered when the reverse gear is shifted into place. So I am thinking to power the V in of the UNO with the 10V from the  reverse bulb socket receives. However I think the amperage sent to this bulb is too much for my UNO. What should I do ? and Does anyone have any other recommendations to power the UNO in such a scenario?

Amps are drawn, not sent. A device will only draw the amps it needs. You might have to add some additional protection, as car voltages are very noisy, with huge spikes, that can easily fry your arduino.

Power the Arduino in parallel with the bulb.  Take the V+ wire running to the reverse light and the frame ground.  The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame.  Or you can just splice the light bulbs ground wire.  When powering the circuit in parallel you do not have to worry about the amperage draw of the light.  By a barrel jack connector like this connector from spark fun you can buy these cheaper elsewhere just a 2.1mm barrel jack connector.  Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack.
As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug.  If everything works don't scramble to fix it, but be aware it exists.

If you put it in series, the bulb will not light up (too little amps going through both). Just place it in parallel. The arduino will only draw what it needs; a few milliamps.

I made a massive brain fart I just switched series and parallel in the answer.  DO NOT WIRE IN SERIES!!


text:
Making a composite waveform using a single TIMER interrupt
I'm writing software for a laser tag gun, which under the system we use needs the output waveform to be a carrier wave of 57600Hz with a signal wave of 1800HZ for about 50ms
Using the Tone library (https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation) and a transistor AND gate, I've had this working using two timers, however I really want to shrink it down to one timer so that I can use the other for sound (using the TMRPCM library which only needs timer1).
I've modified the Tone library cut down to what I need, with the following methods:
void TagTone::beginPulse(uint8_t tonePin)
{
    _pin = tonePin;
    _timer = 2;

    // 8 bit timer
    TCCR2A = 0;
    TCCR2B = 0;
    bitWrite(TCCR2A, WGM21, 1);
    bitWrite(TCCR2B, CS20, 1);
    timer2_pin_port = portOutputRegister(digitalPinToPort(_pin));
    timer2_pin_mask = digitalPinToBitMask(_pin);

    int duration = 50; //50 milliseconds
    uint8_t prescalarbits = 0b001;
    int32_t signal_toggle_count = 0;

    // Note: may need prescaler reimplemented if using 16Mhz, fine on current 8Mhz
    ocr = F_CPU / (CARRIER_FREQUENCY * 2) - 1;
    prescalarbits = 0b001;

    TCCR2B = (TCCR2B & 0b11111000) | prescalarbits;

    toggle_count = 2 * CARRIER_FREQUENCY * duration / 1000; // how many times the carrier toggles before pulse ends

    // want to AND with 1800 Hz signal

    // as duration now set to 50: toggle_count for carrier = 5760
    // equivalent toggle count for signal = 180
    signal_toggle_count = 2* SIGNAL_FREQUENCY * duration / 1000;

    // want to flip signal state every 32 carrier pulses
    signal_cycle_count = 32; //toggle_count / signal_toggle_count;
}

// duration (in milliseconds).

void TagTone::playPulse()
{

    OCR2A = ocr;
    timer2_signal_toggle_count = signal_cycle_count;
    timer2_toggle_count = toggle_count;
    bitWrite(TIMSK2, OCIE2A, 1);

}

ISR(TIMER2_COMPA_vect)
{
    if(timer2_toggle_count  < 0)
    {
        *timer2_pin_port ^= timer2_pin_mask & signal_state; // flip

        if (timer2_signal_toggle_count > 0)
        {
          timer2_signal_toggle_count--;
        }
        else
        {
            signal_state ^= signal_state;
            timer2_toggle_count -= timer2_signal_toggle_count;
            timer2_signal_toggle_count = signal_cycle_count;
        }
    }
    else
    {
        TIMSK2 &= ~(1 << OCIE2A);                 // disable the interrupt
        *timer2_pin_port &= ~(timer2_pin_mask);   // keep pin low after stop
    }
}

What I hope this is doing is 32 toggles at the carrier speed (ie 16 full cycles of 57600Hz), followed by 32 'silent' toggles where nothing happens, followed by another 32 at carrier speed, etc.  I should then be able to fire using:
digitalWrite(signalPin, HIGH);
carrierTone.playPulse();
delay(60);
digitalWrite(signalPin, LOW);

But that doesn't set off the sensor, whereas the simple code below works.
carrierTone.play(57600, 50);
signalTone.play(1800, 50);

Woo, solved it.  My ISR code was completely wrong.  Works using:
ISR(TIMER2_COMPA_vect)
{
  if (timer2_signal_toggle_count != 0)
  {
    // toggle the pin
    if(signal_state == 1)
        *timer2_pin_port ^= timer2_pin_mask;

    if (timer2_toggle_count > 0)
      timer2_toggle_count--;
    else
    {
        TIMSK2 &= ~(1 << OCIE2A);                 // disable the interrupt
        *timer2_pin_port &= ~(timer2_pin_mask);   // keep pin low after stop
    }
     timer2_signal_toggle_count --;
  }
  else
  {
    timer2_signal_toggle_count = signal_cycle_count;
    timer2_toggle_count --;
    if(signal_state == 1)
    {
        signal_state = 0;
        *timer2_pin_port &= ~(timer2_pin_mask);
        //*timer2_pin_port ^= timer2_pin_mask;
    }
    else
    {
        signal_state = 1;
        *timer2_pin_port ^= timer2_pin_mask;
    }
  }
}

I was trying to just AND the signal state into the original pin state, which was completely the wrong thing to do.


text:
Arduino selection for RTOS
I am brand new to Arduino and am having a difficult time understanding the "lay of the land". I'm looking for the beefiest, fastest, most compute-centric Arduino available to the market that will run embox.
As I understand it, there is really only the Uno and the Mega, both of which are 32-bit. However I also believe that 64-bit variations/designs exist and was wondering if anyone has actually implemented Arduino Uno/Mega as a 64-bit MCU. I also see there is the Arduino Due, but not sure how that fairs (beefiness-wise) with Uno/Mega.
So to summarize: What is the beefiest Arduino one can find, is it 32- or 64-bit, and will it run an embedded RTOS like embox?

Why are you looking for something arduino related? the normal AVR arduinos are 8-bit cores packed full of IO, but not intended for doing much calculation.

I have some teensy boards, that aremore than sufficent, and fully supported by the FOSS, RTOS NuttX. teensy 3.x, 4.x are supported that I know of off hand. you miht find there is arduino stm32 support in which case you can run NuttX on that as well. Check em out: https://nuttx.apache.org/

While I'm not experienced with running an RTOS on it, I'd highly recommend Teensy 3.1 as the "beefiest, fastest, most compute-centric Arduino". FreeRTOS and ChibiOS both support Teensy.

Thanks @Arvid Jense (+1) - but what exactly is Teensy? Is it Arduino? if so, why don't I see "Arduino Teensy" anywhere on the Arduino.cc site? Thanks again!

Teensy is an Arduino compatible board made by Paul Stoffregen and is meant serve for specific applications where you'd want to use the Arduino IDE, but you need more performance than the Atmega chips can deliver, while still being less expensive than most other alternatives. Paul contributes a LOT to the Arduino code base, yet doesn't feel the need to pay for licensing, which is why you won't see it on the arduino website.

Thanks @Arvid Jense (+1 again) - what about my specific questions though? (a) How does Teensy compare to Arduino Due (which seems to be the beefiest)? (b) Is Teensy 32- or 64-bit? (c) Would Teensy run embox? How can you tell? Thanks again!?

a) Due's main advantages are that is has more IO pins and has the arduino form factor, Teensy 3.1 on the other hand is a lot cheaper and fits on a breadboard. Otherwise they are very similar, so I really depends on your specific needs.

b)  32 bit. If you want 64bit you might be looking towards something different than arduino. c) It doesn't seem like it, Google is your best friend!

Thanks @Arvid Jense (+2 for both!) - last follow up question, I promise! For (c) you said "doesn't seem like it", can I ask why? What makes you think Arduino Due/Teensy won't run embox? Thanks again!

Check out the Embox site to see what platforms are compatible with embox, Arduino doesn't seem te be in here. The other two RTOS' I linked to did seem to able to run on Arduino.

Okay @Avrid Jense (+1) - I think that is the root of my confusion here. On Embox's site, they mention ARM as a compatible platform...isn't Arduino Due ARM?!? If not, what is it? From the Due's own website: "The Arduino Due is a microcontroller board based on the Atmel SAM3X8E ARM Cortex-M3 CPU"....thoughts?

It might be able to work if you know what to do, but why doesn't the STM32Discovery, which is already supported, suit your needs?

You could try an Intel Edison Arduino Kit.
It's 64 bit and can be programmed with a variant of the Arduino IDE.
You can interleave Arduino code with system calls to the Linux OS, depending on which approach better suits a specific need.
Running an RTOS inside Edison seems a bit overkill, however it should be doable.
Otoh you could just rely on the much higher clock to provide quasi-deterministic response.
Or just ditch the Arduino IDE and write a normal program with your programming language of choice.


text:
What protocols and tools does Arduino Due use for flashing and debugging?
I am interested in writing a simple C program outside of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:

Flashing/deploying the program to the ARM MCU; and
Connecting the program to a debugger

And, not just the protocols used, but what tools are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?

http://playground.arduino.cc/Bootloader/DueBootloaderExplained

The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).
I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source BOSSA.  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.

Thanks @Majenko (+1) - a few quick followups if you don't mind: (1) Can you confirm that BOSSA/bossac can be used for both flashing and debugging? (2) If I'm understanding you correctly, the ROM (containing proprietary protocol) is a part of the MCU itself, and that's why it can't be changed, yes? And last, (3) Then how is it that BOSSA/bossac can "speak" this proprietary protocol? Did they ink a special deal with Atmel? Thanks again!

No idea, I have never tried it. 2) Yes, that's right. 3) Probably a combination of software examination, protocol decoding and reverse engineering.

While documentation is nice, I disagree with the permanence of factory bootloaders being a bad thing: they make it very hard to "brick" a device, and save you from needing any special tools to initialize new chips (not that SWD/JTAG adapters are expensive).  If you decide you would prefer to have your own custom bootloader, just write one and put it in ordinary flash and make it reluctant to overwrite itself.


text:
Arduino Servo circuit by example
I have an Arduino program that uses the Thread library to create two concurrent threads, where:

Thread #1 blinks an LED every 500ms; and
Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.
I am now trying to add a 3rd thread that sweeps a servo back and forth.
Here's my design:

And the schematic that Fritzing generated for me:

And an accompanying actual picture of the wire up:

If you can see it, I've rigged Pin 10 as an OUTPUT, and attached the servo's signal line to Pin 9. Here's the code:
#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;

Servo servo;
int pos = 0;

static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;

Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();

void setup() {
    pinMode(LED_1_PIN, OUTPUT);
    pinMode(LED_2_PIN, OUTPUT);
    pinMode(SERVO_PWR_PIN, OUTPUT);

    servo.attach(SERVO_SIGNAL_PIN);

    blinkLED1Thread.onRun(blinkLED1);
    blinkLED1Thread.setInterval(250);

    blinkLED2Thread.onRun(blinkLED2);
    blinkLED2Thread.setInterval(500);

    servoThread.onRun(runServo);

    master.add(&blinkLED1Thread);
    master.add(&blinkLED2Thread);
    master.add(&servoThread);
}

void loop() {
    master.run();
}

void runServo() {
    // Give the servo a few seconds to reset to the starting position.
    servo.write(0);
    delay(5000);

    while(true) {
        for(pos = 0; pos < 180; pos += 1)  {
            servo.write(pos);
            delay(15);
        }

        for(pos = 180; pos >=1; pos-=1) {
            servo.write(pos);
            delay(15);
        }
    }
}

void blinkLED1() {
    LED_1_STATUS = !LED_1_STATUS;
    digitalWrite(LED_1_PIN, LED_1_STATUS);
}

void blinkLED2() {
    LED_2_STATUS = !LED_2_STATUS;
    digitalWrite(LED_2_PIN, LED_2_STATUS);
}

When I flash this to the Due, two disappointing things happen:

The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a feeling that once I get those blinking again, the servo will probably start sweeping as well.
Can anyone spot anything that jumps out at them as being wrong here, wiring and code alike?

The whole point of the (misnamed) Threads library is to avoid calling delay(). Do not delay() inside a thread!

Thanks @EdgarBonet (+1) - can you confirm that delay(...) called in one "thread" would block/lock progress in other threads? Thanks again!

One thing that immediately jumps out at me is you are trying to power the servo from a digital pin.  That is very very wrong.
The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.
Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays.  If one of your functions never returns (like your servo one) then the whole system will lock up.  You need to make your servo function non-blocking like your LED functions.  Give it a 15ms time setting and only move one step of the servo each time it gets called.
Ok, according to comments and research I can confirm that in fact the Thread library is really badly named.  It doesn't run threads, it just runs different functions at different times.  Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen.  There is absolutely no concurrency whatsoever.  It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.
Basically the operation is thus:

Add a function and its time to a list.
Work through the list to find a function whose time has expired
Call that function
Continue through the table
Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion.  Only when a function returns is the system able to move on to the next entry in the function list.
You must not use delay() in your "thread" functions for anything more than maybe 1-2ms of delay in total.  You MUST return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.
So your servo thread would look something like this:

Add my current "direction" to the servo value
If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.
Write the value to the servo

That is then triggered every 15ms by the thread library.
So as real code it may look like:
void runServo() {
    static int direction = 1; // 1 = up, -1 is down
    static int value = 0;

    value += direction;
    if ((value <= 0) || (value >= 180)) {
        direction = 0 - direction; // Change direction from + to - or - to +
    }

    value = max(min(180, value), 0); // Clamp it to between 0 and 180

    servo.write(value);
}

You are right about the Threads library not implementing threads. It's only for scheduling tasks implemented as functions. master.run() will check whether any registered task is due to run and, if it is the case, call the corresponding function.

Thanks @Majenko (+1) - please see my question under Edgar Bonnet's comment (under the original question) - I have the same question for you! Thanks again!

See my edit. It makes it plain.

Replace value = 0 - direction; by direction = -direction.

@EdgarBonet What's the difference?  In my version it shows that you are subtracting it from 0. In your version you are subtracting it from 0 but not showing it.  It's explicit in mine, and results in the same code.

Besides the fact that unary minus more clearly shows the programmer's intent, the difference is that I would store the result in direction, not in value.

That part I have to admit I didn't notice - a pure and simple typo ;)  The 0 stays though :P


text:
How are Arduino's OSH if Atmel AVR is proprietary?
I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.
Arduino uses an Atmel AVR CPU - but Googling this shows the Atmel is proprietary!?
So I ask: how can Arduino be truly OSH if it's chief component - its Atmel CPU - is proprietary?!?

I think the point of OSH is that anyone can use and modify the design, not that it can be created from sticks and stones.

Arduino is based on AVR (most boards, not all actually) but is more than just the single MCU chip. Hence the board itself is OSH. As Ignacio mentioned, one is not supposed to recreate an MCU from scratch (who would want to do that by the way?). In this sense we can say that Arduino is OSH.

The power steering, the voltage regulation, the connection footprint, etc.

@smeeb The Arduino design files can be found here: http://arduino.cc/en/Main/arduinoBoardUno  Look for the schematic and the EAGLE files.  Those files are Arduino "design", and since they are open they can easily be modified.  The AVR is a component in the Arduino, but I would say the AVR's design is not part of the Arduino design.

The components are necessarily going to be proprietary.  There is no feasible way around this.  If you wanted to design a new open source microcontroller from scratch with no proprietary components, it would set you back several billion dollars.  The software used to design integrated circuits costs hundreds of thousands of dollars to license and represents billions of dollars of investment.  Production of the chips themselves takes place in wafer fabs that cost billions of dollars to build, and represent billions of dollars of investment in process technology and semiconductor physics research.  The equipment and process technologies are very closely held trade secrets.  If you are OK with proprietary production, then you can submit GDSII design files (developed with your own open source IC design software) to fabs such as TSMC for production, but the line setup costs will run in the hundreds of thousands of dollars.
Bottom line: you have to draw the line somewhere as to what is acceptable to be 'open' and what is not.  Open source hardware generally means the board-level design files and firmware sources are available, and generally nothing more.
Interestingly, there are many open source CPU designs available.  Sun's OpenSPARC is an open design, you can download the RTL description of the CPU core and modify it.  However, convering RTL to a chip requires IC design software or implementation on a proprietary FPGA with a proprietary development environment.

An 'Arduino' is open source in that you can see the schematics, go out and buy any required components (including the AVR), and change the design however you like.
The AVR is not part of what Arduino owns, it is a simply a component which they have built their design around. You could if you so choose replace that component with something else like a PIC for example, or any other programmable microcontroller for that matter. Granted if you made such a change you would also have to change the software, but then if you change the hardware even to another AVR you would have to change the software so in that sense it isn't really a limiting factor.

There is a good practical question and interesting issues raised here, but this part:
"my understanding of OSH is that all its components must be open source."
I would say your understanding is wrong, where did you get that from?
The design (i.e. how to arrange components) must be open source. Ideally the components would be Open Source too, but practicality dictates that components must be bought "off the shelf". IOW, overall the design should aim for "as Open Source as much as possible".
The thing about hardware is that to realize a design components must be bought, and those components often contain proprietary IP. Of course, the same problem applies to Open Source Software, to run it I need to buy a CPU from Intel, AMD, etc.
So while all open source designs must rely on some proprietary IP as a base platform, the practical question is how easily can the design be moved to another platform (portability), and how easily a component can be substituted (fungibility).
There is only one source of AVR chips and that is Atmel. Other components, like a 3.3V regulator can be easily substituted with other.
The Arduino core software does not rely solely on AVR architecture, in principle it is portable to any CPU platform, in practice any platform that is targeted by GCC. The fact that some Arduinos are not AVR e.g. Due, shows that.

Open-source hardware is fundamentally different from open-source software in that you cannot make a copy of OSH for free. If you want to build an Arduino, you will need all the components it's made of, and even the simplest components like diodes are proprietary, just like the AVR chip. Neither can be home-made and both are proprietary designs.
The important thing about OSH is not that it's made of free components, but the fact that information about how it's made is freely available. The abundance of Arduino shields and addons is not due to availability of free AVR cores, but to the fact that anyone has access to the information needed to make their board Arduino-compatible. BTW, that's how personal computers gained the dominant position on the market: IBM has published detailed specifications including schematics of their IBM PC (albeit not under a free license), enabling other companies to make compatible hardware, and later on, PC clones.
Last but not least, the open-source aspect of Arduino is by no means limited to the hardware. The core library was written in portable way, which made it possible to run it on a wide range of hardware cores. There are even FPGA boards featuring Arduino connectors (1, 2, 3), which can run Arduino software on soft-cores such as F32C or NIOS.


text:
Arduino Due Pinout with Explanations?
I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "Arduino Due pinout", "Arduino Due pin mapping" and similar.
The best I could find was this table, however it doesn't help you out at all if you are completely new to electronics and have no idea what TX2, SDA or NPCSO mean, etc.
Does anybody know of Arduino/Due documentation that explains what each I/O pin is?

Yes, it's called the datasheet for the chip on the board. TX2 is UART 2 Transmit. SDA is I2C Serial DAta.  NPSC0 is Chip Select 0 for SPI  (the N is "Not", or "Active Low").

Thanks @Majenko - is this what you're talking about?

That is a start - you can use it in conjunction with this: http://www.atmel.com/images/doc11057s.pdf

Check out:
http://www.robgray.com/temp/Due-pinout.svg
OR http://www.robgray.com/temp/Due-pinout.pdf
Search 'Due Pinout'!

The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.
Atmel SAM3X8E ARM Cortex-M3 datasheet

I'm shocked that something as mainstream as Arduino hasn't incorporated this into their end user docs. But thanks!


text:
Arduino Protothreads by Example
I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:
#include <pt.h>

static struct pt t1, t2;

void setup() {
    PT_INIT(&t1);
    PT_INIT(&t2);
}

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);
}

static int doSomething(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(100);
    PT_END(pt);
}

static int doSomethingElse(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(250);
    PT_END(pt);
}

Does anyone see anything that jumps out at them as missing or wrong?

What is sleep() ?

Check this example: rather than sleep(), it uses PT_WAIT_UNTIL
  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();
      doSomething();
  }

That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.
The rest looks fine, but I have not tried to run the code.

Just to add to the understanding (or confusion), PT_WAIT_UNTIL blocks the execution or "yield" to the other threads. You can see its difference from sleep which blocks everyone. The while(1) "re-arms" the thread again, once dosomething() finishes. Here is some C switch-while hackery going on. (see http://dunkels.com/adam/pt/expansion.html)

Why reinvent the wheel? There are libraries that can do just that for you.
For example
ArduinoThread. I tried it out and did not need to keep looking further. There are also Wiring and SoftTimer but I did not try those.

authors: Артём Типикин


text:
Arduino Servo is behaving strangely
I am trying to use the Arduino Servo library to drive a simple servo and am having some difficulty getting it to even move.
Here's the setup:

And the schematic that Fritzing generated for me:

And the code:
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;

Servo servo;
int pos = 0;
bool GOING_UP = true;

void setup() {
    // Attach the servo and give it a few seconds to reset to the starting position.
    servo.attach(SERVO_SIGNAL_PIN);
    servo.write(0);
    delay(5000);
}

void loop() {
    if((GOING_UP && pos < 180) || pos == 0) {
        GOING_UP = true;
    } else {
        GOING_UP = false;
    }

    int step = 1;

    if(!GOING_UP) {
        step *= -1;
    }

    pos += step;

    servo.write(pos);
    delay(15);
}

When I run this, nothing happens. When I attach a multimeter and set it to the "6V" setting, I have found some strange readings:

When I connect the red multimeter lead ("red lead") to the 5V line connecting the Arduino to the breadboard, and the black multimeter lead ("black lead") to the black GND line connecting the Arduino to the breadboard, I get readings around 5V; but...
When I connect the red lead to the red power line going to the servo, and the black lead to the black GND line coming back from the servo, I get a voltage reading of roughly -20V!!!

I'm not sure what this means/implies. Is anything jumping out at anyone? Anything I can troubleshoot here? Thanks in advance!

The odd voltages might suggest that the servo isn't actually (fully) connected to the Arduino. As it's a diagram of the breadboard layout, not a photo, I can't say for sure, but on some breadboards the +ve/red and -ve/black rows are sometimes split in the middle. i.e. if you were to connect the Arduino's +5v to one end of the breadboards red row, and the servo to the other end, they might not be joined (same applies for -ve/black). Just a thought; apologises in advance if I’m stating the obvious.


text:
Is my Arduino fried?
I am worried that my Arduino is fried from a previous attempt at connecting a servo to it. To test my concerns, I changed the circuit to see if Arduino could even power a simple LED:
Code:
int led = 13;

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

void loop() {
    digitalWrite(led, HIGH);
    delay(4000);
    digitalWrite(led, LOW);
    delay(4000);
}

Wiring:

In that pic, the Arduino is connected to a 9V battery. When I test the purple connections with my multimeter, the power bounces between ~5V and a weird 1.65V value every four seconds. I assume thats power being applied to the output pin in keeping with my code.
However, the LED does not light up. Any ideas as to what could be going wrong or how I could troubleshoot?

Have you tried putting the led the other way around?
Led's do have polarity, so they won't lit up when they're put in the other way around. And also, are you sure the LED is working?

LEDs have a longer and shorter lead. The longer one is positive. The way your diagram is drawn, it looks like you have it in backwards.

As noted in the previous answer, being able to upload a new sketch indicates an Arduino is ok in general – in particular has a functioning CPU – but of course that does not test all features.  For example, individual inputs and outputs can be damaged.
You can easily change your sketch so that it drives some range of outputs, as shown below.  Thereafter, try moving the red wire (that now connects on 13) to some other of the outputs in the selected range.
enum { LedLo=2, LedHi=20}; // Set lo and hi limits of range

void setup() {
  for (int led=LedLo; i <= LedHi; ++i)
    pinMode (led, OUTPUT);
}

void loop() {
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, HIGH);
  delay(4000);
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, LOW);
  delay(4000);
}

If the LED 'ON' is lit, the board has 3.3v power.
Does the LED 'L' blink? It is also on pin 13, the one your sketch controls.
If so, perhaps your breadboard circuit is likely at fault.
Do you have a multimeter? Does the voltage on whichever pin # your sketch controls change as you would expect it to?
If both are correct, then if you recompile your sketch to use a different pin #, and adjust your connections to match, does your breadboard LED light then?


text:
Arduino: ARM, MCU, SoC and RTOS
I'm trying to understand the relationship between embedded RTOSes, SoCs and chip architectures. Specifically, I have a hobby project that would involve me writing a real-time, embedded application for the embox RTOS, and use Arduino hardware for my proof of concept/prototype. Then, budget permitting, I'd like to port that app to run on another, non-Arduino ARM-based system.
My understanding is that ARM is the chip architecture (a conceptual design, really), and that Arduino simply implements this design, and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.
My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.
Is my understanding of: ARM, Arduino, MCU, SoC and embox/RTOS correct? If not, please clarify/correct me! If so, what sort of considerations would have to be made when porting my app to another ARM system in the future?

My understanding is that ARM is the chip architecture (a conceptual design, really),

ARM is the CPU core architecture used in the Atmel SAM3X MCU family. The MCU is the CPU plus all of the facilities (PWM, ADC, DAC, DMA, etc.) that are implemented in order to allow the CPU to interact with external circuitry.

and that Arduino simply implements this design,

Most appropriately, "Arduino" is the IDE and the software libraries that come along with it, plus the specifications and connector layout of the various pieces of Arduino hardware.

and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

"SoC" is exactly what it says on the tin: it's an entire system on a single chip. The Due is not a SoC, since it's a full board. The BCM2835 found on the RPi is a SoC. The SAM3X is a MCU, since it still requires more than just connectors to become a full "system".

My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Provided that embox runs on the new system and that your application can be compiled for it.

Thanks @Ignacio Vazquez-Abrams (+1) - a quick followup question for you: when you say that Arduino is "...the IDE...software libraries...plus the specifications/connector layout for the various pieces of hardware", can you provide a concrete example of each? I'm just not seeing the forest through the trees there... For instance what kind of software library are you talking about? What kind of connector layout, etc.?Thanks again!

All the libraries that come with the IDE; EEPROM, Ethernet, GSM, LiquidCrystal, etc. As for the connectors, everything on a board that isn't actual electronics that allows e.g. a shield to connect.


text:
When and where do I have to worry about accounting for sensor "noise"?
I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!
Being brand new to electronics/robotics, I was shocked that something as simple as a pushbutton required his debounce behavior. That's something I would have never thought about in a million years. What is the 'rule of thumb' for when this type of debounce behavior (regardless of what sensor we're talking about, pushbutton or otherwise) must be accounted for? Is it simply that any type of analog sensor can generate this kind of unexpected 'noise'?
Can someone provide other examples for when special code must be put in place to accommodate unexpected sensor noise?

Switch bounce and sensor noise are two distinct issues.

Thanks @IgnacioVazquez-Abrams (+1) - ok then my apologies for getting my terminology mixed up. What I'm asking for is: what types of sensors, besides pushbuttons and their 'bounce', also exhibit this unexpected behavior. For instance, if I try integrating my Arduino with some new "Fizz Buzz Sensor" (that detects Fizz Buzz), how do I know that I can't just accept the readings it gives me, and that I won't have to do something similar to debounce?

I'm not sure if this is called noise, per see, as the problem with buttons is mechanical, not electrical. I can't think of any other sensors with similar (unexpected) gotchas. Most electrical noise is caused by varying power use, that will result the supply voltage not being stable. This instability can cause malfunctions or give inaccurate readings (like e.g. measuring a voltage while the supply voltage isn't stable, will lead to inaccuracies). Most of this can be negated by adding (decoupling-) capacitors.

Thanks @Gerben (+1) - so to confirm - this "switch bounce" is more of the exception than the rule, and these types of problems are not really encountered with other types of sensor readings, yes? Thanks again!

Rotary encoders  have the same problem (as they work just like buttons on the inside), but other that I don't think so. All sensors probably  have some things to look out for. E.g. light sensors will detect IR (that we humans can't see); Range sensors won't work on certain material; magnetometers might not give correct information when near speakers or microwaves. etc. etc. But nothing as "illogical" as switch bounce (to my knowledge).

Switch bounce is a physical issue that can be cleaned up with filtering. Since the sense states are very simple, only very crude (time-based) filtering is required to clean up its signal.
Other mechanical sensors that can exhibit similar characteristics are bump sensors, tilt sensors, and accelerometers. Bump and tilt sensors are also very simple, and similar filtering will clean up their signals.
Accelerometers on the other hand react to very minute perturbations, so they may require more advanced filtering based on the application they will be used in; orientation sensing can use time-based filtering, whereas things such as motion tracking including dead reckoning will require one or more layers of calculus in order to clean up the signal.

Awesome, thank you @Ignacio Vazquex-Abrams (+1) - when you say "filter/filtering", how does such a filter manifest itself in an Arduino program? For instance, in that video tutorial, the author simply implements a delay(...) inside his debounce function. Is that an example of an actual time-based filter, or does Arduino have some "filter API" that can be coded against to implement various types of filters. Thanks again!

@smeeb you can either filter in software, or with additional components (resistor+capacitor)

@smeeb: There are entire series of university courses that cover digital filtering.

@smeeb: Summing (averaging) several readings is one way of filtering. It depends on the assumption that the signal is consistent and the noise is random with a mean of 0. Thus summing statistically emphasizes the signal and deemphasizes the noise. The average can be as simple as the mean of the last n readings; or: f * (previous average) + (1-f)*(present reading), called an exponential average; and on up to much more complicated ways of treating the signal to reject specific kinds of noise. For most projects, a mean or an exponential average will do and are easy to code.


text:
Arduino: Breadboards and PCBs
I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!
In the video, the author is using a breadboard for prototyping his circuit. What's the next "step up" from this? In other words, say I get my breadboard circuit working perfectly, is it now time to create a PCB? If my understanding of circuitry is correct, this is not a trivial process. I would need a CAD program to design my circuit, and it would likely be very expensive to get the design actually fabricated. At least too expensive for simple hobby purposes. Is there a middle ground between breadboard and PCB?

But there are free EDA packages out there as well as affordable (but not truly cheap unless you're going for hundreds of boards) PCB fab services.

You can build your project on stripboard (aka Veroboard, which is a particular brand). The wiki page at http://en.wikipedia.org/wiki/Stripboard covers most of the salient points - it is essentially a generic PCB. You can cut tracks, either with a knife, or a specialized tool, and you can solder your parts on to the tracks.
They come in various configurations - my personal preference is just straight strips - and you can cut them to size with a hacksaw.
If your project is non-trivial, you might still like to spend some time working out a decent layout. There are free, and not quite free, products to help you - I use Kicad, which is free & opensource, there are many others.
I have also used stripboard to group a few components together - for example, 2 7-segment displays and two SIPO chips to run them - this can then be a "component" for future bread-board projects.

Is there a middle ground between breadboard and PCB?

A prototype PCB with breadboardlike layout is a fast way to turn a breadboard design into a permanent build. So it may be in the range of valid answers to your question.
(-: The link below is just an example, there are lots of other names, designs and sellers and I am in no way releated to any of those... :-)
https://www.tindie.com/products/Schmart/400-tiepoint-schmartboard-breadproto-board-bundle/

or perma-proto

If you are only making one or two the following works well:

Download Kicad (Free) and design your board.
Print out the layout on special film, and transfer to a blank PCB using a domestic iron.An example: http://www.maplin.co.uk/p/press-and-peel-film-pcb-transfer-system-ab15r
Etch the board in ammonium persulphate or ferric chloride solution.
Drill the holes. You will need some 0.8 and 1.0mm drills and a Dremel drill press or similar.
Mount your components and solder away.

The above works well for single-sided boards. Double sided are possible, but will take some practice.
There is a learning curve getting to grips with Kicad, but if you are serious about electroncs, the time invested is well worthwhile. I got from being a Kicad novice to producing a specialist Arduino shield in a weekend. I had the advantage of having used similar tools in the past, and the disadvantage of being 67 years old (with eyesight to suit)
All the required parts should be available from agood electronics parts suppier (For example Jaycay here in New Zealand)


text:
Do I need the Motor Shield to drive servo motors?
I was perusing Arduino's list of official shields and noticed the Motor Shield that can be used to drive up to 2 servo motors.
Being brand new to Arduino/robotics, I am wondering: do I really need this shield to drive a set of servos?

What does this shield really offer in the way of driving motors?
What is lost by not using this shield?
What if I my project has more than 2 motors?!?

The shield will drive a pair of DC motors (the common small ones in models), or one stepper motor (the precision motors you find in dead printers, etc), and can also connect onwards to other stuff, which happens to include servos. I certainly wouldn't get one to run a servo...
If you want more than two motors, there are other motor shields, or you could make a custom board to suit.
There isn't enough power from Arduino outputs to drive a motor (in general) so some sort of driver is needed - for a simple DC motor, a simple transistor would do, you need bridges for steppers, or ESC's for RC-model type high-power motors. Servo's have their own drivers built-in, so can just plug-in to Arduino.
If you just want to control a couple of motors or a single stepper, the shield is quick & easy, which is where it is placed in the market.

The Motor Shield is for driving bare motors, not servos. Servos already include drive electronics and only require a PWM signal in order to control them, whereas the Motor Shield provides the drive electronics for bare motors.

Thanks @Ignacio Vazquez-Abrams (+1) - so it sounds like servos are more of an "all in one" choice, which has me wondering: when to use a servo vs a bare motor? I'm sure servos are more expensive (if they already come with the drive electronics, etc.), but are their specific use cases where one is preferred over the other (servo vs. bare motor), regardless of cost? Thanks again!

if you're talking about RC servos, they are closed loop systems. With the control signal you're asking the servo to move the shaft to a SPECIFIC ANGLE and HOLD IT.

You don't need this shield to drive servo motors, they have their own controller, you need just a 5V power line, GND and digital output pin to generate a PWM and that's it. Usually Arduino has enough power to drive servo motors.
This shield you are talking about is used for DC (direct current) and stepper motor. These motors need power gain and the shield provides it and often has a chip called L298N (which implements H-bridge) with MOSFETs to properly feed the motor.
What does this shield really offer in the way of driving motors?
A proper circuit and components so you plug your motor and connect into your board leaving you just the programming task to control motor's position and speed.
What is lost by not using this shield?
Actually, you use this kind of component just for practice purposes. It is already built and you just use it. However, it's a good learning process building the H-bridge yourself and understanding how it works and why it is necessary (if you have time, this is a good task).
What if I my project has more than 2 motors?!?
Well, just decide how many H-bridges you need. This shield has the capacity for 2 DC motors or 1 stepper motor. In case they are servo motor, you just use this lib. It is possible to have plenty of servos working together and all you need are good battery and enough digital pins. They share timers of microcontroller, that's why it works for many motors.

The statement “servo motors... have their own controller, you need just a 5V power line, GND and digital output pin to generate a PWM” is a little off.  In general, servo motors have an encoder and use a separate servo controller to read the encoder and adjust PWM output to reach a setpoint.  RC servos are a special subcase of servo motors.

good point, @jwpat7, some modern servo motors come with sophisticated control techniques such as PID which improves the stability and precision. That's the "controller" I was talking about.


text:
Implementing Quasi-Perpetual Battery on Arduino
I am interested in seeing how much "uptime" I can achieve with my Arduino device/project. I am brand new to electronics/robotics, and so I wanted to bounce my idea off of this community first and see if I am overlooking anything obvious/major, or if my overall approach is incorrect.
The idea is simple:
Provide my Arduino device with 2+ "rechargeable power sources" (described next) and then provide a mechanism to route power to any viable (non-dead) power source at any time. While one power source is being used to power the Arduino device, the other "idling" power sources are recharging. The intention is to allow the device to keep switching between power sources endlessly, in perpetuity, achieving 100% uptime (perfect "high availability").
As for each "rechargeable power source" I am thinking an energyShield (rechargeable Li-polymer) backed by a solar panel.
I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage. As soon as another source has higher voltage, the circuit begins drawing power from that one, and the "old source" begins recharging.
I'm a noob but not a fool, and I know there is no such thing as perpetual energy (hence the title "quasi-perpetual"), and I'm sure factors like sunlight/weather conditions/etc. would affect the efficacy of the solar panels, etc. But I guess my first concern is: am I doin' it right? Are there any caveats/pitfalls or considerations I'm overlooking here?
Assuming I'm more or less correct in my approach, the other concern is how to actually implement power sources and diodes in a series, and how to actually rig that all up and connect it to the Arduino board. Again, I'm a total electronics newbie, so I'm just having a tough time visualizing the precise solution there.
And as for determining the actual number of power sources (energyShield + solar panel combo) my device would need, I was just planning on starting with 2, and running the device at max power and monitoring their recharge rates. The more sources I add, the longer the device will operate. Obviously, at some point I'll either reach a point where its uptime is sufficient for my needs, or I'll run out of money. :-)

I think you mean "parallel", not "series".

You're overthinking it. Use one or more solar panels, a harvesting IC with sufficient storage, and the bare MCU and peripherals. Use enough panels and storage to run the MCU and peripherals 24/7, and to also charge the storage during the day.

As always, thanks @Ignacio Vazquez-Abrams (+1) you are my hero. But as always, I am compelled to ask followups! (1) What's a good way to tell how much storage my harvesting IC would need? (2) Any chance you can confirm that this one is an example of an IC that is compatible with an Arduino Due? And finally (3) Are there any solar panels you know of (from Ada Fruit or wherever) that would easily connect to this IC? Thanks again!

Measure how much power it uses over a day and add 25% margin. 2. Does it match the input specs of the Due? 3. Nope.

@smeeb, your comment links to your own TI basket so doesn't show what chip you meant to mention.

"I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage."
That is not correct - you need the two sources in parallel with a diode each. Then the higher voltage will become the current source.
When the sources are charging, the charge source may become the current source if that voltage is higher than the other stored charge source.

Sorry, didn't realize how old the question was.


text:
Arduino/DuinOS vs Normal C/ARM Programming
I'm trying to understand the difference between programming Arduino hardware (Atel/ARM based) versus 'normal C-based ARM programming'.
My understanding is that the Arduino language is cross-compiled into C-compatible binary, and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip, which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.
My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.
I'm sure I'm mucking up a few things here, but this is my general understanding: can someone correct/clarify these things for me?

My understanding is that the Arduino language is cross-compiled into C-compatible binary,

There is no "Arduino language". Programs are written in C++ or C, and the IDE mangles them in certain ways in order to ease development by beginners (and on occasion frustrate development by veterans).

and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip,

No. The uploading of the compiled code is done using a separate program, usually AVRDUDE or bossac, and the code is uploaded into flash. Data can be optionally uploaded into EEPROM via the same program, but this is not required.

which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

Not by default. If you want to use DuinOS then you will need to download, compile, and upload it yourself.

My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

Nope. Any system can be run without an OS.

Thanks @Ignacio Vazquez-Abrams (+1) - I follow your first two answers 100%, but have a few quick followups on the last two.  (1) Regarding DuinOS, if I don't use DuinOS, then what is running on the Arduino chip at the OS layer? And if I do use DuinOS, do I install it ahead of time on the chip, and then install my application, or do I bundle/compile them together ahead of time, and deploy them to the chip (via AVRDUDE, etc.) at the same time? And (2) Regarding my understanding of "normal C/ARM programming", is what I said about using the ISP programmer correct or am I way off?

^ I understand you don't need on OS, but if I want to use one, how do I deploy my app/RTOS to an ARM (basic, 30,000 ft view of the procedures)? Thanks again!

There is no OS layer. There is only your code. You will need to see the OS documentation to learn how to deploy it and applications. 2. Low-level ARM programming usually uses JTAG, but many ARM MCUs support programming via UART or USB via a bootloader.