text:
PROGMEM Corrupted Array
I am trying to store a large number of values into a couple of arrays using PROGMEM, but I am finding that a few of the values are read back corrupted. I am storing just 1s and 0s, but when I read these values back, I will sometimes get values greater than 1. I am using a MEGA 2560 to do this.
// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = -1;
  switch(arr) {
    case 0:
      j = pgm_read_byte_far(VALUES_1 + i);
      Serial.println(j);
      return j;
    case 1:
      j = pgm_read_byte_far(VALUES_2 + i);
      Serial.println(j);
      return j;
    case 2:
      j = pgm_read_byte_far(VALUES_3 + i);
      Serial.println(j);
      return j;
    case 3:
      j = pgm_read_byte_far(VALUES_4 + i);
      Serial.println(j);
      return j;
    case 4:
      j = pgm_read_byte_far(VALUES_5 + i);
      Serial.println(j);
      return j;
  }

  Serial.println("Unable to return next value");
  return -1;
}

void loop() {
  // put your main code here, to run repeatedly:
  readNextValue();
}

What I have noticed is that when I use pgm_read_byte_far for case 0 I will get garbage values for right away, but using pgm_read_byte_near will cause these garbage values to occur sometime later. Any insight to this problem is appreciated.

Don't use either near or far? Let the compiler work out which is which?

Your total array size is 5 * 32000 = 160,000 bytes. Why not store it as bits which would only take 20000 bytes? Then all the issues of far-addressing would go away. You could use a small script to turn your 0s and 1s into suitable bytes, and then a simple macro or function to extract the individual bits.

Also see this question about indexing into large arrays, where I posted an answer that avoided corruption.

Thanks for the answers guys. Ill try some of the suggestions tomorrow and see how it goes. If worst comes to worst, it looks like I will have to just use bits like Nick suggested to avoid the 64k addressing problem that Arduino seems to have.

The Mega has reasonably limited memory, if you are storing only 0 or 1 in a byte (8 bits) you lose a lot of memory (7 unused bits per byte). Consider combining 8 0's and 1's into 1 byte (using bit shifting operators).

Just a follow up in case someone else has the same problem. One solution is Nick's answer in his comment, which grabs the far addresses first in the setup, storing them in an array, and using them. I
// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

long VALUES[] = { 0, 0, 0, 0, 0 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}

  VALUES[0] = (long) pgm_get_far_address(VALUES_1);
  VALUES[1] = (long) pgm_get_far_address(VALUES_2);
  VALUES[2] = (long) pgm_get_far_address(VALUES_3);
  VALUES[3] = (long) pgm_get_far_address(VALUES_4);
  VALUES[4] = (long) pgm_get_far_address(VALUES_5);
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = pgm_read_byte_far(VALUES[arr] + i);
  Serial.println(j);

  return j;
}

void loop() {
  // put your main code here, to run repeatedly:
  readNextValue();
}

This runs perfectly with all bytes correct. The better answer would be to convert the bytes into bits like everyone else was saying in order to save memory space.


text:
Keep on getting scandone
I have a node server with express and socket io behind nginx reverse proxy at AWS.
I am try to connect remotely from my NodeMCU esp8266 through websocket io client to my server using WebSocketClientSocketIO (unsuccessfully).
I am new and don't know what I am doing wrong.
Following are my debug messages. I keep on getting scandone.
SDK:2.2.1(cfd48f3)/Core:2.4.2/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1-13-g163bb82)/BearSSL:6d1cefc
del if0
usl
mode : null
mode : sta(84:f3:eb:b7:4e:8c)
add if0

Connecting.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt

connected with Zlink, channel 13
dhcp client start...
....ip:192.168.10.8,mask:255.255.255.0,gw:192.168.10.1
.
Connected to Zlink
IP address: 192.168.10.8

[SETUP] BOOT WAIT 4...
[SETUP] BOOT WAIT 3...
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
state: 5 -> 0 (0)
rm 0
scandone
scandone
scandone
scandone
scandone
.
.
.
.

`
My sketch:
/*
 * WebSocketClientSocketIO.ino
 *
 *  Created on: 06.06.2016
 *
 */
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
const char *ssid = "MyWiFiName";
const char *password = "mypassword";
#define USE_SERIAL Serial
#define MESSAGE_INTERVAL 30000
#define HEARTBEAT_INTERVAL 25000
uint64_t messageTimestamp = 0;
uint64_t heartbeatTimestamp = 0;
bool isConnected = false;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[WSc] Disconnected!\n");
            isConnected = false;
            break;
        case WStype_CONNECTED:
            {
                USE_SERIAL.printf("[WSc] Connected to url: %s\n",  payload);
                isConnected = true;
        // send message to server when Connected
                // socket.io upgrade confirmation message (required)
                webSocket.sendTXT("5");
            }
            break;
        case WStype_TEXT:
           USE_SERIAL.printf("[WSc] get text: %s\n", payload);
                        // send message to server
            // webSocket.sendTXT("message here");
            break;
        case WStype_BIN:
            USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
                        hexdump(payload, length);
            // send data to server
            // webSocket.sendBIN(payload, length);
            break;
    }
};
void setup() {
  delay(1000);
    // USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
 startWiFi();
    USE_SERIAL.setDebugOutput(true);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();
      for(uint8_t t = 4; t > 0; t--) {
          USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
          USE_SERIAL.flush();
          delay(1000);
      }

   // WiFiMulti.addAP("SSID", "passpasspass");

    WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

```   // webSocket.beginSocketIO("192.168.0.123", 81);
      webSocket.beginSocketIO("http://www.myDomainName.com", 80, "/addr");
 //addr is address where I want to send messages
    //webSocket.setAuthorization("user", "Password"); // HTTP Basic Authorization
    webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
testSend();
    if(isConnected) {
        uint64_t now = millis();
        if(now - messageTimestamp > MESSAGE_INTERVAL) {
            messageTimestamp = now;
            // example socket.io message with type "messageType" and JSON payload
            webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
        }
        if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
            // socket.io heartbeat message
            webSocket.sendTXT("2");
        }
    };
};
void startWiFi() {
   WiFi.begin(ssid, password);
  USE_SERIAL.println("");
  USE_SERIAL.print("Connecting");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    USE_SERIAL.print(".");
  };
  //If connection successful show IP address in serial monitor
  USE_SERIAL.println("");
  USE_SERIAL.print("Connected to ");
  USE_SERIAL.println(ssid);
  USE_SERIAL.print("IP address: ");
  USE_SERIAL.println(WiFi.localIP());  //IP address assigned to your ESP
  };
void testSend(){
   webSocket.sendTXT("Hello from esp");
   delay(1000);
  };
`
My code on node server where I am trying to collect messages from esp8266 is very simple as bellow:

socket.on('addr1', function (req,res) {
   console.log(req);
   });

why call WiFi.disconnect()  towards the end of setup
, after you waited to connect?

Thanks fellows. I will consider both points and post results. I will remove wifi Multi cause I don't understand why we need to use access point while all I need is to use socket io CLIENT in my code?

it is not use of AP. you connect to an AP to join the WiFi network. with WiFiMulti more APs can be set to connect to. it is good if the esp8266 changes location (home, work, mobile hotspot, ... )

Try to use your Local IP as your client WebSocket.
...
...
const char* host = "192.168.x.x";
WifiClient wificlient;
...
...

void setup(){
  ...
  ...
  startWiFi();
  //WiFi.mode(WIFI_OFF);
  //WiFi.disconnect();
  if(!wificlient.connect(host, 80)){
    Serial.println(F("connection failed! "));
    return;
  }
  client.setClient(wificlient);
  ...
  ...
}

also add your host on the express NodeJS. I found a issue like your this
...
...
var http = require('http').Server(app);
var io = require('socket.io')(http);
var host = "192.168.x.x";
var port = "80";
...
...
socket.emit("<your-text>");
server.listen(host, port, function(){
  console.log("listening on http://"+host+":"+host+" ");
});
...
...

Hope this helps.

in the sketch 'simple WiFi begin() is mixed with WiFiMulti system. first the sketch connects to AP and then disconnects and starts WiFiMulti. but:
no AP is configured for WiFiMulti to connect

I removed following lines from my code above: WiFi.disconnect(), and WiFiMulti

and? is it better?

Now to connect to socket io server I have this line ''  ' webSocket.beginSocketIO("http://localhost", 8080 , "/espSocketSrvr2" ); ' But I am getting error //[WS-Client] connect ws...
[WS-Client] connection to http://myserver.com:80 Faild
[WS-Client] client disconnected.
[WSc] Disconnected! '

I also tried running simple socket server using ws library. I changed connection line to webSocket.begin("127.0.0.1", 8080 , "/" ); . Still I get  error [WS-Client] connect ws... [WS-Client] connection to 127.0.0.1:8080 Faild [WS-Client] client disconnected. [WSc] Disconnected! . Though I can connect to server through socket from browser in both cases. I guess I am missing some small thing, but what is that ...............,..

I am running node js server on local computer. I also tried   webSocket.begin("http://localhost", 8080 , "/" ); without success.

localhost of your esp8266 is your esp8266

Great point!!!! Let me try using my IP.

Still same problem.  [WS-Client] connect ws...
[WS-Client] connection to myip:8080 Faild
[WS-Client] client disconnected.
[WSc] Disconnected!

but the original question is solved or not?

Unfortunately not. Any way it is late night here. Will try again tomorrow. Lot of thanks dear Juraj.

but the esp8266 is connected to WiFi network or it is still "scandone"?

source: Stack Exchange

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

sort: votes


text:
how to read all line except the first line?
is there a way to read only 2nd up to the last line except for the first line?
here's my sample code
File myFile;
char cr;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());

    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

skip first line
bool firstLine = true;
while (myFile.available()) {
  int c = myFile.read();
  if (firstLine) {
    if (c == '\n') {
      firstLine = false;
    }
  } else {
    Serial.write(c);
  }
}

Why don't you do reads for the first line, ignore them and start the while thus:
while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
while (myFile.available()) {
  Serial.write(myFile.read());
}

@michael
how do i block/skip the first line and read the 2nd line up to the last line?

By reading the first line and don't use it as in the code above.

myFile.read(); reads only one byte/char

@Juraj Thanks and improved my answer accordingly

and what for is the endOfLineFound test in second while?

@Juraj It's indeed not needed, so it can be removed without any functional change. Thanks again. Also I removed the variable for the while condition.

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


text:
Powering an Arduino Uno using 2 (or as few as possible) AAA batteries
[Background] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.
Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?
Thanks for the help

The 8 MHz version of the Arduino Pro Mini, while nominally powered at 3.3 V, should work fine down to 2.5 V according to the ATmega328P datasheet.

The problem here is not an Arduino-equivalent processor, but powering the servo.  Servos for micro/indoor aircraft are available for operation at lower than normal voltages in the 3-4v range.  An ATmega will run on that voltage as well.  So solve your servo power problem first.

I've got a page about power saving.
My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.
If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.

The flight of an amateur rocket doesn't last very long. I wouldn't advice the Arduino to take a nap in mid flight.

Well in that case any battery that can last the distance would do. :)

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


text:
What is touch_pad_get_status() supposed to return?
What I want to do:
I have 7 touch buttons on my board (ESP32 TTGO T-Display) and I want to attach interrupts to everyone, calling the same function.
In this function I would like to use touch_pad_get_status() or other to get which button was touched. Then a switch case would do the rest.
What I'm facing:
This code
  Serial.print("Button ");
  uint32_t touch = touch_pad_get_status();
  Serial.println(String(touch));

always returns 0, no matter what.
What I've tried:
Including this part of code to the setup
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); //tried the SW MODE too
  touch_pad_io_init(TOUCH_PAD_GPIO15_CHANNEL);

But nothing seem to work. I don't want to make 7 different functions...
Thanks in advance.

have you tried the example code that is included with the library?

@jsotola yes, but none uses this function. There was one example that was similar to this application, but it implemented one function for each button :(

See: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/touch_pad.html
See part 'Touch Detection' and 'Touch Triggered Interrupts'.

@MichelKeijzers You're saying the touchAttachInterrupt(...) cannot be used in this scenario? Also I don't know what a intr_handler_t is, there isn't any example online.

I don't know exactly, however https://github.com/espressif/esp-idf/tree/6e77694/examples/peripherals/touch_pad_interrupt seems to be an example.

touch_pad_get_status() is supposed to be used from within a touch interrupt. Full documentation: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/touch_pad.html

Thank you all, I'll post an answer to my own question as now I have solved this problem.

As pointed out from people in the comments, things need to be different.
If you use the function touchAttachInterrupt, things are a bit simpler.
The example that comes with the ESP32 library is enough to make you understand.
If you want to do what I did, this is how:
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  touch_pad_config(TOUCH_PAD_GPIO2_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO15_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO13_CHANNEL, 500);
  touch_pad_isr_register(TouchButton, NULL);
  touch_pad_intr_enable();

Put this code in the setup(). Of course needs the init(), but also needs to be set to timer mode, or otherwise you're going to need to start() probably.
The config() is to configure the pin as an interrupt. I've set 500 in the threshold because the readings of touch_pad_read() told me it went from 800 untouched to 50 touched, so the midterm I chose 500.
isr_register is the function that tells to call TouchButton(), with NULL as argument to it.
void TouchButton(void *arg)
{
  uint32_t touch = touch_pad_get_status();
  touch_pad_clear_status();
  Serial.print("Button ");
  Serial.println(String(touch));
}

This is the declaration of the callback function I've done. It should be noted that clear_status() should be called as soon as possible after the get_status(), preventing the system from panicking (that's the name). You'll also see in the serial monitor that each button represents a power of 2. That's because the get_status() returns the pin mask in binary. So just do something similar to this
for (int i = 0; i < TOUCH_PAD_MAX; i++) {
    if ((pad_intr >> i) & 0x01) {
        s_pad_activated[i] = true;
    }
}

and you'll get a vector of which one was pressed.

Upvoted for the detailed answer and helping others.

And one give you a little nudge over the comment everywhere threshold sooner rather than later.  In a few days you'll be able to mark your own answer as accepted.


text:
Adafruit_SSD1306.cpp fatal error: pgmspace.h: No such file or directory using SSD1306 on Arduino Nano RP2040
I am currently trying to get a SBC-OLED01 display to run under my Arduino Nano RP2040. I use the official example from Adafruit, attached is the code.
/**************************************************************************
 This is an example for our Monochrome OLEDs based on SSD1306 drivers

 Pick one up today in the adafruit shop!
 ------> http://www.adafruit.com/category/63_98

 This example is for a 128x64 pixel display using I2C to communicate
 3 pins are required to interface (two I2C and one reset).

 Adafruit invests time and resources providing this open
 source code, please support Adafruit and open-source
 hardware by purchasing products from Adafruit!

 Written by Limor Fried/Ladyada for Adafruit Industries,
 with contributions from the open source community.
 BSD license, check license.txt for more information
 All text above, and the splash screen below must be
 included in any redistribution.
 **************************************************************************/

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NUMFLAKES     10 // Number of snowflakes in the animation example

#define LOGO_HEIGHT   16
#define LOGO_WIDTH    16
static const unsigned char PROGMEM logo_bmp[] =
{ 0b00000000, 0b11000000,
  0b00000001, 0b11000000,
  0b00000001, 0b11000000,
  0b00000011, 0b11100000,
  0b11110011, 0b11100000,
  0b11111110, 0b11111000,
  0b01111110, 0b11111111,
  0b00110011, 0b10011111,
  0b00011111, 0b11111100,
  0b00001101, 0b01110000,
  0b00011011, 0b10100000,
  0b00111111, 0b11100000,
  0b00111111, 0b11110000,
  0b01111100, 0b11110000,
  0b01110000, 0b01110000,
  0b00000000, 0b00110000 };

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Draw a single pixel in white
  display.drawPixel(10, 10, SSD1306_WHITE);

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);
  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  testdrawline();      // Draw many lines

  testdrawrect();      // Draw rectangles (outlines)

  testfillrect();      // Draw rectangles (filled)

  testdrawcircle();    // Draw circles (outlines)

  testfillcircle();    // Draw circles (filled)

  testdrawroundrect(); // Draw rounded rectangles (outlines)

  testfillroundrect(); // Draw rounded rectangles (filled)

  testdrawtriangle();  // Draw triangles (outlines)

  testfilltriangle();  // Draw triangles (filled)

  testdrawchar();      // Draw characters of the default font

  testdrawstyles();    // Draw 'stylized' characters

  testscrolltext();    // Draw scrolling text

  testdrawbitmap();    // Draw a small bitmap image

  // Invert and restore display, pausing in-between
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  testanimate(logo_bmp, LOGO_WIDTH, LOGO_HEIGHT); // Animate bitmaps
}

void loop() {
}

void testdrawline() {
  int16_t i;

  display.clearDisplay(); // Clear display buffer

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn line
    delay(1);
  }
  for(i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000); // Pause for 2 seconds
}

void testdrawrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testfillrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=3) {
    // The INVERSE color is used so rectangles alternate white/black
    display.fillRect(i, i, display.width()-i*2, display.height()-i*2, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testdrawcircle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=2) {
    display.drawCircle(display.width()/2, display.height()/2, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillcircle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=3) {
    // The INVERSE color is used so circles alternate white/black
    display.fillCircle(display.width() / 2, display.height() / 2, i, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn circle
    delay(1);
  }

  delay(2000);
}

void testdrawroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    // The INVERSE color is used so round-rects alternate white/black
    display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawtriangle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=5) {
    display.drawTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfilltriangle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=5) {
    // The INVERSE color is used so triangles alternate white/black
    display.fillTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  // Not all the characters will fit on the display. This is normal.
  // Library will draw what it can and the rest will be clipped.
  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

void testdrawstyles(void) {
  display.clearDisplay();

  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.setCursor(0,0);             // Start at top-left corner
  display.println(F("Hello, world!"));

  display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Draw 'inverse' text
  display.println(3.141592);

  display.setTextSize(2);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.print(F("0x")); display.println(0xDEADBEEF, HEX);

  display.display();
  delay(2000);
}

void testscrolltext(void) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(F("scroll"));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

void testdrawbitmap(void) {
  display.clearDisplay();

  display.drawBitmap(
    (display.width()  - LOGO_WIDTH ) / 2,
    (display.height() - LOGO_HEIGHT) / 2,
    logo_bmp, LOGO_WIDTH, LOGO_HEIGHT, 1);
  display.display();
  delay(1000);
}

#define XPOS   0 // Indexes into the 'icons' array in function below
#define YPOS   1
#define DELTAY 2

void testanimate(const uint8_t *bitmap, uint8_t w, uint8_t h) {
  int8_t f, icons[NUMFLAKES][3];

  // Initialize 'snowflake' positions
  for(f=0; f< NUMFLAKES; f++) {
    icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
    icons[f][YPOS]   = -LOGO_HEIGHT;
    icons[f][DELTAY] = random(1, 6);
    Serial.print(F("x: "));
    Serial.print(icons[f][XPOS], DEC);
    Serial.print(F(" y: "));
    Serial.print(icons[f][YPOS], DEC);
    Serial.print(F(" dy: "));
    Serial.println(icons[f][DELTAY], DEC);
  }

  for(;;) { // Loop forever...
    display.clearDisplay(); // Clear the display buffer

    // Draw each snowflake:
    for(f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS], bitmap, w, h, SSD1306_WHITE);
    }

    display.display(); // Show the display buffer on the screen
    delay(200);        // Pause for 1/10 second

    // Then update coordinates of each flake...
    for(f=0; f< NUMFLAKES; f++) {
      icons[f][YPOS] += icons[f][DELTAY];
      // If snowflake is off the bottom of the screen...
      if (icons[f][YPOS] >= display.height()) {
        // Reinitialize to a random position, just off the top
        icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
        icons[f][YPOS]   = -LOGO_HEIGHT;
        icons[f][DELTAY] = random(1, 6);
      }
    }
  }
}

I downloaded the optimized Adafruit GFX library from github and installed it as described. As board I use Arduino Nano RP2040 from Arduino Mbed OS in V3.4.1.
Now when I compile the code, I get the following error:
[...]Arduino\libraries\Adafruit_SSD1306\Adafruit_SSD1306.cpp:42:10: fatal error: pgmspace.h: No such file or directory
#include <pgmspace.h>
          ^~~~~~~~~~~~
compilation terminated.

exit status 1

Compilation error: exit status 1

Unfortunately, I have not found a solution on the net how to solve the problem, which is why I have now written this question. I tried the "normal" GFX library from the package manager instead of the optimized one, with the same result. I guess the error is in the Adafruit_SSD1306 library, so it doesn't make any difference anyway.

The first entry that came up in Google for me concerns the same issue with another library by the same developer. See https://github.com/Bodmer/TFT_eSPI/issues/1148. The workaround/solution here is apparently to comment out the line #include <pgmspace.h> in Adafruit_SSD1306.cpp.

in Adafruit_SSD1306.cpp try to remove || defined(ARDUINO_ARCH_RP2040) on line 41, which I guess was added for the 'pico core' which is preferred by Adafruit for their RP2040 boards

What is happening is, in the library you have included, another library is included. There are 2 solutions: delete the #include pgmspace.h within one of those libraries or just get pgmspace.h.
Hope this helps!


text:
Arduino Mega read data from USB
I´m completely new to the arduino and not used to work with it. Due to an project I need to know the best way to transfer Data to my Arduino Mega. The transferred file will be an sliced 3D object. Is it possible to use the built in USB port to read from a stick? Or do I have to use a PC to transfer my data?
Please help me to answer this question since I have no clue how to manage to get the sliced file to my Arduino.

How big is your sliced 3D object? Are you sure, that it will fit on an Arduino Mega?

Accessing a USB stick is not directly possible and not cost effective to add to this platform (vs changing it for a cheaper one that can do so natively), but you can access an SD card, which you could of course have initialized on a PC via a USB adapter.

It would be easier to use a Raspberry Pi.  They support USB natively, so can read a memory stick or directly from a serial port.

The Arduino Mega doesn't support USB-host, so you can't connect a USB stick directly.
The easiest way is to connect it to a computer, and send the data over the serial connection.

And probably only a little bit of it at a time... for example Arduino-based 3d printers "drip feed" the data only a bit in advance of when it is being used, as a many-megabytes part file would not fit in the ATmega at once.  Of course this approach only works for tasks where the can be accessed with a fairly local view - anything that requires looking at separated parts of the data at once (like the conversion of a 3d model to toolpaths) has to be done beforehand on a computer with enough memory.

Thank you both for your ideas on the problem. @ChrisStratton the goal will be to create the toolpath on a machine with enough memory and to send the result to the Arduino. The Arduino then will be used just to control 3 motors to follow the created path and to control the printhead. Is it possible to send the toolpath via the USB port or do I have to establish some kind of other connection?

Since you're basically re-inventing the equivalent of a 3d printer firmware, you should probably start by thoroughly familiarizing yourself with how the open source ones work.   There are likely other gcode interpreters you can find as well.  To put it in historical terms, you'll be tunneling a serial channel through a USB port and more or less using it to emulate a punched tape...

So you just need to check that arduino serial is good enough-fastest it budges data from pc is 250000 baud -which is just over 30kb a second. To put the terminology in historical terms baud refers to the number of different symbols and was used with telegrams in the 19 century.Bit rate concerns two symbols.Thats why its 30kb.

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


text:
How do I go from modules to PCB?
For my engineering class, I am designing a digital scale.  I have already made a working proof-of-concept by using jumper wires to connect several arduino modules to an Arduino UNO.
I want to make a PCB to simplify the design, and not just have a mess of arduino modules.  I want the design to be flat and small, so I need to make a custom PCB, integrating each module onto the board.  Say I'm not using a protoboard, but sending it to a company to get it custom manufactured.  This PCB would use through-hole components, and not SMD.
I am trying to build the eagle files for the PCB.  I have rounded up the SCH file for each arduino module, and the arduino itself.
I am trying to make this PCB in the easiest and fastest way possible.
Should I just copy and paste, and connect the modules' SCH files into one big SCH file?  Then create a BRD file to create the proper footprints and holes?
Thanks

You can probably start by removing all the stuff you don't need: pin headers, the ATmega16U2 (if you can use an ISP), the 3.3V regulator (if you use 5V logic), ...

Yes, avoid copy-pasting everything, since there are a lot of unnecessary components. See what you need from the original schematics, then insert them and, in the end, make the BRD. And... Personally I prefer SMD components (down to a 1mm pitch is easy to hand-solder them, and with a bit of manual skills and flux you can go down to 0.5mm pitch with common tools)

That's a great way to start. But it would be a good idea to try and understand what all the different components are doing. Also look at the layout of the originals. For example, you can see that the crystal for the ATMega is pretty close to the chip itself. Also sprinkle some extra capacitor footprints. If you get some intermittent problems adding some bypass capacitors can often fix things.


text:
Is it possible to use SPI on Redbot Mainboard?
My students use the Sparkfun RedBot Inventor's Kit for their final design projects. The documentation about this board isn't great. There are connectors to SPI pins (they are not soldered to headers, but they exist, see diagram below); however the bumpers and wheel encoders use pins 10 and 11, which are pins used in SPI communication.
My question is: is it possible to solder headers into that SPI socket and use SPI communication without interfering with the bumpers and wheel encoders (for example if my students want to hook up a 7-segment display to show the RedBot's speed)?

From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.
Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.
If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.
It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.

The silkscreen doesn't correspond with how the Redbot is actually used. They are not used for servos, but sensors. The motors are DC motors and are driven by the ICs on the bottom of the mainboard. Thanks for the suggestions though!

You can still use software SPI on any other available pins.


text:
When i press a button to subtract 1 from 5 it skips to 3
When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.
This is the code that i am using:
//Testing the use of addition and subtraction with the menu options.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
int calc_total;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){
    adc_key_in = analogRead(0);

    if (adc_key_in > 1000) return btnNONE;

    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 150)  return btnUP;
    if (adc_key_in < 300)  return btnDOWN;
    if (adc_key_in < 450)  return btnLEFT;
    if (adc_key_in < 700)  return btnSELECT;

    return btnNONE;

}

void setup(){
   lcd.begin(16, 2);
   lcd.setCursor(0,0);
   lcd.print (calc_total);

}

void loop(){

   lcd_key = read_LCD_buttons();
   calc_total = constrain(calc_total, -4, 4);

   switch (lcd_key){

       case btnRIGHT:{
            lcd.clear();
            calc_total = calc_total - 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
       case btnLEFT:{
            lcd.clear();
            calc_total = calc_total + 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
     }
}

Bouncing shouldn't be a problem because of delays. I wonder if you know what the constrain function does?

i thought it stops the value from going above or below a certain point, is that wrong?

Yes, but you should be doing it after (or in) increment. Something like  calc_total = constrain(-4,4, calc_total + 1);. Otherwise you are displaying invalid value -5 that'll get contstraned to -4 in next loop.

Your main problem is that you aren't looking for a change in buttons. You're only doing your adding or subtracting while a button is pressed.
That means, all the time you're holding btnLEFT in your total is incrementing until it hits your limit.
You need to remember the button state from the previous iteration of loop() and compare it to the current state - and only if they differ do you need to do anything.
Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.

I had that problem before but adding in the delay seemed to make it stop, if I press and release the button it adds 1 and the other subtracts 1 fine until gets to 5 -1 or -5 +1, it can do 4 +1 or -4 -1, and all the values in between.

Also see my edit.

Thank you, adding the constrain immediately after the calculation has worked.

The whole point of constrain function is to keep the values between -4 and 4 (including). In your code you can go to the -5 and show it, but right after that it's adjusted to -4 (and you are not displaying this value).
If you increment this value, you can get only result and this is  -4 + 1 = -3.


text:
Arduino MKR WIFI 1010: WiFi101 shield: NOT PRESENT
A few days ago I received my MKR WIFI 1010 including MKR2UNO Board. Vin Connected via power plug, and USB to PC connected as well. The Blink example works fine. Or any example excluding WIFI.
I tried to use examples in "Examples>WIFI101" like Firmware Version or Scan Networks. It always comes back with "WiFi101 shield: NOT PRESENT"
I even attempted to tun "Tools>FirmwareUpdater" By testing the connection, it comes back with "Programmer not responding". I read somewhere that a double-tap on the reset button might help. After doing this and a click on "refresh-list", I see two ports displayed. A click on the new port and "Test connection" Same result "Programmer not responding".
On the MKR 1010 I see three LED's on: They are labeled "ON", "L" and "CHRG" which is slow flashing as well.
I seem not to be able find tutorials or any help really pertaining to MKR wifi 1010. Since this board is different from MKR WIFI 1000, the examples there are not helping.
I also cant find any layout and explanation pf the on-board LED's. Very frustrating!
I hope, any of you can give me some help.
Thanks a lot!

The WiFi101 is a shield for the Uno using the ATWINC1500 module.
The MKR1010 is a complete board with an ESP32-based module.
The two are completely different. You can't use the library for one on the other.
You need the WiFiNINA.h library which is available in the library manager, or from Github here.

the board is not in beta boards, but in 1.6.19. the WiFiNina library is in Library Manager

@Juraj You changed your mind then, and deleted your comment?

:-) yes. do not trust anyone. I was on a phone. I am looking into it deeper now on a computer

the NINA module (ESP32) is connected over SPI. the WiFiNina library uses SPI. the libraries are not so different. the WiFi1010 later renamed to WiFiNina is not so big rewrite of WiFi101.

Thanks for the fast reply. However, running an example from "Examples>WifiNINA>ScanNetworks" produces only "Communication with WiFi module failed!" error. What now???

I would appreciate a working example, so far everything fails

@Majenko, it turned out on arduino forum, that he got a MKR1000, not MKR1010

@Juraj D'oh! ...

The right WiFi library for the MKR1010 is WiFiNINA. You can install it in Library Manager.
the schema of the board is here
from variant.h
// LEDs
// ----
#define PIN_LED     (6u)
#define LED_BUILTIN PIN_LED

you can get support from developers on Arduino forum

Thanks for the fast reply. However, running an example from "Examples>WifiNINA>ScanNetworks" produces only "Communication with WiFi module failed!" error. What now??? –

official support https://forum.arduino.cc/index.php?board=121.0


text:
Running Python on Arduino
I've been using Python for quite long, and I was wondering if it can be used as a programming language for Arduino, rather than C/C++.
When I'm using the Arduino IDE, the sketch is compiled into a hex file that contains the program binary.

Knowing that micro controllers execute only binary, I would like to know if there is a tool to convert Python code into binary, so that I can upload it directly to Arduino using AVR or other programmers.
I read about Micro Python, a lightweight adaptation of Python that can fit in boards, but can only work with PyBoard, which I have never used yet.
I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in IOT.

Python is an interpreted language with a lot of libraries.  You would need either an interpreter squeezed into the Arduino, or a compiler that makes assembly code from Python (maybe by way of C.)  Too much hassle for too little gain.

And I say that as someone who uses Python extensively in personal projects.  I like Python - but not on my Arduino

Adafruit has a few boards that run microPython. As far as I know, those will interpret code, so don't require precompiled binaries.

@Gerben Do you know some examples ?

Their website has whole range of board that run their version of microPython. See https://www.adafruit.com/circuitpython

To my knowledge, there is not a "python to ATMega architecture" compiler out there.
However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.
Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.

Can the arduino mega run Python ?

The GitHub repo, ports directory, indicates no support for ATMega processors, which is what is in an Arduino Mega.


text:
how to compile arduino sketch from termnial without using arduino ide
I want to know how can I compile and upload the arduino sketch from my terminal instead of using Arduino IDE. I want to use a different IDE for writing code.

https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

there's also platformio

https://www.sparkfun.com/news/2833

As a contributor to Sloeber, an Eclipse Plugin dedicated to Arduino and other micro controllers, I can tell you it's all a matter of using the correct version of gcc and provide the correct options.
Even if that might seem simple, it's not like that, so my advice is to download Sloeber and look at the build console output where we print all the statements used to fulfill the build task: you can infer a lot from that.
As Sloeber is also open source, you can also inspect how we create those build commands for the different boards and tool chains.

I have been using PlatformIO for about 2 years now I think. It’s simply amazing.
https://platformio.org
You can use it standalone just for the CLI compile or bundled with VisualCode Studio for a complete IDE solution.


text:
Combining code for two sensors in one programming
We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.
We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.
TH02 Code:
 void setup()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void loop()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
delay(1000);
}

DHT11 Code:
byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setup()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void loop()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

delay(2000);
}

We are new to arduino and we are trying to understand the codes and how the functions work.. It will be a great help if someone makes us understand what we are doing wrong.

This example combines both codes but uses a single delay. If you want readings at two different times you should use two unsigned long global variables to store the millis() of the last time the functions were called. Then you use an if statement to only call readTH02() or readDHT11() when the last millis is less than the <= current-interval.
It is better to use millis interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called BlinkWithoutDelay to understand how to use intervals instead of delay()
void setup()
{
  setupTH02();
  setupDHT11();
}

void loop()
{
  readTH02();
  readDHT11();

  delay(1000);
}

void setupTH02()
{
Serial.begin(9600);        // start serial for output

Serial.println("****TH02_dev demo by seeed studio****\n");
/* Power up,delay 150ms,until voltage is stable */
delay(150);
/* Reset HP20x_dev */
TH02.begin();
delay(100);

/* Determine TH02_dev is available or not */
Serial.println("TH02_dev is available.\n");
}

void readTH02()
{
float temper = TH02.ReadTemperature();
Serial.println("Temperature: ");
Serial.print(temper);
Serial.println("C\r\n");

float humidity = TH02.ReadHumidity();
Serial.println("Humidity: ");
Serial.print(humidity);
Serial.println("%\r\n");
//delay(1000);
}

byte read_dht11_dat()
{
byte i = 0;
byte result=0;
for(i=0; i< 8; i++){

    while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
    delayMicroseconds(30);

    if(PINC & _BV(DHT11_PIN))
    result |=(1<<(7-i));
    while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
}
return result;
}

void setupDHT11()
{
DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

Serial.begin(9600);
Serial.println("Ready");
}

void readDHT11()
{
byte dht11_dat[5];
byte dht11_in;
byte i;
// start condition
// 1. pull-down i/o pin from 18ms
PORTC &= ~_BV(DHT11_PIN);
delay(18);
PORTC |= _BV(DHT11_PIN);
delayMicroseconds(40);

DDRC &= ~_BV(DHT11_PIN);
delayMicroseconds(40);

dht11_in = PINC & _BV(DHT11_PIN);

if(dht11_in){
    Serial.println("dht11 start condition 1 not met");
    return;
}
delayMicroseconds(80);

dht11_in = PINC & _BV(DHT11_PIN);

if(!dht11_in){
    Serial.println("dht11 start condition 2 not met");
    return;
}
delayMicroseconds(80);
// now ready for data reception
for (i=0; i<5; i++)
dht11_dat[i] = read_dht11_dat();

DDRC |= _BV(DHT11_PIN);
PORTC |= _BV(DHT11_PIN);

byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
// check check_sum
if(dht11_dat[4]!= dht11_check_sum)
{
    Serial.println("DHT11 checksum error");
}

Serial.print("Current humdity = ");
Serial.print(dht11_dat[0], DEC);
Serial.print(".");
Serial.print(dht11_dat[1], DEC);
Serial.print("%  ");
Serial.print("temperature = ");
Serial.print(dht11_dat[2], DEC);
Serial.print(".");
Serial.print(dht11_dat[3], DEC);
Serial.println("C  ");

//delay(2000);
}


text:
Two TH02 Sensors to Grove Base Shield V2
We are trying to connect two TH02 (Grove - Temperature&Humidity Sensor (High-Accuracy & Mini))  sensors to Grove Base Shield V2 that is connected to Arduino Wifi Uno.
We connected the each sensor alone to I2C of the Base shield and it is working just fine, but when we connect two, we cannot get simultaneous readings.
We are new to Arduino and we are trying ti figure out if these two sensors can be connected to I2C even if they have the same address.
Please tell if we need to provide more information. Thanks!

It looks like they have a fixed I2C address so, if I understand correctly, unfortunately you cannot address them individually if they're both on the same bus. Perhaps there's a way to multiplex the bus...

Get i2CScanner to confirm what mark has said (he is usually right).  This just scans the I2C bus and tell you what addresses respond to it.  (Its a useful Arduino program to have to hand anyway).  You can get chips that create a second I2C bus, can't remember the make or model, but they are out there.

I have done, and the TH02 sensor's address is 0x40. Is there a way we can connect one of the sensor to D2 or D4?


text:
Problem "Didn't find PN53x board" in Arduino Uno E-Card Reader
This is component to make E-Card reader, using arduino uno pn532

Code
  if (success) {
    // Display some basic information about the card
    Serial.println("Found an ISO14443A card");
    Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("  UID Value: ");
    nfc.PrintHex(uid, uidLength);
    Serial.println("");

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      Serial.println("Seems to be a Mifare Classic card (4 byte UID)");

      // Now we need to try to authenticate it for read/write access
      // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
      Serial.println("Trying to authenticate block 4 with default KEYA value");
      uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

      // Start with block 4 (the first block of sector 1) since sector 0
      // contains the manufacturer data and it's probably better just
      // to leave it alone unless you know what you're doing
      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);

      if (success)
      {
        Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
        uint8_t data[16];

        // If you want to write something to block 4 to test with, uncomment
        // the following line and this text should be read back in a minute
        //memcpy(data, (const uint8_t[]){ 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0 }, sizeof data);
        //success = nfc.mifareclassic_WriteDataBlock (4, data);

        // Try to read the contents of block 4
        success = nfc.mifareclassic_ReadDataBlock(4, data);

        if (success)
        {
          // Data seems to have been read ... spit it out
          Serial.println("Reading Block 4:");
          nfc.PrintHexChar(data, 16);
          Serial.println("");

          // Wait a bit before reading the card again
          delay(1000);
        }
        else
        {
          Serial.println("Ooops ... unable to read the requested block.  Try another key?");
        }
      }
      else
      {
        Serial.println("Ooops ... authentication failed: Try another key?");
      }
    }

    if (uidLength == 7)
    {
      // We probably have a Mifare Ultralight card ...
      Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");

      // Try to read the first general-purpose user page (#4)
      Serial.println("Reading page 4");
      uint8_t data[32];
      success = nfc.mifareultralight_ReadPage (4, data);
      if (success)
      {
        // Data seems to have been read ... spit it out
        nfc.PrintHexChar(data, 4);
        Serial.println("");

        // Wait a bit before reading the card again
        delay(1000);
      }
      else
      {
        Serial.println("Ooops ... unable to read the requested page!?");
      }
    }
  }
}

And i find problem, like this :

EDIT:
Now has ben change to I2C mode and detected RFID. But not detected E-Card:

How solve this is problem?

are you trying to communicate with it using SPI or I2C? You seem to have I2C connections AND half SPI

Oh, wait - you're using HSU mode? The DIP switches look like they're in HSU mode. But, you seem to have SDA connected to SCL and SCL connected to SDA if you were thinking you're using I2C - so, all in all, your wiring is completely wrong

The pictures show, a) board is in HSU (uart) mode, and b) SCL and SDA are "cross" connected - so, very useful actually :p

Now has ben change to I2C mode and detected RFID. But not detected E-Card..

it is under sir, code..

does the code get as far as Display some basic information about the card

I'd remove the photos now - no need for photos in this question

To be blunt: We need the code before the code you posted too...

code too long, to post

if (success) {
    // Display some basic information about the card
    Serial.println("Found an ISO14443A card");
    Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("  UID Value: ");
    nfc.PrintHex(uid, uidLength);
    Serial.println("");
if (uidLength == 4)
{
  // We probably have a Mifare Classic card ...
  Serial.println("Seems to be a Mifare Classic card (4 byte UID)");

  // Now we need to try to authenticate it for read/write access
  // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  Serial.println("Trying to authenticate block 4 with default KEYA value");
  uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

  // Start with block 4 (the first block of sector 1) since sector 0
  // contains the manufacturer data and it's probably better just
  // to leave it alone unless you know what you're doing
  success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);

  if (success)
  {
    Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
    uint8_t data[16];

    // If you want to write something to block 4 to test with, uncomment
    // the following line and this text should be read back in a minute
    //memcpy(data, (const uint8_t[]){ 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0 }, sizeof data);
    //success = nfc.mifareclassic_WriteDataBlock (4, data);

    // Try to read the contents of block 4
    success = nfc.mifareclassic_ReadDataBlock(4, data);

    if (success)
    {
      // Data seems to have been read ... spit it out
      Serial.println("Reading Block 4:");
      nfc.PrintHexChar(data, 16);
      Serial.println("");

      // Wait a bit before reading the card again
      delay(1000);
    }
    else
    {
      Serial.println("Ooops ... unable to read the requested block.  Try another key?");
    }
  }
  else
  {
    Serial.println("Ooops ... authentication failed: Try another key?");
  }
}

if (uidLength == 7)
{
  // We probably have a Mifare Ultralight card ...
  Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");

  // Try to read the first general-purpose user page (#4)
  Serial.println("Reading page 4");
  uint8_t data[32];
  success = nfc.mifareultralight_ReadPage (4, data);
  if (success)
  {
    // Data seems to have been read ... spit it out
    nfc.PrintHexChar(data, 4);
    Serial.println("");

    // Wait a bit before reading the card again
    delay(1000);
  }
  else
  {
    Serial.println("Ooops ... unable to read the requested page!?");
  }
}

}
}

Why are you adding answers - edit your question, remove the answers

This is sir, i check using white card


text:
AVR program upload overrides unrelated program area
I develope a new bus system (uartbus) which includes a host application that can handle new program uploads throught the bus.
How it's work in short: The host application flashed to the AVR. This located between 0-2000 addresses and the flashing function at the end in the NRWW section. Application is written between 2000 and before NRWW section when it's received from the bus.
It's worked for a while with small AVR codes, but now as i try to integrate with the arduino system i've faced a weird problem: sometimes a page between
100 and 180 (one 128 byte page) been erased and some code filled almost at the beginning.
I thought the flashing function has been called with some wild parameter that results this fault, so i added some guard condition to check before write the flash:
__attribute__((section(".bootloader"))) void bootloader_main()
{
    asm ("jmp 0x0");
}

//modified version of:
//https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#gaeb0dba1dd9d338516a94c0bd8a8db78a
__attribute__((section(".bootloader")))  void ubh_impl_write_program_page(const uint32_t page,const  uint8_t *buf,const uint8_t size)
{
    if(page < 0x2000 || (page > 0x7900+SPM_PAGESIZE) || size > SPM_PAGESIZE)
    {
        return;
    }

    uint16_t i;
    uint8_t sreg;
    // Disable interrupts.
    sreg = SREG;
    cli();
    eeprom_busy_wait ();
    boot_page_erase (page);
    boot_spm_busy_wait ();      // Wait until the memory is erased.
    for (i=0; i<size; i+=2)
    {
        // Set up little-endian word.
        uint16_t w = *buf++;
        w += (*buf++) << 8;

        boot_page_fill (page + i, w);
    }
    boot_page_write (page);     // Store buffer in flash page.
    boot_spm_busy_wait();       // Wait until the memory is written.
    // Reenable RWW-section again. We need this if we want to jump back
    // to the application after bootloading.
    boot_rww_enable ();
    // Re-enable interrupts (if they were ever enabled).
    SREG = sreg;
}

But the problem remained. Because the host code has been partially overwritten, the AVR can't receive new code from the bus. After dumped the AVR's flash and disassembled to invesigate what's happened.
avrdude -p atmega328p -b 19200 -P /dev/ttyUSB0 -c avrisp -U flash:r:flash.hex:i
avr-objdump -j .sec1 -d -m avr5 flash.hex > flash.asm

  ... good code ...
      fc:       fb 01           movw    r30, r22
      fe:       31 83           std     Z+1, r19        ; 0x01
     100:       ff ff           .word   0xffff  ; ????
     102:       ff ff           .word   0xffff  ; ????
     104:       ff ff           .word   0xffff  ; ????
     106:       ff ff           .word   0xffff  ; ????
     108:       ff ff           .word   0xffff  ; ????
     10a:       ff ff           .word   0xffff  ; ????
     10c:       ff ff           .word   0xffff  ; ????
     //looks like this code is from the application space between 2b8e and 2b96
     10e:       ff 1f           adc     r31, r31
     110:       05 90           lpm     r0, Z+
     112:       f4 91           lpm     r31, Z
     114:       e0 2d           mov     r30, r0
     116:       09 94           ijmp
     118:       ff ff           .word   0xffff  ; ????
     11a:       ff ff           .word   0xffff  ; ????
     11c:       ff ff           .word   0xffff  ; ????
     11e:       ff ff           .word   0xffff  ; ????
 ....

     17c:       ff ff           .word   0xffff  ; ????
     17e:       ff ff           .word   0xffff  ; ????
     180:       9f 93           push    r25
     182:       8f 93           push    r24
     184:       0e 94 9e 0a     call    0x153c  ;  0x153c
   ...good code ...

How is this possible to happen even after adding some guard condition before writing the flash?
(Another guard is also installed: when AVR accidentally starts in bootloader mode it's jumps immedialty to 0x00).
I also checked, there's no SPM instruction in the code i uploaded and as far as i know they can be run outside of the NRWW section.

doesn't page 100 start at 0x3200 byte address?

Yes, the 0x3200 is the 100th page of the memory. (On the atmega328, the SPM_PAGESIZE is 128. The 0x3200 in decimal is 12800.). Hmm, that address is acutally writeable and previously i uploaded only shorter codes (under 2 Kbytes, so under the 0x2000+0x800). Maybe that's the root of this weird connection, but i don't have an idea how they connected.

then the 'guarding' if can't apply. so what is the problem?

It can. However the variable name 'page' is a bad name for that, it's actually stores the start address of the page, not the page offset itself. (This name comes from the original source of this flash function: https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html) There's no call example attached, but this code worked prevously with shorter codes to upload and absolute code addresses.

but I don't understand why it is a problem that the page 100 at byte address 0x3200 is written and how and why should the if(page < 0x2000 || (page > 0x7900+SPM_PAGESIZE) prevent it?

The host program (which accepts the uploaded code and implements also other functionalities) is placed between 0x0-0x2000. And that host program writes the received paged to the flash area between 0x2000 and FLASH_END. The condition page < 0x2000 should prevent to write any page under the application area (prevent to overwrite the host). This condition  page > 0x7900+SPM_PAGESIZE added because documentation says nothing about what happens when you call boot function with higher addresses than we have on flash. Condition size > SPM_PAGESIZE is yet another check for failure condition.

So the application area is between 0x2000 and FLASH_END. To override the area i shown in the dump (0x100-180) i, or something*  should calls this function with page = 0x100. When this happen somehow, this guard conditions rejects the call.
( note to i or something*): Like restart to bootloader mode, where the execution can walk to this flashing function with uninitialised values, which prevented by the "jmp 0x0" instruction, placed right before this function. Months ago that made randomly failures .

so you meant the page at byte address 0x100, not the 100th page

More precisely, i meant a whole page between 0x100 and 0x180 (well yes, i've missed the 0x notation). That shows that erase executed successfully but the write sequence got broken. Meanwhile i try to reporduce this failure on other device, but i can't. Because this failure happens randomly (or for ahidden reson), it makes to reproduce much harder.

Randomly: On the original device, after 6 code upload it happend. On a new device, i've uploaded new code at least 15 times but still no error. Ok, maybe it is a device (instance) specific error, but when later happens on a deployed node it will be very frustrating.


text:
LCD displays an "A" instead of 0
I am trying to make a timer that has a accuracy up to 1 tenth of a second. However when it is suppose to print "0", it will print an "A". For example, when printing "10", it will print "1A".
This program only lasts up to seconds. Any suggestion is highly appreciated, thank you!
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
unsigned long time2 = 0;
int x = 0;
int a = 0;
int b = 0;
void setup() {
  lcd.begin(16,2);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("00:00:00:0      ");
  Serial.begin(9600);
}

void loop() {
  unsigned long time1;
  time1 = millis();
  if (time1 - time2 > 100){
    time2 = time1;
    lcd.setCursor (9,0);
    x=x+1;
    lcd.print(x," ");
  }
  if (x>=10){
    x=0;
    a=a+1;
    lcd.setCursor(7,0);
    lcd.print(a,":");
  }
  if (a>=10){
    a=0;
    b=b+1;
    lcd.setCursor(6,0);
    lcd.print(b+a);
  }
}

Hint: Check and correct the statement lcd.print(a,":");

https://www.arduino.cc/reference/en/language/functions/communication/serial/print/

Here is my Suggestion: In cases a clear answer could not be seen, you have to remove any weaknesses step by step to further encircle the problem. Since there is now answer for more than a month, I assume this as an appropriate proceeding.
One weakness I see in your coding is, that you are counting your values x, a, b, up to ten and you are printing them bevor reseting them to Zero, so your are printing 'x' even if it is ten. If for any reason in the further handling your display shows HEX values, you will end up displaying an 'A'. Change your Code so that values > 9 are not printed out, than this weakness will be removed.


text:
Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing
I have a complex sketch with Arduino Uno, Bluetooth Serial Com using altSoftSerial, serial com using SoftwareSerial and Serial communication with PC.
I want to move one stepper motor and stop it when a signal is received.
I use A4988 Pololu driver and NEMA 17 bipolar stepper motor.
This code is working fine.
      MyStepper.moveTo(position);
      MyStepper.runToPosition();
If I change the code to
      MyStepper.moveTo(position);
      MyStepper.run();
so that the running does not block my code the motor does nothing
Absolutely no movement.
The ground of the motor power supply is connected with the ground of Arduino. The motor is working fine with blocking movements.

read the library documentation for the run() function

You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.
If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.
When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.
stepperMotor.moveTo(3000);
stepperMotor.runToPosition();
// reaches destination

stepperMotor.moveTo(3000);
stepperMotor.run();
// moves a single step

stepperMotor.moveTo(3000);
while (stepperMotor.distanceToGo > 0) {
stepperMotor.run();
}
// reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:
stepperMotor1.moveTo(5000);
stepperMotor2.moveTo(3000);
while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
stepperMotor1.run();
stepperMotor2.run();
}
// Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).

The problem is at blocking delays. The Run function is interrupted by any other action of program. So you have to call it all the time. A call to run is required in the loop and I wrote a simple mydelay function which solves the problem if you have to use delay for bluetooth communication or other purpose.
int mydelay(int j) {
  long endmillis;
  endmillis = millis() + j;
  while (millis() < endmillis) {
  MyStepper.run();
  }

I hope I help someone because it took me a while to figure this out as a newbie to Arduino.

i downvoted your answer because you wrote a blocking function to solve a problem caused by another blocking function ..... it may work for you, which is great, but blocking functions should be avoided .... i upvoted your question because you solved it yourself...... also, your solution suffers from the rollover bug and it may mess up after a 49 day run ..... read https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

In my case I need to wait for bluetooth to send a whole string. If I send the string "12345", The if bluetoothserial.available() catches the 1, maybe 2, loses 3 4 5 which arrive in a few ms. I need a small delay about 10ms. My device is never going to work for 50 days that the clock timer will reset. Anyway this was the solution to my problem and I managed to move the stepper controlled by mobile, it moves smoothly and while it is moving I can change the target position and it will change it's direction with proper accelerations. I really couldn't find a better way and I searched a lot.

that is why i said that it is great that it works for you .... the reason for downvote is because other people will do research for a problem that they may have and they will find your answer ..... it is important that they think about possible problems if they adopt your solution

about the bluetooth comm ..... if you send a "12345", is there an end-of-line character like a CR or NL at the end?

Yes there is 12345#. Sometimes I send big strings GOTO#1500#. @jsotola Your question triggered my mind and I tried removing the delay and read until # is received. It did not work initially, then I added while incoming!="#", if bluetooth available read incoming and it works. I try to add code in the comment but Ctrl+K does not work so I won't add code for now.


text:
LED on same Pin as Toggle Switch, not illuminating
I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of simulated byte, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).
So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.
My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.
I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) seemed to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)
Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?
The breadboard looks like this:

Do you want to turn the led on and off regardless of the switch as well? Or do you only want to read the switch (and the switch turns the led on and off).

Can you post your code? You might have switch bounce. An even number of bounces could cancel a press, and an odd number would effectively count as one press.

LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.
You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.
So:
Vout = (Vin - Vled) * (R2 / (R1 + R2))

     = (5 - 2) * (1000 / (200 + 1000))

     = 3 * (1000 / 1200)

     = 3 * 0.833

     = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.
You're between those two voltages - in the "dead zone".
The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.

Using a double-pole switch seems indeed the smarter approach here. Thanks. I see your logic... but it doesn't account for my case, however, where I am getting the correct input on the Arduino--the LED is not illuminating. The dead zone you note would be like a floating pin, no?

This is your circuit that does not work:

simulate this circuit – Schematic created using CircuitLab
There are many ways to use a single pin. Some circuits are with a diode and some circuits need to turn off the led to read the switch. The most simple solution might be this:

simulate this circuit
When the switch is not closed, the LED is a weak pullup (perhaps too weak). By using INPUT_PULLUP for D7, the pullup is stronger and D7 can read the switch.
As an extra it is possible to turn the LED on when the switch is open. But you have to be sure to switch between OUTPUT + LOW and INPUT_PULLUP in the code or else there is a shortcut.


text:
Does Arduino Uno come with Virtual Pin support?
I want to recieve Data with Virtuino from my Arduino Uno 3 (Ethernet Shield) via Ethernet.
Does Arduino Uno 3 support virtual pin? If so - is there a link with the Syntax I need?
Thank you very much

have you searched for virtuino arduino uno - second link in google uses an ethernet shield

Thanks, I am using an ethernet shield and established a connection with Virtuino already. I did use google. Doesn't answer my question if Ardunio Uni supports virtual pins though :/

What are virtual pins?

@Majenko The library he mentions allows to map variables in the mobile app to variables in the device firmware using the so called virtual pins. It's just a way to define a data binding between the two pieces of software: you change the virtual pin state/value in one to get the same change reflected on the other end.

Ah. So the answer is: "Yes. If you write the software to do it - or install whatever libraries this Virtuino thing provides for you".

Thats right, basically what I want to do. If I google for "Arduino Virtal Pin" and similiar things I often come to "Blynk" though I need to use Virtuino.
What I basically need is a library and/or Syntax to use virtual pins.

it appears that the virtual pin exists in the Android app .... when an Arduino hardware pin changes state, a message is sent to the app, which changes the state of the virtual pin ..........  changing the state of a virtual pin in the app, sends  a message to the arduino, which changes the state of the hardware pin  ..... because of the time required to send a message, you cannot use the virtual pin for fast changing pins such as PWM

@Red, the Virtuino  web site has a bunch of example sketches ..... you just have to look ....... you may also be misunderstanding what virtual pins are ...... that may be why you are not satisfied with the answers that you found

Virtual pins are, as the name gives away, virtual, thus not related to the hardware you are using. Imagine you have a board with 100 pins, you have 100 physical pins and can add 1 million virtual pins (memory permitting).
In other words, the question doesn't seem to make sense to me.
UPDATE
If you need a bootstrap on how virtual pins are defined and used you could give a look at the examples published by the authors, like these
If that's not enough, please provide additional information on what problem you are facing and which solutions you have already attempted.

Nono, thats everything I needed. I used many of the examples the IDE provided but I didn't find this one. It's perfect. Thank you very much Roberto :)


text:
Battery for WS2812 Strip? (Something's not right)
I have posted this in a few places, so sorry if you have seen it somewhere else
Im working on a battery powered led strip project,
iv put the project together and have been testing with a mains power supply
Iv run some tests and found at max I'd be pulling 4.5 amps
Averaging around 2 ish

I rounded out to about 3.5 amps, and said for 90 mins run time id be looking at the 7ah battery
7/2 = 3.5 so 2 hours runtime
I got a 7ah SLA 12v battery, running though a 12v to 5v converter to power the led strips
(Arduino is running off a usb battery pack)
However after about 45 mins I tested the battery and it said 10.9 v
Which I understand to be too low for SLA batteries (11 should be the minimum?) so I shut it off
My question is did I mess up somewhere and get my math wrong?
Many thanks in advance

What kind of 12V to 5V converter are you using?

Its listed as a Step Down buck converter regulator
9-35v input, 5v 5A output

In that case 4.5A at 5V will only be around 2A to 2.5A at 12V.

So based on that my battery should have lasted longer? not shorter?

Yep. If indeed there was even a problem.

There are a few things that may contribute to your lower than expected battery lifetime.
Effective capacity: you should aim to never use more than 50% of the capacity of a lead acid battery or you will shorten its lifespan considerably.
Also, note that lead acid battery capacity is usually given for a discharge time of 20 hours (C20 rating). The “C” rating could be different but its value should be on the label of the battery.
In the case of a stated capacity of 7Ah at C20, this means the capacity has been calculated at a discharge rate of 7Ah/20h = 350mA. For higher discharge rates, such as in your application, the effective capacity will be much lower.
Battery voltage: measuring battery voltage under load does not say much. Measure the battery voltage “at rest”, when completely disconnected from the load for about 1 hour.
Charging: Are you charging the battery with a proper charger?

I cant see anything about a C rating?
I think my understanding ( or at least what i was told ) is wrong, as i was going off the understanding that 7AH means 7 amps over an hour, so 3.5 amps would be 2 hours etc
I had no mention of C ratings when researching this
For the load, iv charged the battery back up now, but i did check when i was pulling the battery out (would have been about 30 mins after) and was still showing 10.8V more or less
and I have a charger which is marked as being for SLA batteries

okay so i have done some reading on C values, and can understand what you mean now. my next question would be how do I fix this? EG what battery type would I need,

Next step up in terms of common SLA battery sizes would probably be 17Ah. If you keep to 50% maximum discharge you should probably be able to reach 90 minutes with some spare capacity left, but YMMV.


text:
Controlling I2C slave on Arduino with Python
Typically, when I connect my Arduino to a slave device through I2C or SPI, I'll control the slave using instructions coded in the firmware. The output data will be then printed to the Serial port and I'll use Python or MATLAB to read from the serial port and process the data later on.
PC <- Arduino <--> Slave

Now say I want to control the I2C slave from my computer, i.e. write instructions to the I2C slave. How do I go about it? I thought of writing to the Arduino Serial port, making Arduino read it and hence configuring it but this doesn't seem efficient and I have been racking my head over this for a while.

why wouldn't that be efficient? You can put an interrupt on an incoming string.

That use of an Arduino as a 'format converter' to a peripheral from a computer is 'efficient' in the sense that you can use what you have to hand, do it quickly, expect it to work, and debug it easily if it doesn't. It's not efficient in the sense that there's an extra  computer in the way, but, who cares?

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

Have you looked into the pigpio library?  Do a quick search, maybe?

The OP did not mention the Raspberry Pi which is what the Pigpio library is for.


text:
GUI interface with microcontroller to control a device through SPI
I am trying to develop a GUI to control a device hooked up on the Arduino. The Arduino communicates with the device through SPI. I have developed a GUI on MATLAB to visualize read by the Arduino. For this, I made Arduino write data from the MISO line to the serial port and MATLAB would read from the same port and do its magic. However, I am trying to come up with a method to write to the MOSI line using the GUI.
Right now I am thinking of making Arduino listen for a particular code (like a character) on the serial port and once it sees it, it will look for an x number of succeeding bytes. The bytes will be formatted in a particular way so that Arduino can then parse it and write to the appropriate registers.
Is there a better way to do this? As a generic question, what's a good way to write to a device hooked onto a microcontroller using I2C or SPI through a GUI?

the GUI should be separate from the communication. develop the communication part first. once that works, add the GUI code.

You can bypass the Arduino entirely, if you want to make this more efficient. https://www.adafruit.com/product/2264 EDIT: I just realized how old this is. What are the chances OP needs this anymore?

@Tri Thanks for the recent reply. I decided to make the GUI write a configuration file to the serial port and have the Arduino code parse through the same before communicating with the device on SPI. Thank you for the FT232 link though. That will be helpful in the future

Perhaps we need clarification / definition of "GUI" by the original poster, hence stop mixing "graphical user interface" with "device interface".

I grappled with the same question for a while. Here is how I solved the issue.
1- Find a suitable exchange format and protocol
Here you need to decide what is the most important thing on the communication. Is it speed? Is it error detection? Is it memory footprint? For my project, for instance, I decided that I need my communication to be as error free as possible, with minimal memory footprint (up to 64 bytes) and I don't really care about speed, so I gone for a JSON messaging protocol where the desktop application send a short (up to 64 characters) JSON message and receives a short answer. This solved MY problem, your requirements might be different. If you need speed and don't care for memory, for instance, you can use a binary protocol with a header specifing size, the message and a CRC footer to check vailidity. Or you can use BSON and take this library to avoid the hassle.
2- Define the Serial Polling Cycle
How will the arduino firmware knows it is time to send or receive messages? It is always talking? Always ready to receive? It looks at the serial port buffer once each few microsseconds to know if there is an incomming message? How that is handled by your device? If you just need to output data without bothering whether there is someone listening or not, like an GPS device, just throw a Serial.print now and then, but if you need to wait for data, you will have to compartimentalize the process inside an FSM or using some kind of scheduler. If you are not using a scheduler, I recommend this one.
3- Define the Communication Cycle
Here you will take the data from serial port and storing it on a buffer for later usage.
The trick here is
1- Check the serial FIFO for incomming data. Serial.available() does it already.
2- If there is incomming data, copy the data to next available space in the buffer.
3- Check if there is more incomming data after a few millisseconds.
4- If there is no incomming data, mark the buffer as ready to use, and parse it.
The following code is unscheduled for simplicity,and I recommend you to replace the sleep() calls to proper scheduling least you want the arduino go unresponsive. It is also waiting text data, so you will need to make changes if you are waiting binary data.
  char buffer[64];
  memset(buffer, 0, 64);

  while (!Serial.available())
    delay(50);

  while (Serial.available()){
    Serial.readBytes(buffer + strlen(buffer), Serial.available());
    delay(50);
  }
  parseBuffer(buffer);

I had a similar requirement and came up with Wirekite. It is a complete solution based on a Teensy board, some code for it plus libraries for Mac or PC.
With Wirekite, you can hook up digital and analog inputs and outputs, I2C devices and SPI devices (very soon) to the Teensy board and connect the Teensy board via USB to your Mac or PC. You can then control the I/Os, I2C and SPI buses from you Mac or PC. You don't need to adapt the code on the Teensy.
Wirekite uses a custom protocol for the communication. But you don't need to care about that because you can simply use the far more convenient API provided by the Wirekite libraries (.NET for Windows, Objective-C/Swift for MacOS).

Ya I guess that's one way of doing it. MATLAB can already do this. There's a hardware package that I can use for the same. I think this is a good alternative. Will look into it.

If you want to communicate from the computer to the arduino, use USART. Arduino already has this pre-programmed, as well it's own GUI.


text:
Floating power supply for Arduino - Is it still connected to the USB ground?
I am trying to power my Arduino Mega 2560 from a benchtop power supply. I plan to essentially feed in a 9V supply directly on the Vin pin and connect the GND pin to the floating ground pin on the power supply. I noticed on the schematic that the UGND is connected to GND through this jumper. On the Arduino that I have these two pins are tied together. Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?
What is the best way to float the Arduino? Would it be ok to remove the jumper connection between UGND and GND? Or should I try something like a linear USB isolator like this?

Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

Yes.

Would it be ok to remove the jumper connection between UGND and GND?

No. I don't know quite why they provided that jumper. I can see no scenario in the datasheet where it suggests the two can be separate.

Or should I try something like a linear USB isolator like this?

If you want it to float then you need galvanic isolation on all USB pins. The device you link to will do that for you. There are others as well.
Personally in these situations I prefer to use a wireless communication system so there is no worry about grounds and isolation - it's naturally isolated.

What do you mean all USB pins? The data pins are differential with respect to the UGND right? Unfortunately I need the data to be transmitted through a wired link :|

By all pins I mean all pins. With galvanic isolation the ground is isolated. What is ground at one end is not ground at the other. Separating the grounds but not separating the rest of the signals means that only at the computer's end do the signals make any sense.


text:
Wifi proof with WeMos D1 ESP8266 Ad-Hoc
I am trying to use a WeMos module to send a broadcast message through an peer-to-peer network (Ad-Hoc). The thing is that i can't give a SSID nor Password to that network, i just can define it through them IP Addresses. As you suspect i don't have a specific idea of the configuration of the Wemos module.
What am I talking about?
I need to receive messages in a IEEE802.11 software-defined radio module. In this module I can't establish a network, just listen to a channel, and read whatever someone is sending. Think about it as a sniffer. But in this case i can assign to this module a MAC and IP within the Network.
What do I need?
I need just to:
Initialize peer-to-peer (Ad Hoc) network without an SSID nor Password.
Set a channel (I do it with channel 13, it is most times free).
Send a broadcast message in that channel to the SDR module in the network.

In other words
Module SDR:
 - IP:192.168.123.2
 - MAC: xxx
Wemos
 - IP:192.168.123.3
 - MAC: xxx
Through Wemos:

wifi, send broadcast message

The mask is /24, then it is going to send the message to all IPs from 192.168.123.2 to 192.168.123.254, then, for sure to the SDR Module, and i could receive it.
Thanks in advance.
Best regards,
Cristian

if there's not a formally connected peer, i doubt it would bother to broadcast. Look into the Nrf24L01, or even the 433Mhz wireless modules; they naively broadcast.

ESP8266 does not currently support Ad-Hoc/IBSS mode.


text:
Arduino code to run 2 thing simultaneously
I am making a project for my college in which I need to measure the rpm of the motor and show the real-time clock on the 128x64 GLCD simultaneously but when I run the project it only shows one thing at a time. is there any method to show both of them simultaneously I am not putting any code because I just compile my hall sensor separately and rtc code separately

You write code that does what you want. You never "do two things simultaneously", but write code that just does what you want. You have to understand what your current "two codes" do and how they work before you can try getting them to work together.

Without code it's hard to suggest improvements. Have a look at the blink without delay example (millis to get rid of blocking code like delay). This is what I used to emulate parallel processing.

Interrupts are your friend. So are the timer/counters.

Arduino Microprocessors are mostly single core devices and thus are unable to do more than one thing at a time.
The trick is to write code efficiently so it looks like several things are happening at the same time but in reality they just happen very quickly.
The LCD only needs to show time every second and displaying RPM every second should be enough so to get both to happen within a second should be possible.


text:
How can I have code in a project that won't compile for Arduino?
I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:
project/
    core.cpp      # core algorithms
    core.h        # header for core.cpp
    project.ino   # Arduino setup() loop() calling into core
    pc-main.cpp   # main(argv) calling into core

However, when I do this, the Arduino IDE wants to compile pc-main.cpp, which won't work since it uses stdio and all that. What can I do instead?
Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

What I've thought of:

I could put pc-main.cpp in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.
I could symlink the core.* files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.
I could put an #ifdef around the contents of pc-main.cpp, but I haven't found a suitable #define to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.
I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found arduino_ci and PlatformIO while researching this question. I'll switch to looking at such options if there isn't a good solution to the problem as I've stated it here.

[My question is arguably the same as Project structure to build for PC and Arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.]

I would use conditional compilation, like this:
#ifndef(ARDUINO)
// Non-Arduino code.
#endif

Thanks. Is there official documentation that specifies this #define exists?

You can add the #define to your code and manually change it when you change environments. You can look up Arduino compiler predefined symbols. Or you can tweak the IDE's compiler command to include "-DSYMBOL_OF_MY_CHOICE" which would define your symbol during an IDE compile and presumably be undefined in your desktop environment.

To be clear, I found that ARDUINO is already defined and I didn't need to configure anything, so Edgar's code works exactly as written. I'm asking if there's documentation for it, as I think the answer would be even better with a link.

@KevinReid: I didn't find it in a doc (although it's mentioned here), but in a Makefile intended to emulate the Arduino IDE.