text:
Connect Arduino Uno to video camera's web Server via Ethernet (not working)
I work with cameras in the film and TV industry. A project I have just started tinkering around with is building an Arduino Uno-based box that would automatically collect the metadata (settings, etc.) via the camera's built-in web server (over Ethernet, at least at the moment). Specifically the Arri Alexa camera.
Like I said, this camera already has a web server and the functionality built in for somebody to hook their computer directly up to the camera with an Ethernet cord (it actually uses an RJ45 - Lemo proprietary cable system in order to support some accessories that draw more power than RJ45 is capable of). Then when you navigate to the camera's IP address in a web browser it serves up a web page to you with all the camera settings and other things displayed.
I found that my test computer connected perfectly to the camera without fiddling with any network settings as the manufacturer's documentation seemed to indicate. Here are the basic network settings my computer had when connected directly to the camera over ethernet (no Arduino yet):

Notice the IP Address and subnet mask: 169.254.106.46 and 255.255.0.0 respectively.
Just to note, these are the manufacturer recommended settings I found in some literature:

Since that was working I tested the Arduino using the same settings. I am using an Arduino Uno combined with a Seeed Ethernet Shield (v2.0) which utilizes a Wiznet 5200 processor (not the 5100 normally used). Because of this you have to use the Ethernetv2_0 library that Seeed provides rather than the normal Ethernet library.
Here is my code, basically an adapted version of the WebClientRepeating example. I got this code working when I was just connecting to say arduino.cc and was going through the hub of my router (auto-assigned IP address). However when I attempt to connect to the camera with the Arduino sans Hub / Switch with a manually assigned IP address and subnet mask and all that I can never make the client (object) to connect. Basically this code is printing out "connection failed" to the serial monitor indicating and connection was never established.
#include <SPI.h>
#include <EthernetV2_0.h>

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
//IPAddress ip(169, 254, 106, 46); //Address that worked on my computer
IPAddress ip(169, 254, 1, 2); //Manufacturer recommended address

// fill in your Domain Name Server address here:
IPAddress myDns(1, 1, 1, 1); //Random, not sure if I need to do anything specific here

// subnet mask that manufacturer recommends and what worked on my computer
IPAddress subnet(255, 255, 0, 0);

// initialize the library instance:
EthernetClient client;

//IPAddress server(64,131,82,241); //arduino.cc IPAddress
IPAddress server(169, 254, 184, 143); //Arri Alexa (Camera) IPAddress

unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

#define W5200_CS  10
#define SDCARD_CS 4

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, subnet);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  // if ten seconds have passed since your last connection,
  // then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP GET request:
    client.println("GET /webremote/index.html HTTP/1.1");
    client.println("Host: 169.254.184.143");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

I guess my question is, if I'm using the exact same network settings that worked for my computer connecting to the camera, why aren't they working for the Arduino? I know this is somewhat of an obscure situation but I'll appreciate any ideas you can give me. Thanks!

The code looks reasonable to me - no obvious goofs that I can spot. If you're at a loss, I'd suggest stripping out the SD card stuff and disconnecting the reader, just in case it's interfering, and also testing against a PC rather than the camera - you'll be able to see if the connection comes in at all, for example. If you use Linux, or possibly Mac, then nc or netcat is a really useful tool for debugging this sort of thing.

Please link to the specifications or at least product pages for the particular hardware you're using; having to search for that themselves can discourage people from answering your question.

For what it's worth, I did check the datasheet and confirmed that the chip supports Auto MDI-X, so it's not a case that you need a crossover cable. However, I'd suggest trying your connection through a switch anyway as at least you'll have some lights to see if one end or the other is not making an Ethernet-level connection.

In the spirit of "Use the Source, Luke," I've had a look at the code on GitHub, which is I hope the same code that you're using or very similar to it.
There the four-parameter version of Ethernet.begin() takes the gateway, not the subnet mask, as the fourth parameter. The subnet mask, when passed in explicitly, is the fifth parameter of the five-parameter version.
This shouldn't actually make any difference since the gateway ought not be used for anything on the same subnet, and the default subnet for class B addresses  (from 128.0.0.0 through 191.255.255.255), in which range your address falls, is 16 bits, 255.255.0.0.
The problem is, the code linked has what I would argue is a bug:
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
{
  IPAddress subnet(255, 255, 255, 0);
  begin(mac_address, local_ip, dns_server, gateway, subnet);
}

The subnet mask is always set to 24 bits (255.255.255.0), in this call that you're using.
169.254.1.2 and 16.254.184.143 don't have the same 24-bit prefix, so the software (I assume, I've not followed it through) will try to contact the gateway you inadvertently supplied, which isn't even on the same network (not to mention nonexistent), and so fail.
Try calling the 5-argument Ethernet.begin() (passing in 0.0.0.0 for the gateway should be fine) and see if that fixes your problem.
I checked the WebClientRepeating example in that repo and they use the three-parameter version. Perhaps you switched to the four-parameter version, or perhaps you got your example from another library. (This example hasn't been modified since the start of the repo in April 2014.)

I agree with Mark that your code all looks sensible, apart from the line defining myDNS. I have no experience of the board/library you are using, but recently I saw an industrial board suffer from a similar problem that turned out to be it was trying to resolve an IP address to a name using reverse DNS and because the DNS server wasn't set properly it failed to connect. So it might be that by setting the address in the myDNS line to a valid DNS server (the one your test PC uses?) then the problem will go away.
If that doesn't work then can you read the manual and see if the Client object can be persuaded to give you an error code or message that would give you a hint as to why it isn't working?
I understand that 169.254.1.2 is the manufacturer recommended address, but why did you use 169.254.106.49 for the test PC? It's very unlikely to be anything, but...
Also (I'm sure this was your first check), is the connection between the Arduino and the camera a straight connection, there are no firewall, routers, switches or bridges in the way doing NAT or PAT or blocking certain connections etc?
(DNS = Domain Name Service, converts names like google.com into meaningful addresses like 1.2.3.4)


text:
Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino
I am working on a project where I need to calculate distance traveled by a robot. The mouse is connected to the arduino uno processor and I received some sample code from the arduino website to get started.
The problem is that the mouse gives difference distances depending on how fast or slow the it moves. (The same way you can move your pc mouse from side to side, fast and slow, and watch it cover different distances across the screen). Is there anyway to get get around this mouse setting? If not,  is there a more accurate sensor that can be used to accomplish the task? I'm having a hard time finding one.
Here is a link to the datasheet: http://www.alldatasheet.com/datasheet-pdf/pdf/333273/PIXART/PAW3402.html

Mouse acceleration is part of the OS, not the mouse. Are you really having this problem, or are you just predicting this problem?

If you could point out in the specifications you linked to where the mouse has the feature / ability to tell how fast it is moving I would appreciate it.  And will change my answer to accommodate.

Assuming under normal conditions a relative pointing device such as a optical mouse always reports relative position changes with out regard to speed.  If true, then consider that the speed of the robot is faster than the mouse can process.  Also, consider that the mouse's optics is out of focus with respect to the surface it is supposedly taking its positioning cues from.  Lastly, consider the surface may not be ideal for an optical mouse.  Attempt the same experiment using a sheet of paper or a "not-shiny" wood surface.
All surfaces have to be flat.  For example, a ceramic tile floor will likely not work as the surface will come in and out of focus during travel.  Make sure the elevation of the robot with respect to the surface is constant.  Inspect the wheels to make sure they are perfectly round and rotating around their center point.
Check and make sure you are not suffering from a integer calculation or type size problem.  Examine your code and make sure you are handling all cases including the expected maximum and minimum values properly.  And that your variables are large enough to handle these expected values.

It seems that the speed of the robot is faster than the mouse can process

on page 9 of the data sheet, bytes 2 and 3 give the detail of how fast the mouse is moving in the X and Y directions

@Jay, agreed.  I knew this was going to be tricky to explain.  I believe your Question describes an artifact of the driver, not the mouse.  That is, using most drivers, if you move the mouse 1 inch slowly the driver will move the cursor a much shorter distance across the screen then if you moved the mouse the same distance quickly.  I suspect, if you sum up all the mouse reports for both actions, the total will be nearly identical.

What you can do is use a hall effect (magnetic) sensor. If you connect a small magnet yo your shaft and connect the sensor in a way that the magnet will pass the sensor at every rotation, you can count the number of rotation that the shaft doesn thus calculating the distance.
It's a simple math equation:
distance = rotation * circonference of the wheels
For circonference, here is the equation:
circonfernce = diameter * PI

source: Stack Exchange

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

sort: votes


text:
getting error 'Serial' was not declared in this scope
I am adding Dust Sensor to my particle photon project at home,
I got this GitHub project that I want to test before implementing a final code.
I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.
but I keep getting error:
'Serial' was not declared in this scope
'Serial1' was not declared in this scope
'DEBUG' was not declared in this scope
'DEC' was not declared in this scope dustSensor.cpp:13:57:
I do have Serial.begin(57600) called in setup() function but still get the above error

add #include <Arduno.h> to cpp

you can find it with opened your Particle Project in the Desktop IDE and click on the Browse and Manage Libraries buttons and find the library you need. that's automatically include your libraries. see this docs.

I learned that I needed to include Arduino.h header file
apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.
The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.

The technical name for that is a "forward reference". Historical note: the necessity to declare the function before a forward reference originated because early C compilers were written to read your source code only once, rather than once to find function and variable definitions and again to generate code once the components of it were known. Such a compiler was easier to write and ran faster (which was a bigger concern at the time than it is today).

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


text:
Help setting up Dust sensor with Arduino Mega
So I wired Sharp Dust Sensor with Arduino Mega with below fritzing:

the connector cable only connects to the dust sensor as you can seee the image below:

however looking at other example projects the same dust sensor has wiring inverted. I followed the hookup and the code as given here: https://www.elecrow.com/wiki/index.php?title=Dust_Sensor-_GP2Y1010AU0F
but I get the result without having to connect the green wire to A0 and Yellow wire connected to D2
Raw Signal Value (0-1023): 346.00 - Voltage: 1.69 - Dust Density: 0.19
Raw Signal Value (0-1023): 394.00 - Voltage: 1.92 - Dust Density: 0.23
Raw Signal Value (0-1023): 398.00 - Voltage: 1.94 - Dust Density: 0.23
Raw Signal Value (0-1023): 408.00 - Voltage: 1.99 - Dust Density: 0.24
Raw Signal Value (0-1023): 433.00 - Voltage: 2.11 - Dust Density: 0.26
Raw Signal Value (0-1023): 468.00 - Voltage: 2.29 - Dust Density: 0.29

if I connect the yellow to A0 And green to D2  then I get below result.
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1005.00 - Voltage: 4.91 - Dust Density: 0.73
Raw Signal Value (0-1023): 952.00 - Voltage: 4.65 - Dust Density: 0.69
Raw Signal Value (0-1023): 712.00 - Voltage: 3.48 - Dust Density: 0.49
Raw Signal Value (0-1023): 631.00 - Voltage: 3.08 - Dust Density: 0.42
Raw Signal Value (0-1023): 559.00 - Voltage: 2.73 - Dust Density: 0.36
Raw Signal Value (0-1023): 504.00 - Voltage: 2.46 - Dust Density: 0.32
Raw Signal Value (0-1023): 463.00 - Voltage: 2.26 - Dust Density: 0.28
Raw Signal Value (0-1023): 431.00 - Voltage: 2.10 - Dust Density: 0.26
Raw Signal Value (0-1023): 409.00 - Voltage: 2.00 - Dust Density: 0.24
Raw Signal Value (0-1023): 430.00 - Voltage: 2.10 - Dust Density: 0.26
Raw Signal Value (0-1023): 413.00 - Voltage: 2.02 - Dust Density: 0.24
Raw Signal Value (0-1023): 377.00 - Voltage: 1.84 - Dust Density: 0.21
Raw Signal Value (0-1023): 453.00 - Voltage: 2.21 - Dust Density: 0.28
Raw Signal Value (0-1023): 368.00 - Voltage: 1.80 - Dust Density: 0.21
Raw Signal Value (0-1023): 367.00 - Voltage: 1.79 - Dust Density: 0.20
Raw Signal Value (0-1023): 364.00 - Voltage: 1.78 - Dust Density: 0.20
Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 356.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 358.00 - Voltage: 1.75 - Dust Density: 0.20
Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 345.00 - Voltage: 1.68 - Dust Density: 0.19
Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 375.00 - Voltage: 1.83 - Dust Density: 0.21
Raw Signal Value (0-1023): 395.00 - Voltage: 1.93 - Dust Density: 0.23
Raw Signal Value (0-1023): 421.00 - Voltage: 2.06 - Dust Density: 0.25
Raw Signal Value (0-1023): 441.00 - Voltage: 2.15 - Dust Density: 0.27
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 342.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
Raw Signal Value (0-1023): 335.00 - Voltage: 1.64 - Dust Density: 0.18
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 348.00 - Voltage: 1.70 - Dust Density: 0.19
Raw Signal Value (0-1023): 351.00 - Voltage: 1.71 - Dust Density: 0.19
Raw Signal Value (0-1023): 355.00 - Voltage: 1.73 - Dust Density: 0.19
Raw Signal Value (0-1023): 359.00 - Voltage: 1.75 - Dust Density: 0.20
Raw Signal Value (0-1023): 456.00 - Voltage: 2.23 - Dust Density: 0.28
Raw Signal Value (0-1023): 477.00 - Voltage: 2.33 - Dust Density: 0.30
Raw Signal Value (0-1023): 392.00 - Voltage: 1.91 - Dust Density: 0.23
Raw Signal Value (0-1023): 443.00 - Voltage: 2.16 - Dust Density: 0.27
Raw Signal Value (0-1023): 419.00 - Voltage: 2.05 - Dust Density: 0.25
Raw Signal Value (0-1023): 379.00 - Voltage: 1.85 - Dust Density: 0.21
Raw Signal Value (0-1023): 292.00 - Voltage: 1.43 - Dust Density: 0.14
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 311.00 - Voltage: 1.52 - Dust Density: 0.16
Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
Raw Signal Value (0-1023): 284.00 - Voltage: 1.39 - Dust Density: 0.14
Raw Signal Value (0-1023): 322.00 - Voltage: 1.57 - Dust Density: 0.17
Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 331.00 - Voltage: 1.62 - Dust Density: 0.17
Raw Signal Value (0-1023): 326.00 - Voltage: 1.59 - Dust Density: 0.17
Raw Signal Value (0-1023): 304.00 - Voltage: 1.48 - Dust Density: 0.15
Raw Signal Value (0-1023): 340.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 385.00 - Voltage: 1.88 - Dust Density: 0.22
Raw Signal Value (0-1023): 399.00 - Voltage: 1.95 - Dust Density: 0.23
Raw Signal Value (0-1023): 420.00 - Voltage: 2.05 - Dust Density: 0.25
Raw Signal Value (0-1023): 448.00 - Voltage: 2.19 - Dust Density: 0.27
Raw Signal Value (0-1023): 479.00 - Voltage: 2.34 - Dust Density: 0.30
Raw Signal Value (0-1023): 424.00 - Voltage: 2.07 - Dust Density: 0.25
Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
Raw Signal Value (0-1023): 330.00 - Voltage: 1.61 - Dust Density: 0.17
Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
Raw Signal Value (0-1023): 350.00 - Voltage: 1.71 - Dust Density: 0.19
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 314.00 - Voltage: 1.53 - Dust Density: 0.16
Raw Signal Value (0-1023): 305.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 317.00 - Voltage: 1.55 - Dust Density: 0.16
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
Raw Signal Value (0-1023): 384.00 - Voltage: 1.88 - Dust Density: 0.22
Raw Signal Value (0-1023): 417.00 - Voltage: 2.04 - Dust Density: 0.25
Raw Signal Value (0-1023): 435.00 - Voltage: 2.12 - Dust Density: 0.26
Raw Signal Value (0-1023): 446.00 - Voltage: 2.18 - Dust Density: 0.27
Raw Signal Value (0-1023): 310.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 462.00 - Voltage: 2.26 - Dust Density: 0.28
Raw Signal Value (0-1023): 432.00 - Voltage: 2.11 - Dust Density: 0.26
Raw Signal Value (0-1023): 391.00 - Voltage: 1.91 - Dust Density: 0.22
Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 324.00 - Voltage: 1.58 - Dust Density: 0.17
Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 294.00 - Voltage: 1.44 - Dust Density: 0.14
Raw Signal Value (0-1023): 283.00 - Voltage: 1.38 - Dust Density: 0.13
Raw Signal Value (0-1023): 274.00 - Voltage: 1.34 - Dust Density: 0.13

If I connect the green wire to A0 and Yellow wire to D2 I get below result
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10

I am not really sure whether I am getting the correct result or not, and have I hooked up correctly.

The outline diagram shows the connection order:

As you can see from the image in the second row pin 1 is closest to the edge of the unit. In your image that is red.  So following those down and matching them to the "Terminal Configuration":

V-LED = Red (Connect to 5V via resistor)
LED-GND = Black (GND)
LED = Yellow (D2)
S-GND = White (GND)
Vo = Green (A0)
Vcc = Blue (Connect direct to 5V)

connecting this way gives this result:
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10

The way you wired it before may have killed the IR LED through over-current...

is IR LED replaceable manually by soldering ?

If you can get to it, possibly. Unlikely though for a novice.

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


text:
checking if user is opening root entry point of the IP address on esp8266 webserver
I am trying to open load a webpage from ESP8266 that displays temperature and humidity of my room if I only type root URL:192.168.1.89
GET / HTTP/1.1
Host: 192.168.1.89
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50
Accept-Language: en-us
DNT: 1
Accept-Encoding: gzip, deflate

to do that in my esp8266 sketch I am trying this logic:
bool readRequest(WiFiClient& client) {
  bool currentLineIsBlank = true;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      if (c == "GET / HTTP/1.1"){
        Serial.println("Got root");
        client.println(handleRoot()); // where handle root contains web page
      }
      else{
        Serial.println("Did not got root.");
      }
      if (c == '\n' && currentLineIsBlank) {

        return true;
      } else if (c == '\n') {
        currentLineIsBlank = true;
      } else if (c != '\r') {
        currentLineIsBlank = false;
      }
    }
  }
  return false;
}

but the condition to check if it met GET / HTTP/1.1 never validates.

Just use a HTTP server library.

@gre_gor in a different project I am using ESP8266WebServer  but I want ed to give a try to WiFiServer server(80); while sticking with ArduinoJson.h library as well.

This applies to networking as well as serial. Also this may be of use to you, along with this.

@gre_gor I switched back to ESP8266WebServer.h however I cannot pass ArduinoJson.h's jsonObject to server.send(...) https://arduino.stackexchange.com/q/46961/27363


text:
How to use DO pin on ldr module?
I have ldr module with 4 pins
 1. Vin
 2. Gnd
 3. AO
 4. DO
I want to know how can i take advantage of DO suppose i want to turn on lcd display when light falls on the ldr sensor!

I have noticed when light falls on ldr sensor the Green  led with DO written next to it lights up.

I bet if you look where you bought that little board from they have some sort of instructions on how to use it.  They usually do.

I bought it long time back i dont even remember now :(

it is digital out ... do some experimenting

So go look online for a similar one.  Check and see if it has some numbers or something on it that you can google.  Be smart about this.

what is the problem? wire and code it as button

The DO pin gives a Digital Output that is HIGH when the light falling on the LDR is above a threshold, and LOW when it's below a threshold. Just connect it to a digital input pin and read that pin with digitalRead().
You can change the threshold by adjusting the small blue trimpot.

fwiw, this is problematic because the LDR can get "accustomed" to a light level and change responsiveness, so the threshold adjustment won't always keep the same objective light level (lux) setting as a trigger level, but it should be enough for "is it light or dark". It would be better done in software, so you can work around such fatigue and surging values from the LDR with debouching, self-calibration via computed averages, and actually seen high/low values as a min/max.

@dandavis, for that there is AO (analog output). but why would one buy a module for LDR and one resistor.

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


text:
how to write an int to RFID tag and when read then store that in an array
The writing code is from the MFRC522 Example below:
I have added an array to store the value but it does not store it as the same value written to it in the writing. instead it stores it as byte values.
I am fairly new so would appreciate any help.

/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Enter the weight, ending with#"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

}

and the reading code is :
/*
 * Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

int weightArray[2];
int counter = 0;

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read

}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.println("Detected");

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
/*  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");
*/
  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);
    }

  for(int i = 0; i < sizeof(weightArray) / sizeof(weightArray[1]); i++) {
    Serial.print(weightArray[i]);
  }

  counter++;

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//
````````````````````````````````````

OK, so you posted some code.  But in order for people to help you, please also include a question.

First you are not writing int value during write as, buffer is defined as byte type. Your are just type casting it char* during serial read for storing data. And Your are writing just first 16 value in your CARD, so you might not get the expected results.
byte data type provides only 8 bit or 1 byte of memory location.
int data type provides 2 bytes or 4 bytes of memory location.


text:
Arduino and NodeMCU problem with wifi conecction
Hello guys I am beginner with micro controllers but I am trying to make a simple IoT with Arduino and NodeMCU as WiFi. I was using this tutorial and code https://www.electronicshub.org/wifi-controlled-led-using-esp8266-and-arduino/.
When I upload the code for the first time everything worked perfectly but every other time when I upload the same code my program is stuck in a loop.
Program is in infinite while loop while(!esp8266.find("OK")) because as far as i understand it didnt receive the OK status from ESP.
But in fact esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG); prints OK in my console so it means that it should work but it doesnt...
Do you guys have any idea whats the reason?
Code looks as follows;
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //Pin 2 & 3 of Arduino as RX and TX. Connect TX and RX of ESP8266 respectively.
#define DEBUG true
#define led_pin 11 //LED is connected to Pin 11 of Arduino

void setup()
  {
    pinMode(led_pin, OUTPUT);
    digitalWrite(led_pin, LOW);
    Serial.begin(9600);
    esp8266.begin(115200); //Baud rate for communicating with ESP8266. Your's might be different.
    esp8266Serial("AT+RST\r\n", 5000, DEBUG); // Reset the ESP8266
    esp8266Serial("AT+CWMODE=1\r\n", 5000, DEBUG); //Set station mode Operation
    esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG);//Enter your WiFi network's SSID and Password.

    while(!esp8266.find("OK"))
    {
      }
    esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);//You will get the IP Address of the ESP8266 from this command.
    esp8266Serial("AT+CIPMUX=1\r\n", 5000, DEBUG);
    esp8266Serial("AT+CIPSERVER=1,80\r\n", 5000, DEBUG);
  }

void loop()
  {
    if (esp8266.available())
      {
        if (esp8266.find("+IPD,"))
          {
            String msg;
            esp8266.find("?");
            msg = esp8266.readStringUntil(' ');
            String command1 = msg.substring(0, 3);
            String command2 = msg.substring(4);

            if (DEBUG)
              {
                Serial.println(command1);//Must print "led"
                Serial.println(command2);//Must print "ON" or "OFF"
              }
            delay(100);

              if (command2 == "ON")
                    {
                      digitalWrite(led_pin, HIGH);
                    }
                   else
                     {
                       digitalWrite(led_pin, LOW);
                     }
          }
      }
  }

String esp8266Serial(String command, const int timeout, boolean debug)
  {
    String response = "";
    esp8266.print(command);
    long int time = millis();
    while ( (time + timeout) > millis())
      {
        while (esp8266.available())
          {
            char c = esp8266.read();
            response += c;
          }
      }
    if (debug)
      {
        Serial.print(response);
      }
    return response;
  }

use the WiFiEsp library

why do you need to upload the same code more than once?

@Juraj thanks for your answer, I will read about it.

@jsotola thanks for your answer, well i made some changes to my code and uploaded it but it stuck in infinite loop so i revert changes and upload original code which worked before but now it is also stuck in the same loop. It never finds "OK".

Your esp8266Serial function already read the response including the "OK" from the input so find() can't read it again


text:
Can't get fastled.h and remoteme.h to work together
I'm trying to make a Google Assistant controlled LED strip, but I'm stuck. I can control the on board LED of the nodemcu with Google Assistant, and I can control a LED strip too, but I can't combine the two. This is my code:

#define WIFI_NAME "****************"
#define WIFI_PASSWORD "********"
#define DEVICE_ID 1
#define DEVICE_NAME "Google_ESP"
#define TOKEN "************"

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#include "FastLED.h"

#include <RemoteMe.h>
#include <RemoteMeSocketConnector.h>

#include <ESP8266WiFi.h>

#define ledpin D0

RemoteMe& remoteMe = RemoteMe::getInstance(TOKEN, DEVICE_ID);

//*************** CODE FOR CONFORTABLE VARIABLE SET *********************

inline void setLedstrip(boolean b) {remoteMe.getVariables()->setBoolean("Ledstrip", b); }

//*************** IMPLEMENT FUNCTIONS BELOW *********************

// How many leds in your strip?
#define NUM_LEDS 120

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN D3

CRGB leds[NUM_LEDS];

boolean ledsOn = 0;

void onLedstripChange(boolean b) {
    Serial.printf("onLedstripChange: b: %d\n",b);

    if(ledsOn != b){
        if(b == 1){
            turnLedsOn();
        }
        else{
            turnLedsOff();
        }

        ledsOn = b;
    }
}

void setup() {
    FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

    Serial.begin(9600);

    WiFi.begin(WIFI_NAME, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED) {
        delay(100);
    }

    remoteMe.getVariables()->observeBoolean("Ledstrip" ,onLedstripChange);

    remoteMe.setConnector(new RemoteMeSocketConnector());
    remoteMe.sendRegisterDeviceMessage(DEVICE_NAME);

    pinMode(ledpin, OUTPUT);
    digitalWrite(ledpin, HIGH);
}

void loop() {
  remoteMe.loop();
}

void turnLedsOn(){
  digitalWrite(ledpin, LOW);
  leds[0] = CHSV(0, 100, 100);
  FastLED.show();
}

void turnLedsOff(){
  digitalWrite(ledpin, HIGH);
  leds[0] = CHSV(0, 0, 0);
  FastLED.show();
}

As you can see, it should turn on the on board LED and the first LED of the strip. It only does the on board one.

Hi @CodeHard, Could you provide links or the actual code to the two programs that work? Handy if you could provide links to the libraries you used. Thanks.

Wow, okay. Nevermind...
I just read my code of the ledstrip only program and the google assistant ledstrip to look for differences, and found out it didn't work because I used pin D3 instead of pin 3...

Also, ledpin should be 0 instead of D0.

Please add that as an answer down below. You can answer your own question and get some upvotes from solving it (hopefully).


text:
what is causing my esp8266 setup function to reinitialise?
Here is code I have written:
#include <stdio.h>
#include <ESP8266WebServer.h>

#define MAX_WIFI_INIT_RETRY 50
#define WIFI_RETRY_DELAY 500

const char* wifi_ssid = "ssid";
const char* wifi_passwd = "password";

ESP8266WebServer http_rest_server(80);

const int numParams = 20;
String params [numParams];

String toString(String my_array[], int size)
{
  String string;
  for (int i = 0; i < size; i++) {
    string = string + ", " + my_array[i];
  }
  return string;
}

int init_wifi() {
  int retries = 0;
  Serial.println("Connecting to WiFi AP..........");
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_passwd);
  // check the status of WiFi connection to be WL_CONNECTED
  while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
    retries++;
    delay(WIFI_RETRY_DELAY);
    Serial.print("#");
  }
  return WiFi.status(); // return the WiFi connection status
}

void readParams(String (& params) [numParams])
{
  int mn = WiFi.scanNetworks();
  for (int i = 0; i < mn; i++)
  {
    //    Serial.println(WiFi.SSID(i).c_str()); // prints name of all hotspots in serial monitor.
    params [i] = WiFi.SSID(i).c_str();
  }
}

void listHotspots() {
  String results = toString(params, sizeof(params));
  Serial.println(results);
  http_rest_server.send(200, "text/plain", results);
}

void config_rest_server_routing() {
  http_rest_server.on("/", HTTP_GET, []() {
    http_rest_server.send(200, "text/html",
                          "Welcome to the ESP8266 REST Web Server");
  });
  http_rest_server.on("/hotspots", HTTP_GET, listHotspots);
}

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

  init_led_resource();

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  readParams (params);

  if (init_wifi() == WL_CONNECTED) {
    Serial.print("Connetted to ");
    Serial.print(wifi_ssid);
    Serial.print("--- IP: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.print("Error connecting to: ");
    Serial.println(wifi_ssid);
  }

  config_rest_server_routing();

  http_rest_server.begin();
  Serial.println("HTTP REST Server Started");
}

void loop(void) {
  http_rest_server.handleClient();
}

when I access the root url: i.e. 192.168.0.101/ It opens the root page fine, but when I try to open the 192.168.0.101/hotspots It reboots the ESP8266  until the page stops to make a new attempts and I get nothing in result.
In the serial monitor I am seeing this exception when I try to visit the ip/hotspot page .
Exception (9):
epc1=0x4020148a epc2=0x00000000 epc3=0x00000000 excvaddr=0x4d2d5456 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffde0 end: 3fffffc0 offset: 01a0
3fffff80:  3fffdad0 3ffee553 3ffee5a4 40201347
3fffff90:  402086b8 6505a8c0 feefeffe feefeffe
3fffffa0:  3fffdad0 00000000 3ffee5e0 40206614
3fffffb0:  feefeffe feefeffe 3ffe8510 40100479
<<<stack<<<

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
Connecting to WiFi AP..........
######Connetted to Hometelecom1N5E--- IP: 192.168.0.101
HTTP REST Server Started

is it something wrong with the toString function ?

cause 4 is a watchdog reset

so what might be causing watchdog reset ?

not calling a function which 'feeds the dog' long enough. decode the stack trace

nevermind, I figured out solved my problem

When a program crashes, you can debug the crash based on the Fatal exception number.
 Exception (9)  Unaligned read/write operation addresses
     1. Unaligned read/write Cache addresses
     2. Wild pointers

This leads than as Juraj points out to a WD reset:
 rst:4     Hardware WDT reset

To get the exact part of the code paste the >>>stack>>> into the window of the espExeption decoder in the ArduinoIDE. Details how to install and use.
My educated guess is that the heavy use of String class in combination with lot of String operations with the getHotspot function leads to heap corruption and crashes the Esp8266. Try defining fixed char arrays and get rid of the String class to get a stable running system. Post the espExeption decoder result as edit to your question if you thing something else might be fishy

thank you @codebreaker007 I managed to get the code working can you please take a good look at my code review at https://codereview.stackexchange.com/q/242917/22943


text:
how to use arduino to detect an 8Mhz ultrasonic pulse using piezo disc as receiver?
i need a code to detect an 8MHz ultrasonic pulse and show its properties eg wave pattern and amplitude on serial plotter( like an oscilloscope)

Which Arduino do you think you want to use for this?

I have arduino uno...do you think it'll work?

In a word: no.
Let's crunch some numbers...  You want detail like an oscilloscope.  Okay...
My scope is 50MHz bandwidth and runs at 1 giga samples per second.
Drop that down to 8MHz with the same kind of resolution, and you get (1,000,000,000 * (8/50)) = 160,000,000 samples per second.
That's 10 times more samples per second that the clock speed of the Arduino, and it takes at least 1664 clock cycles to take one sample.
So, no.  You need a board with an ADC which can run in the hundreds of millions of samples per second. The Arduino can only run at just under 10 thousand samples per second.
A slight discrepancy.
Even the Arduino Due can only get as good as 1Msps. I have seen MCUs with 15Msps theoretical maximum, but for the kind of output you want you would need considerably more.
So no, there won't be a cheap development "Arduino-like" board around that will do what you want. There may be an expensive one with a very fast CPU, DSP, ultra-high-speed ADC, etc, but you won't be programming it with Arduino, and you most likely won't be able to afford it to just play with.

Thanks for the info but what is the highest value of frequency that arduino can detect with its clock speed of 16Mhz?

You can sample at a maximum of 9615 samples per second, so 4807.5Hz is the maximum frequency component you can recover.  If you don't care about the shape of the signal you can turn it into a square wave and use digital inputs (such as the T1 input to Timer1) to measure the frequency, but that's all you'll get - the fundamental frequency. No shape, no amplitude, nothing - just the fundamental frequency. And 8MHz is the absolute top limit (F_OSC/2).


text:
Arduino board with built-in Bluetooth
I would like to find an Arduino with built-in Bluetooth.
I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.
The official Arduino foundation did produce an board but it's retired now.

Yeah i know what google is. Why it would be better? Less moving parts, well tested board. If you think its an dumb question dont answer then. There are plenty of other post waiting for your knowledge.

I'm not being sarcastic, but have you thought this through?  I appreciate that there might be an issue with serial comms, but I would have thought most of that would be programming errors rather than a 'hardware' issue.  If I'm not right say!  Having a separate board would give you the advantage of being able to spare it or upgrade it to support BT5, BT6 or even BT 921!  Also a separate board means you have more options over what the Arduino board can be.  Maybe looking at why you have serial problems would be a good point to focus on?

@Sigma - If a board becomes a moving part, you need to check your soldering :D

Yeah you are probable right. But when the application iworks 98% of the time. It makes it hard to understand or debugg what the 2% failures are because of. I need to be 100% sure it is programmatic and not hardware.

Adafruit could be a good place to look. Thanks! Have seen that there has been some kickstarter boards, but they are not mass produced.

What about using an ESP32 with integrated BT?

@CodeGorilla Yeah that could be a solution.

Arduino has just released a MKR WIFI 1010 board that includes an ESP32 module that allows Bluetooth connectivity. It's mainly an internet of things board but it supports:

Bluetooth low energy, BLE
Wifi

Yes Im using that one, great board.

This is my currently favourite Arduino compatible board:
https://wiki.wemos.cc/products:d32:d32

ESP32 is great: offers both wi-fi, Bluetooth and BLE connection as well as lots of GPIO.
9 GPIO's can be used as capacitive touch sensors (it has 10, but only 9 are available).

This is also a great option.

There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0
Bluno - An Arduino Bluetooth 4.0 (BLE) Board


text:
Can't send SoftwareSerial to Class Object
I have a problem when I try to use SoftwareSerial in a class..
Here my detail My class
class MyEsp8266
{
 protected:
     SoftwareSerial *esp8266;
 public:
     MyEsp8266(SoftwareSerial *_esp8266){
           esp8266 = _esp8266;
     }
     void begin(int baud){
        esp8266->begin(baud);
     }
     String testAT(){
          esp8266->println("AT");
          return esp8266->readString();
     }
}

My Arduino code
#include <SoftwareSerial.h>
#include "MyEsp8266.h"
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);
MyEsp8266 wifi(&_esp);

void setup() {
    Serial.begin(9600);
    wifi.begin(115200);
    Serial.println(wifi.testAT());
}

It doesn't log anything But when I have used all code in Arduino code it worked.
#include <SoftwareSerial.h>
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);

void setup() {
    Serial.begin(9600);
    _esp.begin(115200);
    _esp.println("AT");
    Serial.println(_esp.readString());
}

Thank any tips.
Regards.

You forgot to print the return value of wifi.testAT();...?

it my mistake when post question I have updated it

This is more of a work-around than a solution, but the code you're trying to get to work, worked for me once I changed
wifi.begin(115200);

to
wifi.begin(9600);

(sorry I don't have enough karma to just comment)

Hi baud 115200 worked with secondary code.

I agree! and when testing your desired block of code, I got it to output the test line by changing the baud from 115200 to 9600.

I think that means your Wifi module use baud 9600.

To clarify, I was using the bluetooth HC-05 which a quick Google search tells me It can go up to 1382400. But besides, I tried both code samples, the second worked without modification (meaning my hardware can handle 115200) and then when I tried the first, and once I changed the baud to 9600 it worked. Did adjusting the baud rate on the first code sample not fix the problem for you?

authors: Евгений Циулин


text:
Instance does not name a type, in function void loop (8x8 matrix)
Hey guys I'm doing a beginners project 8x8 matrix and I have some errors when compiling
The Errors are;

MyBlink:0: error: 'Instance' does not name a type
MyBlink.cpp: In function 'void loop()':

-MyBlink:40: error: 'row1' was not declared in this scope
 Instance code:
//the pin to control ROW
const int row1 = 2; // the number of the row pin 9
const int row2 = 3; // the number of the row pin 14
const int row3 = 4; // the number of the row pin 8
const int row4 = 5; // the number of the row pin 12
const int row5 = 17; // the number of the row pin 1
const int row6 = 16; // the number of the row pin 7
const int row7 = 15; // the number of the row pin 2
const int row8 = 14; // the number of the row pin 5
//the pin to control COl
const int col1 = 6; // the number of the col pin 13
const int col2 = 7; // the number of the col pin 3
const int col3 = 8; // the number of the col pin 4
const int col4 = 9; // the number of the col pin 10
const int col5 = 10; // the number of the col pin 6
const int col6 = 11; // the number of the col pin 11
const int col7 = 12; // the number of the col pin 15
const int col8 = 13; // the number of the col pin 16
void setup(){
int i = 0 ;
for(i=2;i<18;i++)
{
pinMode(i, OUTPUT);
}
pinMode(row5, OUTPUT);
pinMode(row6, OUTPUT);
pinMode(row7, OUTPUT);
pinMode(row8, OUTPUT);
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
}
void loop(){
int i;
//the row # 1 and col # 1 of the LEDs turn on
digitalWrite(row1, HIGH);
digitalWrite(row2, LOW);
digitalWrite(row3, LOW);
digitalWrite(row4, LOW);
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
digitalWrite(col1, LOW);
digitalWrite(col2, HIGH);
digitalWrite(col3, HIGH);
digitalWrite(col4, HIGH);
digitalWrite(col5, HIGH);
digitalWrite(col6, HIGH);
digitalWrite(col7, HIGH);
digitalWrite(col8, HIGH);
delay(1000);
//turn off all
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
delay(1000);
}

MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line Instance code: on the first line both errors went away.
Cheers

There is typo in your program. Exactly you should comment out the first line of your code. Adding two slashes at the beginning of the first lines.
Instance code:

As this is not a valid syntax for your code. The compiler is not recognizing what are you trying to do. So it generates a second error because everything that comes after may generate an unknown error.
Next time try to solve these kind of problems by reading your console log as it describes exactly at which lines the compiler has found an error. You can see that it generates an error at line 0:

Myblink:0:error....

You have multiples errors on this program because as i said before sometimes they are generated as a consequence of your previous error. So you should also try to fix your errors from top to bottom.

The colon is a bit misleading, it is used in C++ to denote inheritance like this:
E.g.
class Form
{
  int _area;

  public Form(area)
  {
    _area = area;
  }
}

class Circle : class Form
...

However, this is not your intention probably.
Also the colon is used for calling base constructors and for labels to go to (goto, never use this).


text:
Yún vs Uno with Yún Shield
What are the differences between an Arduino Yún and a Arduino Uno with an added Yún Shield? And is there a way to expand the storage of the Yún / Yún Shield?

As Majenko wrote: the Arduino Yún = Leonardo + Yún shield. You get into a lot of trouble with the Arduino Uno, and the Yún shield has already enough troubles on its own.
Maybe the Arduino Mega 2560 can be used when both the hardware and software is changed to use another hardware serial port for the Yún shield. If you start with the Yún shield, then use the Leonardo. Don't even try the Arduino Uno.
It is possible to upload a sketch via Ethernet or WiFi, but that often fails. Therefor you need the usb-serial connection to the computer to upload a sketch.
Even when you use a Arduino Leonardo, the communication between the Yún shield and the Arduino board (the 'Bridge') can cause troubles. In OpenWRT a Python script is used to read the serial data from the 'Bridge', which causes a lot of CPU usage.
The Yún shield is not fully compatible with the Arduino Yún. I think a few GPIO pins are different and maybe some other things. That means you are stuck to the firmware of the Yún shield, which can have issues and is not fully compatible with the Arduino Yún firmware.
When installing software in OpenWRT, the rootfs is filled quickly. You can type df or df -h to see the disk usage. I have read about ways to add a SD memory card or a USB flash drive to the rootfs. I have not tried that because I want OpenWRT to run even without a SD memory or USB drive.
An SD memory or USB drive can be used to store a website on it, or scripts, or music files, and so on.
When you need more memory, you might want to try the Raspberry Pi. The Raspberry Pi Zero W is very cheap and has WiFi.

I already own a 1x Raspberry Pi B 512MB and 2x Raspberry Pi 3, Arduino Yun interested me

Using OpenWRT is fun, since everything is optimized for small systems. However, my advice is to stay away from the Yun. The 'Bridge' causes too many problems. If you want to get closer to the Arduino, the NodeMcu is better.

The differences are manifold.
The biggest difference is that the Yun employs an ATMega32U4 as the MCU, whereas the Uno employs the ATMega328P. This has big ramifications with the Yun shield.

The ATMega32U4 uses a dedicated USB connection to the USB socket, and a dedicated UART connection to the MIPS SoC.
The ATMega328P has only a UART connection which is shared between the USB interface and the MIPS SoC.

This means that the Yun shield can interfere with the operation of the USB connection. You cannot communicate between the MIPS SoC and the Uno whilst at the same time using the USB connection, like you can with the full blown Yun. Uploading sketches can be an issue - you may want to remove the Yun shield while uploading.
The Yun is closer in operation to an Yun Shield + Arduino Leonardo than an Uno.


text:
Arduino Due vs Mega 2560
What can an Arduino Due do that a Mega 2560 can't? What can a Mega 2560 do that a Due can't? I've heard the Due is 3.3V so it can't work with most shields.

Since the due uses a ARM chip instead of an AVR you might run into problems with certain libraries that only support AVR.

people like the mega because it's "more uno", while the due is trying to be a "faster uno" but jettisons much of the beloved uno cargo in doing so.

The 'R3' version boards and shields are compatible with 3.3V and 5V. For example the Ethernet Shield V1 version 'R3' can be used with the Due. The new Arduino Ethernet Shield 2 is also compatible with the Due.
Many older shield are not compatible with the Due, but do you really need to use an old shield ?
Most sensors are 3.3V, and also a SD memory card is 3.3V. That is a lot easer with the Arduino Due which runs at 3.3V.
The Arduino Mega 2560 board is the only board with 10k pullup resistors at SDA and SCL, therefor it has a 5V I2C bus. When a 3.3V sensor with I2C is used, you need a I2C level shifter. When a 3.3V with SPI is used, you need more hardware.
The Arduino Mega pins can drive more than 20mA, it can be used to drive 10 leds with 20mA simultaneously, the Arduino Due can't do that.
My suggestion is to use an Arduino Uno for all kind of testing. It's always good to have one lying around. Start with an Arduino Uno if you want to learn programming and have fun with leds and buttons.
The Arduino Zero or MKRzero or M0 have a M0+ processor at 3.3V and they can be used for all kind of nice projects. When you already know a little about programming and electronics, this is a very good choice.
The Arduino Due has more processing power then the M0+.
The Arduino Mega 2560 is still used, because there are many libraries and shields that are compatible with the Arduino Mega 2560.

The Due can do a lot of things much faster. It has more memory and far more processing power. It has more flexible and more powerful built-in peripherals.
It can't easily interface with 5V devices though.
The Mega2560 has less memory and far less processing power, but interfacing with legacy 5V devices is far easier. It's also more forgiving to the novice user than the more complex SAM3X chip.
From an Arduino programming point of view both boards are pretty much programmed the same. The language is, excepting a few esoteric anomalies, largely the same. However when you come to do low-level programming instead if relying on the Arduino API you would find that the ATMega2560 is a much simpler chip to program.  Power comes at a price. The more powerful SAM3X chip is much harder to get to grips with and program.
It's like comparing a Ford Escort with a Boeing 737. They're both vehicles, and they can both get you from A to B. The Boeing does it much faster and can carry more people, but flying it is a lot harder than driving a Ford Escort, and you can't fly it on an old-fashioned road.

Ahhhh... There is a more profound problem than these mentioned because the MEGA treats double precision declarations as floating point ( far less precision ).  I was working with 1 CM GPS Location coordinates requiring double precision variables.  It took a while for me to discover that ONLY the DUE compiles to a true double precision variable.  The MEGA and most others do not.  They convert double to float at compiler level.  This is only meaningful if extremely precise math must occur.
Donald


text:
MAX7219 library that can compensate for poorly designed/miswired 8x32 panel?
I have this sample code:
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define MAX_DEVICES 4
#define CLK_PIN   11
#define DATA_PIN  12
#define CS_PIN    10

MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void) {
  P.begin();
  P.print("PPPPPPPP");
}

void loop(void) {
}

And this is how it lights up the display:

I presume that the code displays text incorrectly, because the display manufacturer has connected individual 8x8 displays "differently than any library expects" (i.e. in red I have annotated the column addresses for my display, while with green I have annotated what they would have to be for this library to show text correctly).
I have two questions:

Is there any good Arduino graphics library that would allow me to fix from software the addressing issue specific to my display?
Since in the future I plan to make a 16x64 display out of 4 of these, then is there a library capable of doing that as well (i.e. have vertical font size of 12-16 pixels)?

No software will work properly when hardware doesn't.

@IgnacioVazquez-Abrams I imagine that if there was graphics library that would allow me to render pixels in memory buffer instead of hardware directly, then I could compensate this hardware bug by using LedControl library and calling something like setColumn((7-addr&0x7)+addr&252,value). So is there a library that allows to render  pixlels in memory buffer?

This may help. It's hard to say if you have bad hardware or a bad library.

The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.
Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.
The author did 99% of the work for you. You just need to finish the last 1%.

You mean to change the code in library itself? This somewhat puts maintenance burden on me to share a fork of patched Parola library with my code until I get these Parola changes upstreamed and downstream (ie. Arduino Web IDE) picks them up. So I would prefer to use a library that can deal with this issue out of the box, if there is one.

the solution is really simple: swap bit orders. so you just need to write a function that swaps bit 7 <-> bit 0, bit 6 <-> bit 1, bit 5 <-> bit 2, bit 4 <-> bit 3. very easy to do.

I experienced the same problem.  This is a hardware design problem.  It is probably why these things were so cheep on EBAY.
These things shift 1 bit at a time in a serpentine pattern. They were wired wrong. They should have been wired to display bits
1-8 in col 1,
9-16 in col 2,
17-24 in col 3,
25-32 in col 4,
33-40 in col 5,
41-48 in col 6,
49-56 in col 7,
57-64 in col 8.

however they were wired to have
1-8 in col 8,
9-16 in col 7,
17-24 in col 6,
25-32 in col 5,
33-40 in col 4,
41-48 in col 3,
49-56 in col 2,
57-64 in col 1.

This could be fixed in software with some slight problems. The chips they used are basically shift registers.  But they don't have the ability to blank the screen.
You could use some timing tricks to paint the entire display then pause then paint the entire display again.  This is the only way I see that you could achieve motion.
You would experience a quick blur of motion between each movement. Generally undesirable.

No software will work properly when hardware doesn't. –
Ignacio Vazquez-Abrams
Dec 3, 2017 at 20:26


text:
Arduino Uno WiFi - WiFi mode keeps changing
I have an Arduino Uno WiFi device, which is turned on all the time (day and night). The WiFi mode is set to 'STA'. But from time to time it switches to 'AP+STA' mode automatically, so the device is visible in the network as an Access Point, which is not what I want. Is there a way to prevent my Arduino Uno to switch the WiFi mode by itself? Can it be done via code maybe? Thank you for your help.
Here's the code that is working on it (and it's still working without any problems):
#include <Wire.h>
//#include <Ciao.h> // for older IDE
#include <UnoWiFiDevEd.h> // for newer IDE

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

int sensorsValues[] = {9999,9999,9999};
int timerCount = 25;
static const uint8_t analogPins[] = {A0, A1, A2};

// for LEDs
int NUMPIXELS = 9;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, 2); // (numOfPixels, pinNo, options)

boolean hasChanged = false;

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code
  //start serial connection
  Serial.begin(9600);
  for(int i=0; i<3; i++){
    pinMode(analogPins[i], INPUT_PULLUP);
  }
  strip.setBrightness(40);
  strip.begin(); // Initialize the NeoPixel library.
  strip.show(); // Initialize all pixels to 'off'
  Ciao.begin();
}

void loop() {
  for (int i = 0; i < 3; i++) {
    int sensorVal = analogRead(analogPins[i]) >= 1000 ? 1 : 0;
    if( sensorsValues[i] != sensorVal ) {
      hasChanged = true;
      if (sensorVal == 1) {
        // green light
        strip.setPixelColor( (i*3), 100, 255, 100);
        strip.setPixelColor( (i*3)+1, 100, 255, 100);
        strip.setPixelColor( (i*3)+2, 100, 255, 100);
        strip.show();
      } else {
        // red light
        strip.setPixelColor( (i*3), 255, 50, 50);
        strip.setPixelColor( (i*3)+1, 255, 50, 50);
        strip.setPixelColor( (i*3)+2, 255, 50, 50);
        strip.show();
      }
    }
    sensorsValues[i] = sensorVal;
  }
  timerCount += 1;
  if( hasChanged == false && (timerCount % 30) == 0 ){
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/active", "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
  }
  if (hasChanged == true && (timerCount % 5) == 0 ) {
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/a/" + String(sensorsValues[0]) + "," + String(sensorsValues[1]) + "," + String(sensorsValues[2]), "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
    hasChanged = false;
  }
  if (timerCount > 30) timerCount = 0;
  delay(1000);
}

Are you running any code on it?  If so is it possible for you to post the code.

Yes, the code reads 3 analog sensors, send their values to server if any has changed and it controls LED strip. Seems like I can't post the code here..

You can't do that :)  You'll need to edit your post.  Have you tried monitoring it with something like Blink running (a do nothing program).  If it doesn't do it then its your code, if it does its something to do with the board.

@CodeGorilla I just edited my question adding a code.

So unless Ciao.write() is flicking the AP on and off its a function of the board.  There might be some register you can set to prevent it, but your going to have dig through the documentation for the board.  Sorry :(

Well, I already dig a lot in the documentations but found nothing. That's why I posted this question here.. Anyway, thanks.

OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to http://<IPADDRESS>/wifi/info you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to http://<IPADDRESS>/wifi/setmode?mode=<MODE> to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'.
I've created a little cron job on my server that checks the wifi mode and changes it if needed.

Note that when the Uno WiFi board first boots, it is in AP+STA mode...

Which means it broadcasts its own SSID (that's the AP part).

AND

It can connect to an existing wireless AP on your network, if you've configured those settings (that's the STA part, because it's a STAtion off the infrastructure AP).

IDEALLY

You will change it to STA mode so it connects to your existing wireless AP only and stops broadcasting as its own AP.

Why does yours go back to AP+STA mode?  Is your sketch crashing/running out of memory/rebooting?  Is it older firmware?  I'm not sure.

The thing is that I have 5 Uno WiFi boards that are working all the time, all of them doing exactly the same stuff (just in different areas of our warehouse). Only two of them are sometimes switching to AP+STA mode in a different periods of time - sometimes once a week, sometimes more frequently. Other 3 devices are running without an issue.


text:
What am I missing? ST7735 TFT white screen
I followed this guy's guide with regards to wiring, etc., and all I seem to be getting is a white screen, as shown in these pictures. Is there an issue with the guy's guide, I'm missing or there is an issue with my wiring (pictures also included in above link) Any help would be appreciated.

the issue may well be that you haven't connected VCC and GND on the display to anything

The guide i was following suggested that "Connecting to VCC and ground like you’re accustomed to doing just won’t work here." ... that is not the case?

read comments in that guide

Oh look at that, "Thank you,
This worked for me only if I connected the VCC and Ground as well" and it indeed made it work. Sorry for the trouble.

TFT utterly temperamental anyway, i guess that's what you get for paying not much for it.


text:
Create New Serial Class Inheriting from Stream
How should I inherit from Stream, for creating a new class MySerial able to be initialized from a Stream0 instance?.
The error so far is: "cannot declare variable 'mySerial' to be of abstract type 'MySerial'".
If I make a class MySerial not inheriting, but adding a property Stream, everything works fine, except the new call mechanism for the resend() function, created to accept Stream instances.
EDIT: This is the edited code. Current error is: "expected unqualified-id before '=' token".
MySerial.h

class MySerial:public Stream{
    private:
        int param;
    public:
        MySerial(){}; // OK
        MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
        // Stream Implementation
        int available(){return available();}
        int read(){return read();}
        int peek(){return peek();}
        size_t write(uint8_t c){return write(c);}
        using Print::write;
};

MySerial.ino
#include <MySerial.h>
#include <SoftwareSerial.h>

SoftwareSerial swSerial(6,7);
MySerial mySerial(swSerial);

void setup(){}
void loop(){
    if (mySerial.available()){
        c=mySerial.read();
        resend(mySerial,c);
    }
}
// This function should accept any Stream: SoftwareSerial, MySerial, Serial...
void resend(Stream &Stream0, char c){
    Stream0.write(c);
}

The Stream class has pure virtual methods which must be implemented in derived not abstract class.
The pure virtual method from base class Print is:
virtual size_t write(uint8_t) = 0;

The pure virtual methods from Stream are:
virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;

additionally add in your class the line
using Print::write;

to pull in overloaded methods write(str) and write(buf, size) fromPrint
Here I have an example of a simple class derived from Stream.

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:
MySerial.h
#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_

#include <SoftwareSerial.h>

class MySerial: public SoftwareSerial {
private:
  int param;

public:

  MySerial(uint8_t receivePin, uint8_t transmitPin) :
      SoftwareSerial(receivePin, transmitPin, false) {
    param = 0;
  }

  void resend(char c) {
    write(c);
  }
};
#endif

MySerial.ino
#include "MySerial.h"

MySerial mySerial(6, 7);

void setup() {
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    int c = mySerial.read();
    mySerial.resend(c);
  }
}

Thanks. I made the indicated changes. I am still troubled with the constructor declaration, for taking a Stream object as initial object.

Your answers are great just as the last time. I will study this code further.


text:
Maximum Capacity Debugging
1. Example
Check the program below for an Arduino Nano, Old Bootloader, for variable values of N.

For low values (N<=1857), the program outputs "[FFFFFFFF]",
For higher values (1858<=N<=1953), the program outputs unpredictable variations of this string,
For higher values (1954<=N<=1955), the program outputs fails flooding the symbol "[",
Over a certain value (1956<=N), the programs does not output any character.

I didn't check extensively these results, which could be very different actually, and totally platform dependent, but I guess, reproducible.
Note that no dynamic allocation is being used.
Note that everything is initialized, first 4 values to 0xFF, next N-3 values to 0x00 (Ref.).
The compilation do not show any relevant alert, showing a modest 10% capacity usage.
Sketch uses 3206 bytes (10%) of program storage space. Maximum is 30720 bytes.
Global variables use 196 bytes (9%) of dynamic memory, leaving 1852 bytes for local variables. Maximum is 2048 bytes.

It is evident from this example how to figure the proper value of N, indeed a capacity related issue could be expected (Ref.).
Note these values are by far less than the "guess" value of N=32767 for 1 byte variables (?) (Ref.).
2. Problem
Now, with a considerably huge, real program, I am having the same issue regarding those unexpected results, so I am almost sure (few moments ago) than this is the cause.
When exceeding some "~maximum~" level, the program starts failing, and when "~releasing~" this capacity, the program starts working well (without those deleted functionality of course!).
3. Question
How should I debug, measure, dimension, or prevent this situation, and specify when it is the proper time to keep this processor, and when should I move into a bigger one, when clearly the compiler is not a reasonable guess?.

// CAPACITY TEST
#include <SoftwareSerial.h>

// SET THE PROPER N VALUE
// N<=1857: Last Valid Result
// 1858<=N<=1953: Last Observable Output - Single Char
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1954<=N<=1955: Last Observable Output - Flood
//     Invalid opcode 0xFFFF at PC=0xA402
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1956<=N: No Output
//     Invalid opcode 0xFFFF at PC=0xA402
#define N 1857

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

    byte a[N+1]={0xFF,0xFF,0xFF,0xFF};

    char si[3];
    Serial.print("[");
    for (int i1=0;i1<=N-1&&a[i1]!=0;i1++){
        sprintf(si,"%02X",a[i1]);
        Serial.print(si);
    }
    Serial.print("]");
}

void loop(){}

Your numbers are within the SRAM limit of an Arduino Nano (2K byte). There is a distinction between the AVR GCC language limit and the SRAM limit for a given board/MCU.

From the bottom to the top of the RAM, you have:

the .data section (statically allocated initialized variables)
the .bss section (statically allocated non initialized variables)
the heap (dynamic allocations with malloc() and new)
free space
the stack (return addresses and automatic local-variable allocations)

See the memories of an Arduino for a more lengthy
discussion.
The sizes of the .data and .bss sections are known at build time. This
is the “Global variables” memory usage reported at the end of the
compilation. The rest of the RAM is available for the heap and the
stack. This is the amount reported as “leaving 1852 bytes for local
variables”, where “local variables” is a slight oversimplification.
Your example program doesn't use heap allocation. It does use some
static allocation, mostly for the Serial buffers, and a lot of stack
for:

the return addresses from the calls to main() and setup() (4
bytes)
the local arrays a and si (N+4 bytes)
the memory needed by sprintf() or Serial.print() (unknown)

Even ignoring the last item, you can see that the whole RAM will be
consumed when 4 + N + 4 = 1852, i.e. N = 1844. As you make N larger than
this value, the stack bumps into the .bss section, and you start
corrupting your global variables. The behavior you describe is
consistent with the program corrupting the internal data structures of
the Serial object.

How should I debug, measure, dimension, or prevent this situation

There is no easy way to determine beforehand the amount of heap and
stack your program will consume. The usual solution is to measure and
report it at run time. See for example the MemoryFree library
(there are many similar to this).


text:
Fritzing PCB design review/questions
I've designed an PCB and due tot the delivery times, I kinda want to order it right now.
I don't yet have the components, so I haven't actually tried it on a breadboard.
Now I'm unsure if the PCB would work, as this also is my first try in PCB design.
It's a single-sided PCB.
All parts (should be) through hole.
I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).
[TL:DR] Would this PCB work?
Some points of which I'm unsure, or might be a problem:

Is the spacing of the board/lines to other components/side big enough?
Should I use a copper/ground fill? Which and why?
Are the rounded-off traces actually better as sharp edges?
It says: 36mm by 15mm isn't this too small to fit all those components?
Can I actually use the RESET pin as other functions (without changing fuse bits)?
Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Breadboard

Schematic

Layout

File
If someone needs the file:
It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects.
Download below:
https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0
Some credits to Nick Gammon, I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).
Version2!

Changes:
 - replaced the "V" shape.
 - pull-up on the reset pin.
 - decoupling capacitors
EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.

You could use the reset pin to make the chip reset. You can distinguish between resets and power-ups. So as long as your program doesn't require any variables to need to remain, you could add a button to the reset pin and make it do something. Or if it does you could use it to change some settings. E.g. changing baudrate.

@Gerben interesting idea, but I was looking to use the pin for UART. I think I'm going to use the MISO pin, since I don't have to receive data from the slave device. I might get one of those HVSP, since that way I can actually get full UART and full SPI. Which would be awesome for a RS485 to SPI converter.

Version 2 is flipped. Are the orange traces on the top or bottom layer. Having a mirrored board would be a problem. Though with through hole this can be fixed by soldering to components on the same side as the copper. But his a lot harder. Especially with header, where you have to temporary remove the plastic for soldering. Always double check this. I've made this mistake a few times.

@Gerben ah, yea, I switched to bottom view, I'll check it when I can. Thanks for the heads up :)

Would this PCB work?

Possibly, sometimes, under some conditions. See below.

Is the spacing of the board/lines to other components/side big enough?

Plenty.

Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again.  This blog post details how it is done.

Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete.  There are a couple of things missing that you need to add, and some that you might want to add.
The things that are missing:

Decoupling capacitors (100nF) on the power pins of both chips
You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
(Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.

Setting fuses can't be done with an USB-ISP?
And good catch on the termination resistors & decoupling capacitors.
In this case, one big capacitor on the power-in line wouldn't be enough? I'm not planning on using a switching circuit and the IC's don't have a big transient load? Is it more of a cherry on the top as a requirement?

Sharp edges can also be problematic in etching. Mostly a problem with home etching. But with the thickness of the traces and the spacing between them, it doesn't really matter if there is a bit more copper etched away in the corners.

@Paul Yes, you can set fuses with a low voltage ISP, but once you have disabled RESET you can no longer use the low voltage ISP since it relies on using the RESET functionality to enter program mode. So once you have done it you can't undo it without a HVSP to enter program mode through the secondary High Voltage method.

@Gerben Yes, right-angles can trap copper in their inner angle, but sometimes right-angles are the best you can hope for - for instance, always use T junctions; never join a trace to another at an acute angle or you get a nice place to trap cruft.

@Paul The large capacitor is to deal with larger power droops caused by low speed switching, such as the communication drivers. The small capacitors are there to deal with the high speed transients caused by the internal circuitry of the chips. They cover different frequency ranges, so they are both needed. The ATTiny especially. It is a switching circuit whether you like it or not - it has a clock and things inside switch on and off very fast.

@Majenko, ah that makes sense, I'm indeed planning on SPI which is some kind of switching. And it's better to learn it right :)

I've added V2 (v1.01) to the post (I just noticed I still miss the 10uF) but the termination resistor can be added in the pin header (along with the A/B RS485 pins), so this would be a better/working design? ;D

For a reservoir capacitor, does it matter if it's a tantalum or electrolytic capacitor?

Electrolytic is the norm.

Is the spacing of the board/lines to other components/side big enough?

Looks ok.  You might be able to squeeze it a few mm smaller each way, although since the board already is small, that probably would make little difference in cost.

Should I use a copper/ground fill? Which and why?

Copper/ground fill on a single-sided board won't make much difference for this circuit.  It would be reasonable, however, to make the ground traces two or three times as wide as they are.

Are the rounded-off traces actually better as sharp edges?

If you mean, make square corners rather than the 45° turns as shown, either way will make little difference for this circuit.  The 45° turns are ok.
Note, sharp V-notches, like the one inside the traces at pin 2 of the Tiny85, are undesirable; I think they etch less accurately than more-open junctions do.

It says: 36mm by 15mm isn't this too small to fit all those components?

Looks like there's room to spare and the board could be made slightly smaller.
For homemade boards that are drilled using a hand-cranked XY table, keeping drilled holes on the intersections of a .1"x.1" grid is a good idea.  For commercially-made boards, it's less important but can help with assembly.
Edit: Regarding “Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger?”, yes, both ground and power traces typically should be large, if board layout allows.  It's desirable that those traces have low inductance and it's ok to have high capacitance between ground and power traces.
Regarding how long it takes to get your PCB back from a manufacturer: The PCBshopper.com website makes it easy to compare time vs cost across a range of manufacturers.  For small circuits like yours, OSHpark is an inexpensive choice (you would get three double-sided boards for under $5, in about 15 days).  If you need up to about 10 medium-size boards, Maker Studio is quite economical but standard delivery may be slow (2-3 weeks).  If you are in a hurry and need a larger number of boards, consider (eg) PCBway.  By paying $25 for DHL shipping, you can have a batch of boards in 9 or 10 days – about three days for manufacture and a week for delivery.  The pictures below show an example of PCBway's order tracking, the left side at about two days after the order was placed, the right side 11 hours later.  This order for 50 each 36 mm x 56 mm two-layer boards with silk both sides cost $27 for manufacture and $25 for delivery.

Good catch on the V shape. The size question was quite silly, I can't yet imagine it to be 3,6cm long (which isn't a lot). Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger? (They're 24 mil, can't make them bigger in fritzing?)

@Paul, see edit

I went with OshPark since they've got a Gerber viewer built in (so I could re-check each layer). Pricing was around 5x better as Fritzing and will get some nice purple-colored boards, without shipping cost.
I now actually realize I don't have any programming headers or reverse current protection. But I guess I'll make it on a breadboard beforehand anyway, and take a good look when wiring.


text:
7-Segment Common Anode
I accidently bought a "Common Anode" 7-segment display instead of a "Common Cathode".
I understand that the polarity of the leds within the display is 'reversed'. So instead of putting the common pin on GND I have to put it to 5v (with current limiting resistor)
My questions on this are:

Can I still use only one current limiting resistor on the common pin? Instead of a resistor on every segment pin.
Can I use the pins from arduino to drive it (withouth pull-up/pull-down?) By making the signal LOW the current will flow from 5V common anode to the arduino and thus the segment wil light?
Can I still use a shift register to drive the segment led? (By inversing the outputs (in software))

Obviously I would like to have wiring more like this (but then I would ofcourse change  the GND line to a 5V line.

The wiring below is the worst-case wiring I can think of.

^ So can I avoid this, when using a Common Anode 7-segment display or am I forced to buy a Common Cathode 7-segment display?

Both thanks for the help and explanation!
I was able to test the segments :) (They arrived today)
They'll fit nicely in my "Alarm clock" project.
For further reference, be sure to read both answers, especially note that the maximal sink current for all the pins together is different as for each pin itself.

You can use a single resistor on the common pin if you want. The problem is that lighting up multiple segments at the same time will substantially reduce the brightness of each one. You could work around that by lighting each segment one at a time in very quick succession though.
It should be possible to control the display directly from the IO pins by setting them LOW. In this configuration, they will be sinking current (rather than sourcing it). It depends on the specification of the display and on what resistor you use though.
Basically, try to keep the current below 20mA and it should be OK (assuming you're using a standard 5V Arduino). For example, if each segment has a forward voltage drop of 2V, you would want to use a resistor of around 180 Ohm.
Controlling the display directly from a shift register is probably not possible, although once again it depends on its specification. Shift registers usually aren't designed to sink enough current so you'll need something like a transistor on each output.

So, if I find out how much current my shift register can sink, I have to use a resistor that limits the current to this level (taken into account my arduino is 5V). Though the brightness of the led's will be lower the less current flows through.
And by sourcing it, the only problem would be sourcing too much current to the LED's thus be safer for arduino/shift register than sinking it in most cases.
Basically I should buy "Common Cathode" next time :) (did check it on the RGB leds and 8x8 segment I bought though)

@FuaZe There will be a limit on how much current the Arduino or shift register pins can safely source too, so it's not necessarily any safer than sinking.

Peter R. Ah, ofcourse, I was thinking that sourcing too much will cause your LED to fail, but yeah, it's not safe to rely on that.

Sorry about the crudity of my image, but you don't always need those transistors. Peter has already said so, but I wanted to explain a bit further.

The only thing is that you need to set a pin to LOW to light up the led, and HIGH to turn it off. Just use a ! to make your code more intuitive if your like. So e.g. digitalWrite(segmentA, !HIGH)
Some limitations. A pin can sink up to 40mA (no problem here), but the total sink current for the digital pins 0 to 4 shouldn't exceed 100mA. The same goes for pins 5 to 13. And the same goes for the analog pins. So either limit the current through the leds to around 10mA, or make sure no more than 5 leds are lit at the same time, or connect half of the segments to on of the above mentioned groups, and the other half another (f.y.i. analog pins can be used just like digital pins).

Thanks for the heads up on the total sink limitation!
I didn't know that, what would go wrong if I sink more than 100mA?

Fry the input pin, fry the entire chip, unstable behavior, having less current going through the pins (dimmer leds), who knows. The ratings are conservative, so you're probably fine if you go a little over.

PS I prefer common anode displays. Easier to wire.

How's common anode easier to wire? The pic of my fritzing drawing is a common cathode, the only thing is that you have a GND and not a 5V?
And I think arduino can source more current than sink, so it should be safer for your arduino to source, or you'll have brighter segments?

Like I said above, you are going to hit the 100mA limit. Easiest way to solve this is by adding transistors. Having the transistors at the low side, sinking the current, means you can always use regular NPN transistors. Sourcing the current can be done with NPNs but only if you use the same voltage for the leds, as you do the arduino. Otherwise you'd need PNP which are a bit of a pain (to me at least). If you are just using resistors, there is no real difference. Source limit is 150mA, so that's a bit higher. PS see edit above.

PS group restrictions for sourcing current are different than sinking 1] The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA.
2] The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 150mA.

Peter and Gerben have already said what is needed , but I wish to explain things even further.
A normal small 7-Segment display consumes only 70-80mA when all segments are HIGH.So you can use the Arduino directly without damaging it. Also note, depending on the quality of the project, you could either use a common resistor for all segments, or use separate ones. Separate ones will give much brighter light and better quality.
A medium size one will require max consumption of around 400mA current, so use cheap transistors.
A large size one will require max consumption of upto 1.5-2A current , so use MOSFETS or other high current Transistors.
An Extra Large one will require max consumption of upto 10-25A current, so use good MOSFETS or maybe even Relays.
Usage
Small- Wrist watches
Medium- Small clocks
Large- Big clocks
Extra Large- Very big clocks like ones in Railway stations


text:
How to upload a sketch to Arduino if it goes to deep sleep mode quickly
I have created sketch where Arduino goes to powerdown mode in about 1s after boot. Now I can not upload other sketch, because programmer does not get proper response. I tried to hold reset and release it at various stages during compile/upload, but it does not help. I suspect the programmer needs to communicate with Arduino for several seconds. Any advice how to erase the sketch without programmer, or how to ban the sleep mode? It is Pro Mini 168. Thanks

Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.
If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.
Update:

Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. This article has more information.

Thanks for the response but I have tried to hold reset many times and Arduino never synchronized. I think it goes to sleep despite the data ready signal on programming interface. Would another Arduino overcome this problem? Sorry but I do not see any comments you refer to by "connect the two as described in the comments". Jan

Turn on Verbose output (Under File:preferences).
Press & hold the Reset button. After the compilation ends, you will see a message like:
"Compiled xxx of 32xxx bytes".
That's when the download starts - release reset.
It make take a few tries to get the timing of the release correct.
If you can't get the reset to take hold, then it's time to reburn the bootloader using a Programmer connected to the ICSP pins.