Inventory/Rack Management I am trying to make a project where each item in a rack has its fixed spot. When picked/misplaced from this spot a LED will glow indicating the item is missing from its place also time of pickup, item name and time of re-keeping are to be recorded.
The best possible hardware I can think of is Arduino UNO and RFID tagging each item and placing a RFID MFRC522 Scanner on each item's place but I'm not being able to scale it.
I mean I can't use many scanners.
I need your help regarding this project about how to use multiple RFID scanners and glowing an LED for each item picked(separate light for all items).
By items I mean -

Files/Folders
Cylindrical chemical bottles(like in a chemistry lab)
Books

Very interesting project. What to do depends largely on your exact requirements. I guess you have chosen RFID for its easy usage, when everything is set up (like just placing the item roughly at the right spot, instead of needing extra electrical plugs or similar).

I'm not being able to scale it

In a case like this you normally wouldn't use just one Arduino. I would use multiple Arduino Nanos (or similar), each interfacing only a few RFID readers. Then I would use a long range interface (like RS485) to let a master Arduino communicate with all other Arduinos. That way you can faciliate the RFID interfacing code to many Arduinos (which also gives you an easier method of scaling up). Arduino Nano clones are rather cheap (like about 2$ or less I think).

Now items per rack are about 30 that would be so daunting task to place 30 scanners on each rack

Placing 30 RFID moduls per rack is a big task, yes. But that is the price for such a system. If that is too much for you (either in work time or in money), you would need to think about different approaches than RFID. Each approach, that I can think of, will also give you some caveats.

You could use bar codes and bar code scanners on each place. That has a similar difficulty to the RFID approach.
You could give every item an electrical plug, that connects to a fitting socket  on the rack. The ID of the item could then be hold on the item plug by either a number of electrical connections (giving you a binary code) (many electrical lines needed) or by a single chip like an EEPROM (which was programmed with the item ID) (less lines needed).
You could give each item a unique strip with a color code and use multiple color sensors on each place in the rack to identify the item (it has to be put in at the exact correct orientation for reading the colors) (potentially many electrical lines due to multiple color sensors).

All these options are not really better than the RFID option. I would consider the plug with the EEPROM chip the best option from the RFID alternatives above, since these chips can be rather cheap. Though it will be a toll onto the work, that has be done for each item (assembling the plug with the EEPROM chip). Also the infrastructure with the extra Arduinos for every group of a few places in the rack is also needed here.
All in all the RFID option is rather good in comparison to the others. Its main caveat will be the cost, since the RFID reading pads are not very cheap.
Aside from those options, you could make bigger compromises. Big warehouses often have a system, where a worker caries a bar code reader and has to read the bar code of the item and of the rack space, where he will put it. The system can then know, where the item is and if that location is the correct one, and show that on a handheld. That will be way easier to implement, but takes a greater toll on your usability.

I've tried 4-5 RFID scanners with one Arduino uno watching a youtube tutorial and failed.

If you want help with that, you would need to describe, how exactly you failed. Please provide your code, a link to the youtube tutorial and links to any other resources, that you used. Include a detailed description about, what you expected and what actually happened. And put all this information into your question by editing it (not in the comments).
Also as a side note: I've had rather bad experiences with youtube tutorials. You might wanna search for a text based tutorial.


When to use PROGMEM? I believe PROGMEM is used to store large data (e.g. strings) that don't change. So it frees up the SRAM.

in the Ardunio Reference it is mentioned that.

"Using PROGMEM is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the pgmspace.h library, to read the data from program memory back into SRAM, so we can do something useful with it."

If I have to load the data into SRAM before using it then how is it efficient than directly stroing into SRAM by defining vaiable normally

Say you have a string of 1000 characters in Flash, and you want to print it to Serial.  Yes, you need to load it into RAM in order to pass that data around the place for printing. But, do you need to put all of it in RAM at once?  No.  You only need one character at a time.  So instead of taking 1000 characters and allocating 1000 bytes of RAM and copying the whole shebang into RAM then printing it, you just need to allocate 1 byte of RAM* and copy each character in turn and print it.

Since you can only read one character at a time from flash there's no advantage in reading the whole lot anyway.

*Actually, because of compiler optimizations, this probably never even touches RAM and just stays in a CPU register.


Timing taking longer than expected This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.

https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png
^ So you don't have to look it up yourselves. previousMillis is initialized to 0.

However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.

Factor 8 in timing smells like wrong fuses.

Perhaps you don't use an external oscillator, but the internal one?


Is there a way to power off external devices during deep sleep I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.

Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.

So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?

Thanks!

I made a temperature and humidity sensor which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.

The power-control part of the circuit is here:

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

The full schematic is:

I think I've changed the batteries once since making it in 2013.


Blink without delay for 5 times every 20 seconds I'm trying to write a blink without delay code that will wait 20 seconds, then blink 5 times, then wait another 20 seconds - rinse and repeat.

Here's the minimal code I wrote:

if (currentTime % 20000 == 0) {
  for (int x = 0; x <= 5; x++) {
    if (currentTime % 500 == 0) {
      if (solenoid == LOW) {
        solenoid = HIGH;
      }   else {
        solenoid = LOW;
      }
      digitalWrite(solenoidpin, solenoid);
    }
  }
}
}

All this seems to do is set solenoid to HIGH and keep it there. If I get rid of the for loop and the second if statement, I can get it to switch between low and high every 20 seconds, but adding the if and for loops seems to kill it. Any thoughts on how to make this work?

Here is a solution:

void setup()
{
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);
}

#define INTERVAL 20000L
#define BLINK_TIMES 5
void loop()
{
    static unsigned long lastBlink = 0;
    static int count = 0;

    unsigned long now = millis();

    if(count > 0) {
        count -= blink();
        lastBlink = now;
    } else {
        if(now - lastBlink >= INTERVAL) {
            count = BLINK_TIMES;
        }
    }
}

/*
 * Do one blink.
 * Return 1 when blink is done.
 */
int blink()
{
  static unsigned long lastFlip = 0;
  static int count = 0;
  bool last = false;

  unsigned long now = millis();

  if(now - lastFlip >= 500) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    Serial.print(now / 1000); Serial.print(". "); Serial.println("blink");
    lastFlip = now;
    count++;
    if (count == 2) {
      count = 0;
      last = true;
      }
   }

   return (last) ? 1 : 0 ;
}

The count variable controls when to blink and how many times. While it's zero, no blinking.

When not blinking, it keeps comparing actual time with the last time it blinked. When the time exceed 20s, it puts count to five, and in the next loop, the blinking start.

Variables are declared static so they keep their values between loop executions.


Is there any way to control current precisely with Arduino without using a DC-DC converter? I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?

The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.

You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).

If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.


Print connection password typed by user on NodeMCU Lua ESP8266 ESP-12E I want to make a WiFi Access point created with the ESP8266. Let's say that the SSID is 'net_work' and the password is '12345678'.

When a client tries to connect with a wrong password, I want to print that wrong password in the serial console. But nowhere in the docu I can find an event listener or something to do this... The only thing i can find in the docu is how to start the AP and wait for a successfull connection.

You can't.

The password does not exist.

In short:

The password is used to create a key
The key is used to encrypt the connection
If both ends agree on the encryption then it's "connected" and packets can travel back and forth.

There is no password for you to print, only the fact that encryption didn't agree.

It actuality it's more complex than that, but that's the rough outline of how it works.


Can I program for Arduino without having a real board? I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

There are a whole slew of Arduino simulators out there, many free, and some paid products as well.

The CodeBlocks Arduino development environment includes a free Arduino simulator, still under development but functional.
Simuino simulates the Arduino Uno and Mega pins - not a pretty-looking realistic simulator, but it works.
The Python based Arduino Simulator is another option, that plays well with the official IDE
Virtronics Simulator for Arduino looks promising, but I don't see why I would pay $14.99 for it, when I could buy one or more actual Arduino clones for that price

Many other Arduino simulators are out there if you search, and new ones are being announced, even crowdfunded, all the time.


MQTT broker and Arduino + Sensors NRF24L01 I am newbie, I have never used MQTT before, so I have some questions.
Here is my topology.

I have several sensors (Arduino Pro Mini + NRF24L01) and main server/handler(Arduino Mega + Ethernet Shield or ESP module) to receive/send messages to/from sensor nodes, so all network is build on NRF24L01 (NRF24 Mesh library). But I need to be able to communicate with all these sensors from outside over the internet. Previously I implemented simple socket communication.
I have recently discovered MQTT protocol and it is awesome. I want to implement communication between main server and outside world using it.

What part of my topology should implement broker in? I think it should be on the main server (Arduino Mega) but again communication between main server/master server is implemented via NRF24L01 modules and custom protocol.
Or in my case is better to use HTTP communication with master server?

Please explain this topic and suggest how to implement this correctly in my case.

The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.

A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.

Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.

Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.

Cheers!


Interfacing Aduino Nano and RDM8800 I'm attempting to use an Arduino Nano with the RDM8800 to read data from NFC tags. After soldering wires between the Nano and the RDM8800, I attempted to test these devices using code similar to what has been used successfully on other serial devices similar to the RDM8800. Below is the code I used to test.

Wiring:

Nano - RDM8800
--------------
 5V  -  5V
GND  -  GND
 D3  -  TX
 D2  -  RX

Tags Tested:

NTAG 216 (ISO14443A)
MiFare Classic 1k (ISO14443A)

Code:

#include <SoftwareSerial.h>

SoftwareSerial soft(2,3);

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

void loop() {
  if(soft.available() > 0) {
    String serialData = soft.readString();
    Serial.println(serialData);
    writeAck();
  }

}

void writeAck() {
  uint8_t payload[] = "ACK|0|\n";
  soft.write(payload, sizeof(payload));
}

I watched the serial monitor and attempted to scan two different NFC tags that matched the ISO14443A compatibility that should ship with the RDM8800, according to this article. I got no information returned on the serial monitor.

After, assuming the issue is with the firmware, I attempted to upload the firmware to the RDM8800, with no success. I installed the needed board support to the Arduino IDE, as outlined in the intro article. Not having a USB to serial tool, I used another Nano and simply bridged the connection between the GND and RST pins. I was unable to upload the firmware to the RDM8800, getting the error below each time I tried.

Error:

avrdude: stk500_recv(): programmer is not responding

I believe that it's possible that I can't upload the firmware to the RDM8800 because the setup I used with the Nano as the USB to serial tool lacked a reset button. The image in the intro article, says to connect the TX RX GND 5V and RST pins, but the image that it says shows this only shows the TX RX GND and 5V pins connected(See below).

Image:

The information that I've found on the RDM8800 and its use is very limited and so is my knowledge on this topic. I'm unsure how I should proceed right now. I believe that I'm taking the right approach to setup code to scan NFC tags, but I could be wrong there. I'm very unsure on what I'm doing in relation to the potential firmware issue. Overall, I'm simply unsure on how to proceed and I'm looking for more knowledgeable people to give me some advice on how to proceed.

Relevant Resources:
RDM8800 Itead Wiki Page
RDM8800 Data Sheet
RDM8800 Schematic
RDM8800 Introduction Article

SoftwareSerial constructor is rx pin first then tx pin.

You have SoftwareSerial soft(2,3); But you said that

D3 - TX
D2 - RX

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:

SoftwareSerial soft(3,2);


Arduino Micro vs. Pro Micro What are the differences between the Arduino Micro and Pro Micro?

I actually think you are meaning what is the difference between the Arduino Mini and the Arduino Pro Mini, since there is no such board as the Arduino Pro Micro. However there is a board called the Arduino Micro and also the Sparkfun Pro Micro, so this answer will look at all four.

Arduino Mini

Arduino Pro Mini

Arduino Micro

(Sparkfun) Pro Micro

Microcontroller
Arduino Mini: ATmega328
Arduino Pro Mini: ATmega328 (ATmega168 on older boards)
Arduino Micro: ATmega32U4
Pro Micro: ATmega32U4

Memory
All four have 32KB of Flash and 1KB of EEPROM
Both Minis have 2KB of SRAM where as both Micro boards have 2.5KB

Digital I/O
Both Minis have 14 (of which 6 provide PWM output)
The Arduino Micro has 14 also (of which 7 provide PWM output)
Some of the analog pins can also be used as digital I/O
The Pro Micro has 12 (5 PWM pins)

Analog Inputs
Arduino Mini/Pro Mini: 8 (some boards only break out 6 analog inputs)
Arduino Micro: 12 (6 dedicated and 6 from digital I/O pins)
Pro Micro: 9 channels of 10-bit ADC

USB
Arduino Mini/Pro Mini: Requires FTDI cable or Sparkfun breakout board to provide USB power and communication to the board.
Arduino Micro / Pro Micro: Native USB

Clock
All 16 MHz
(Some 3V3 variants run at 8MHz)

Power
Arduino Mini: 7-9 V
Arduino Pro Mini: There are two version of the Pro Mini. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz. VRAW  can accept voltage up to 12VDC.
Arduino Micro: USB or external supply of 6 to 20 volts (recommended range is 7 to 12 volts)
Pro Micro: can accept voltage up to 12VDC

Interrupts
Arduino Pro Mini: The Atmega328 has 2 hardware interrupts available
Arduino Micro / Pro Micro: The ATMega32u4 has 5 hardware interrupts available
credit: Enric Blanco


Daisy chaining of multiple blocs of 4x(8x8) MAX7219 matrix Thanks for your presentation https://arduino.stackexchange.com/tags/max7219/info.
You say that multiple MAX7219 8x8 blocs can easily be daisy-chained and you show an example of at least 12 blocs displaying "Testing12345".
Trying several programs I found for Arduino, I never succeeded to chain more than 8 blocs with 8x8 matrix (either 8 individual blocs or 2 groups of 4 as on your image).
So I'ld be very happy if you send me examples of programs managing more than 8 blocs for fixed or scrolling displays.
Many thanks in advance.

All is OK changing the proposed statement
define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW
to
define HARDWARE_TYPE MD_MAX72XX::FC16_HW


Determing approximate bicycle speed for distancemeter I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?

I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.

I used "arduino gps library" as the search terms and found many options. One of them, TinyGPS++ appears to have what you require and much more:

  TinyGPS++ is a new Arduino library for parsing NMEA data streams
  provided by GPS modules.

  Like its predecessor, TinyGPS, this library provides compact and
  easy-to-use methods for extracting position, date, time, altitude,
  speed, and course from consumer GPS devices.

  However, TinyGPS++’s programmer interface is considerably simpler to
  use than TinyGPS, and the new library can extract arbitrary data from
  any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.

There may be other libraries that provide your objective, this was the first on the search returns.

The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.


MFRC522 Communication Failure I'm using TTGO ESP32 and I've got an MFRC522 from AliExpress.
I've soldered connector pins to the board itself (both for ESP32 and MFRC522) and I'm using jumper wires female-to-female to connect themselves.
However, using an example sketch (DumpInfo) from miguelbalboa's RFID library, it says communication failure and scanning 3 different key cards or the key fob doesn't output anything.
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?

This is my current pinout scheme:
(MFRC - ESP32)
SDA (SS) -> 33
SCK -> 25
MISO -> 27
MOSI -> 26
RST -> 32

And, of course also GND to G and 3.3V to 3.3V.
I've also tried SDA and SCK to connect to 21 and 22, respectively but no luck.
Though I have a DS1307 RTC module and microSD card adapter module and connected accordingly and it's working fine, by using Dupont wires, with the same method.
A manufacturer's defect or still I'm making an error somewhere?
You can see TTGO's ESP32 pinout diagram and also a picture of MFRC522 here  wired using jumper wires. I may be using (again) the wrong pins. The red LED on the MFRC522 is stable, though.
Thank you in advance.

UPDATE!
The issue has been fixed, just after finding this stackoverflow answer by bat macumba. I'll leave the question here, in case someone stumbles into the same problem.


Using Arduino UNO as FTDI programmer for 9DOF Razor IMU I am trying to upload some code to the ATmega328 on Sparkfun's 9DOF Razor IMU. Because I don't have an FTDI board at hand I was trying to use my UNO by "grounding" the RESET pin. Communicating with the 9DOF works well (it has some sample firmware loaded):

So here's the problem:

When I try to program the ATmega328, the Arduino IDE gives e the following error:

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x0d

What am I doing wrong?

What you're missing is the signal that resets the ATMega so it can enter the bootloader.  That signal is the one that goes to the DTR pin of the 9DOF and would normally be sent to the reset pin on your Arduino (that you are grounding).

What you need to do is reset the 9DOF just as it's about to start trying to upload the code.  Timing is critical - you get about a second or so of leeway where the bootloader is actually available for avrdude to talk to.

Alternatively you can try and find a point on your Arduino board where the DTR signal from the USB interface chip is available before it passes through the capacitor to the RESET pin of the Arduino and take a wire from there (wherever that may be) to the DTR pin of the 9DOF.


Unable to receive SMS on Android I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:

<<Content not supported>>

I also tried sending it to a basic mobile. It displayed:

Content can't be displayed

I tried changing the encoding using the AT command.

AT+CSCS="UCS2"
AT+CSCS="GSM"

It didn't work for any encoding.

The command I use to send SMS is:

---> AT+CMGF=1
<--- OK
---> AT+CMGS="10 digit number"
<--- >
> Hello!
^Z

Can someone please tell me what is going wrong? Thank you in advance!

In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.

The AT commando that (perhaps) will work for you is the ATZ, in the SIM900 works for me.

You can look over here to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.

Hope you can find an answer.


Trying to understand bitbanging, shiftIn(), reading EEPROM Alright, so I have an Atmel 93C66, http://www.atmel.com/Images/doc0172Z.pdf Datasheet and I'm wanting to read whatever is in it.

I copied the following code from this thread http://forum.arduino.cc/index.php?topic=96411.0 and made some changes to it, mainly I deleted the part where it writes:

//difining pins for eeprom
int CLOCK =4;
int DATA_OUT =3;
int DATA_IN = 2;
int CHIP_SEL =5;

int low =0;     //low address

byte READ  = 0b1100;                //read instruction

void setup(){

  pinMode(CLOCK ,OUTPUT);
  pinMode(DATA_OUT ,OUTPUT);
  pinMode(DATA_IN ,INPUT);
  pinMode(CHIP_SEL ,OUTPUT);
  digitalWrite(CHIP_SEL ,LOW);
  digitalWrite(CLOCK, LOW);
  Serial.begin(9600);
}

void loop()
{

  for (int i=0;i<=511;i++)
  {
    digitalWrite(CHIP_SEL ,HIGH);
    shiftOut(DATA_OUT,CLOCK,MSBFIRST,READ); //sending READ instruction
    shiftOut(DATA_OUT,CLOCK,MSBFIRST,low);   //sending low address
    byte incoming = shiftIn(DATA_IN,CLOCK,MSBFIRST); //receiving data
    digitalWrite(CHIP_SEL ,LOW);

    Serial.print(low);
    Serial.print("/t");
    Serial.print(incoming, BIN);
    Serial.print("/t");
    Serial.print(incoming, HEX);
    Serial.println():

    low++;       //incrementing low address

  }
  while(1);
}

What I'm trying to understand is:

In the 93C66 datasheet page 5, table 6, it says that to read the contents of memory I need to send SB 1, OPCODE 10, and memory address, which I don't know exactly how to do, but I guess the chip wants a 110 (or a HIGH, HIGH, LOW signal) plus memory address (variable “low”=0). The SB and OP CODE are similar to the BYTE variable READ in the code above, but this variable has an extra 0 (1100). I tested the code with 110 and I get different incoming data. I also thought if BYTE is 8 bits then why not make the BYTE variable READ 11000000, but it changes the incoming data. So now I don't really know how exactly to send SB 1 and OP CODE 10. Need help with that.

Also, as you can see I'm printing the variable "low" and the variable "incoming" (in Binary and Hex) on one line, I thought it would be printing 1 bit per line, but it prints varying amounts of bits. Sometimes it would print 4 bits, 6 bits, or 8 bits, as in 1110, 11111111, 111100. I thought the line byte incoming = shiftIn(DATA_IN,CLOCK,MSBFIRST);
would get filled with 8 bits all the time, so when I Serial.print() it would have 8 bits, but it's not happening, why?

Also I thought the shifting in of the bits into the variable "incoming" occurs once in the for loop, or is there an inner loop in shiftIn()? I ask because I first made the for loop go for i=<4095, since there are 4096 bits in this EEPROM, but the increment of I doesn’t match the amount of bits I’m getting on each Serial.print() line.
i.e. I would get something like this:

1   10111111    BF

I thought it would be getting something like this. (I’m thinking the shiftIn() of the 1st bit at address 0 happens when i=0, then 2nd bits gets shiftIn() when i=1, and so forth)

1   1
2   1
3   0
4   1
Etc, etc

How is shiftIn() shiftinf in the bits into the BYTE variable?

Thanks and sorry if it’s so many questions.

OK I know this is a little late, but for other readers having the same problem, here's a sketch I wrote to read a 93c46 when I had to dump the EEPROM from a car radio. I've deliberately not included the EWEN instruction anywhere as the last thing I wanted to do was accidentally write to the EEPROM.

The key is the modified shiftOut routine which adds a parameter specifying how many bits you want to shift out.

To adapt sketch for other 93c packages, change the number of 16bit words at start of loop{} and number of address bits in 2nd call to myshiftOut.

If your package has an ORG pin, tie it to Vcc.

Hope this helps someone...

/*
Arduino Uno sketch to dump a 93c46 EEPROM in 16 bit mode.  Metalbanana 12/9/16, with thanks to raint.
Easily modified for other 93c series parts. Note many 93c46 from autos are 'rotated' pinout,
i.e. those with a T following part no. e.g. 'TEM8':

1=NC    8=ORG
2=Vcc   7=GND
3=CS    6=DO
4=SK    5=DI

so check pcb for Vcc and GND locations with a meter first! An Arduino ProtoShield is ideal to mount IC
as it has a SOIC pad (Note: you can't use the mini breadboard at same time as it covers one set of headers).
Standard shiftOut is not suitable as it sends 8 bits, our addresses are 6 bits,
instructions are 3 bits so sketch uses a modified shiftOut called myshiftOut.
*/

// define pins for eeprom
const int CHIP_SEL = 8;  // to CS
const int CLOCK = 9;     // to SK
const int DATA_IN = 10;  // to DO
const int DATA_OUT = 11; // to DI

const byte READ  = B110;                //read instruction

bool debug = 0;

void myshiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, byte val, uint8_t bits)
{
  for (int i = 0; i < bits; i++)  {
    if (bitOrder == LSBFIRST) {
      digitalWrite(dataPin, !!(val & (1 << i)));
      if (debug)Serial.print(!!(val & (1 << i)));
    }
    else
    {
      digitalWrite(dataPin, !!(val & (1 << (bits - 1 - i))));
      if (debug)Serial.print(!!(val & (1 << (bits - 1 - i))));
    }
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);
  }
}

void setup() {
  pinMode(CHIP_SEL, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA_OUT, OUTPUT);
  pinMode(DATA_IN, INPUT_PULLUP);

  Serial.begin(9600);
  Serial.println("\n\n");
}

void loop()
{
  for (int addr = 0; addr < 64; addr++) // 64 words for 93c46
  {
    // print address at start of each line
    if (addr % 8 == 0) {
      Serial.println();
      if (addr < 8) Serial.print("0");
      Serial.print(addr * 2, HEX);
      Serial.print(": ");
    }

    digitalWrite(CHIP_SEL, HIGH);
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, READ, 3); //send READ instruction
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, addr, 6); //send address, 6 bits for 93c46

    digitalWrite(CLOCK, LOW); // recommended in language reference
    byte incomingH = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive high byte
    byte incomingL = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive low byte

    // reverse byte order & print
    if (incomingL < 16) Serial.print("0");
    Serial.print(incomingL, HEX);
    Serial.print(" ");
    if (incomingH < 16) Serial.print("0");
    Serial.print(incomingH, HEX);
    Serial.print(" ");

    digitalWrite(CHIP_SEL, LOW);
  }

  while (1);
}


Transient and reverse current Does anyone know (1) how much transient current can be output from a pin and (2) how much (and how long) reverse current an output pin can take?  For instance, consider the following circuit (driven by a series of 10 ms pulses at 5V):

  o----------------
       |          |
       = 10µF    1k LOAD
       |          |
  o----------------

which would be a classical filtered (smoothed) PWM circuit.  When the pin goes to +5V, the capacitor would act like a short and allow very high current (assuming about 20 ohm impedance, maybe 250 mA) for a millisecond or so.  Similarly, when the voltage drops to 0V, the charged capacitor will discharge, leading to a reverse current until it bleeds through the load.  Will either of these damage the diodes in the pin or even the IC?  Thanks.  (Worse comes to worse, does this mean that a resistor and diode are needed to protect the pin?)

More info

1)  It's 10µF.  10 pF would be useless in a power supply, it would only store 0.05 µC of electricity at most, which would only be able to smooth the output for a few microseconds.

2)  The load is resistance, 1 k ohms.

3)  A diode would be handy if you wanted to prevent reverse current, since you could put a much larger diode outside than the protective diodes in the Arduino.  They are classically used with motors (inductive load) as a clamp diode.

4)  My general question is about high transient current or reverse currents.  A capacitor is just an example of a situation that could cause this.  Another example would be a pin that is putting out only occasional (for example) 1ms long 100 mA pulses, separated by many seconds.  Such a circuit is really not delivering much power, but for very short periods it exceeds that recommended 40 mA.  Would this burn out the pin or not?

5)  A capacitor in parallel with the load is pretty much the classic filtered DC power supply.  Open any wall wart you have and you'll see a transformer, a rectifier and several large (electrolytic) capacitors (along with a couple small ones) and a voltage regulator.  Closer to this example, say you want to deliver current at 2 volts DC.  You can do this by alternating 2 ms pulses (at 5V) with 3 ms at 0V.  Then have a capacitor in series to smooth it to closer to DC, making it more like analog output.  That is, in fact, exactly how adjustable power supplies often work.

It sounds like you are trying to make a digital to analog converter driving some type of load.  Look at this link: http://emesystems.com/BS2PWM.htm
It will give you a start. Please note they use an opamp as a buffer.

This 'buffer' has a very high input impedance and a low output impedance.  It can drive from a few mills to over an amp depending on the opamp chosen.  Additional circuitry can get you into thousands of amps if desired.  The schematic is a 2 pole filter originally designed for the Stamp microcontroller.

The filter soothes it out but adds a delay on the final output value (settling time).  The greater the filter capactance the lower the ripple and the slower the response.  You can add another pole to filter if you want.

As a bit of information from an old semiconductor guy absolute ratings are just that.  If you exceed them even for a few nanoseconds you can be sure you damaged the device, you just do not know when it will fail.

I have seen a lot of microcontrollers damaged because of capacitors connected to the pins, power excluded, doesn't matter if the pin is input or output.  When the power supply collapses it will inject current into the microprocessor substrate possibly damaging it.

Good Luck


For loop not running I've been trying to get a for loop to run 9 times using the below code but can't get the loop to run.

void output() {
  int r;
  r = 1;
  Serial.println("Output");
  digitalWrite(Latch, LOW);
  for (int r=1; r >= 9;  r = r + 1) {
    Serial.println("Test");
    digitalWrite(DataOutput, Q[r]);
    digitalWrite(ClockPin, HIGH);
    digitalWrite(ClockPin, LOW);
  }
  Serial.println("Done For");
  digitalWrite(Latch, HIGH);
  digitalWrite(Latch, LOW);
}

Change

for (int r=1; r >= 9;  r = r + 1) {

to

for (int r=1; r <= 9;  r = r + 1) {

The for loop will only run while the second part is true.


LCD displaying weird text I am doing a project that requires input from a keypad to be displayed on the LCD display.

lcd.print() displays in proper form, but when the I press characters on the keypad, they are overwritten as weird symbols.

Any help would be appreciated.

Here's the code:

void setup()
{
  Serial.begin(9600);
  Serial.println("LCD test with PWM contrast adjustment");
  pinMode(13,OUTPUT);
  analogWrite(6,Contrast);

  lcd.begin(16,2);

  pinMode(buzzer, OUTPUT);
  lcd.print(" Electronic ");
  Serial.print(" Electronic ");
  lcd.setCursor(0,1);
  lcd.print(" Keypad Lock ");
  Serial.print(" Keypad Lock ");
  delay(2000);
  lcd.clear();
  lcd.print("Enter Ur Passkey:");
  Serial.println("Enter Ur Passkey:");
  lcd.setCursor(1,0);
  for(int j=0;j<4;j++)
    EEPROM.write(j, j+49);
  for(int j=0;j<4;j++)
    pass[j]=EEPROM.read(j);
}

stick to one type of variable, to prevent mix-up

So if you stick to a byte (uint8_t) type for keypad:

uint8_t keys[4][3] = {
  {1,2,3},
  {4,5,6},
  {7,8,9},
  {0xF,0xA,0xB}                 // F-*  B-#
}

then you can save it to your EEPROM as a byte and read it as a byte.it will prevent mix-up.
your code which you are not displaying (everybody here can write one of those faster then to download it from here)already translate numbers to numbers and then you are growing them to symbols with higher value


Can removing lines of code destroy a motor driver and make it catch fire? I am making a pid line follower robot. So I was tinkering with code to optimize my line follower when i removed two lines of code unknowingly. As soon as I uploaded my code and started the line follower, 4 mosfets on my motor driver smoked and burst into blue flames. Bought a new one and same outcome. Interestingly, The ones corresponding to the left motor alone had this outcome as I removed " return Motorspeed1" and " return MotorSpeed2" from the function corresponding to the left motor. Heres the code :

signed int MotorSpeed = 70;
int MotorSpeed1, MotorSpeed2;
int MotorFunc(signed int a, signed int b){
   if(a >= -10 && a < 0)
   {
      b = -b;
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, LOW);
      MotorSpeed1 = MotorSpeed + b;
      MotorSpeed2 = MotorSpeed + b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed2 = constrain(MotorSpeed2, 0, 255);
      analogWrite(_pwm_m1, MotorSpeed1);
      analogWrite(_pwm_m1, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }
   if (a < 10 && a > 0)
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, LOW);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2= MotorSpeed+ b;
      MotorSpeed1 = constrain( MotorSpeed1, 0, 255);
      MotorSpeed2= constrain( MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1,  MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

   else
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2 = MotorSpeed - b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed1 = constrain(MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1, MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

}

And i called this function in the code using :

    MotorFunc(a,b)

This code ran just fine, But when i removed the return functions from the first if condition, I destroyed 2 motordrivers,
Is this possible?
Edit:
I am updating the whole code:

The main code tab :

     int _dir_m1 = 2;
     int _pwm_m1 = 3;
     int _brk_m1 = 4;
     int _brk_m2 = 5;
     int _pwm_m2 = 6;
     int _dir_m2 = 7;

     int sen1 = A4;
     int sen2 = A3;
     int sen3 = A2;
     int sen4 = A1;
     int sen5 = A0;
     signed int Error = 0;

     int Kp = 20;
     int Ki = 0;
     int Kd = 0;

     void setup() {
     pinMode(_dir_m1, OUTPUT);
     pinMode(_pwm_m1, OUTPUT);
     pinMode(_brk_m1, OUTPUT);
     pinMode(_dir_m2, OUTPUT);
     pinMode(_pwm_m2, OUTPUT);
     pinMode(_brk_m2, OUTPUT);

     pinMode(sen1, INPUT);
     pinMode(sen2, INPUT);
     pinMode(sen3, INPUT);
     pinMode(sen4, INPUT);
     pinMode(sen5, INPUT);

     }

     void loop(){

     signed int a = Sensors();
     signed int b = PID(a);
     MotorFunc(a,b);
       }

And pretty much it. I am leaving out PID as Its not required along with error selection.

The setup is -
Arduino mega connected to 5 ir sensors
12v 9ah battery
500rpm 12v motors johnsons
and the motor driver 20 amp 20v-30v

Motor driver link with specs

It all depends on how the circuit works and how it is controlled.  A basic H-bridge looks like this:

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".

However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.


Differential steering drive equation I'm trying to control an Arduino-powered motorized toy with a differential drive. However, I want to code it the motor movements with a direction vector.

e.g.

(1,0) = forward
(-1,0) = backward
(0,1) = turn left, pivoting on center axis
(0,-1) = turn right, pivoting on center axis
(1,1) = forward-left, pivoting on left wheel
(1,-1) = forward-left, pivoting on right wheel

I thought the equation to convert these to the literal motor signals was:

float mag = sqrt(dirX*dirX + dirY*dirY);
float left = dirX - dirY;
float right = dirX + dirY;

This seems to work for the first 4 cases, but fails for the last two, where it results in an un-normalized vector.

One potential fix would be to simple wrap left and right in min() to stop it from going over 1.0, but that feels like a hack, and would possibly lose resolution. Is there a more elegant fix?

If you want to take it to to the extreme, I always use an algorithm called Diamond Coordinates. It is described in this PDF.  It performs perfectly, and I keep a C# and Java implementation handy. I'll probably be doing a Python one soon :)


Change global variables How can I change global variables as come EEPROM data? I should write codes in loop. But i dont know anything about changing global variable. Have you an idea?

For most purposes, a global variable is no different than any other variable. For example:

int var1;

void setup()
{
    int var2;

    var1 = 123; // global
    var2 = 123; // local
}

You can assign to global and local variables in the same way.

The only difference is that you need to be careful if you're using a global variable in an interrupt. You may need to declare it as volatile for it to behave correctly elsewhere in your code. If you don't know about interrupts then you probably don't need to worry about that though.


Are any Arduino boards especially suited for low-power operation? The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.

Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation?  Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator.
But if you don't need so much I/O you can go with a digispark Attiny board.


Time Stamping data on an Arduino and reading it on a Java IDE Does anyone have an idea on the best way to time stamp an arduino sketch that contains a data packet which is to be read out using a java IDE (IntelliJ) for graphic visualization of the packet. I tried declaring the time variable on the arduino section but having problem unpacking the unsigned long variable in java. Below is a snippet of the arduino code.

             unsigned long codeTime = 0; //The time the sketch takes to execute
         static unsigned long char dataArray [1]; // a variable to hold both sensor data

         void setup(){
              Serial.begin(9600);
              Serial1.begin(9600);
          }
         void state1(){
             if (Serial1.available()){
                    while (Serial1.available() > 0){
                 codeTime = millis(); //using the millis() instead of micros()
                 //memcpy should copy the whole data into position 0 ????
                 memcpy(&dataArray[0], &codeTime,sizeof(codeTime));
                 uint16_t newByte1 = Serial1.read(); // read in the first byte
                 uint16_t newByte2 = Serial1.read(); //read in the second byte
                 uint16_t dataByte = newByte2 >> 8;
                 dataByte = (dataByte | newByte1);
                 dataArray[1] = dataByte;
                 Serial1.write((uint16_t*)dataArray, sizeOf(dataArray));
                 }
               }
              }

            void loop(){
                   state1();
                   Serial1.flush();  //clear the serial port
                   delay(100);
                }

The question now is how do i unpack the data in java to ensure that the time variable (unsigned long time variable is well unpacked in the correct order)????. The second variable i could easily unpack in java as

              int variable1 = variable2 >> 8; //as it is a 16 bit integer I shifted
                                              // the msb/lsb accordingly
              variable1 = (variable1 | variable2);  // and finally casting it.

There's a number of fundamentally wrong things in your sketch.

static char buffer[1]; // a variable to hold both sensor data

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.

buffer[1] = newByte;

No. There is no buffer[1]. You count slices from 0.  buffer[0] exists (the first one) but buffer[1] doesn't.

buffer[0] = millis;

You aren't calling the function, you are assigning the address of the function. And worse than that, buffer is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an unsigned long which is 4 bytes in size.

You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.


Turning all 35 leds on sequentially with MM5451 I've been struggling for a long time trying to get the MM5451 chip to light up all 35 leds sequentially without any luck.  I've had intermittent help from the arduino forum, someone on youtube, and even found source code on here.  But all I've been able to accomplish is either to get all the lights lit up at once, or every other led lit up at once, or having two sets of 8 leds lighting up sequentially together.  I can't figure out how to get all of them lit on and off sequentially.  I'm sure it has to do with shifting bits but can't figure out how to do this.  Here's two sets of code that either light two sets of 8 bits together sequentially, and another program that lights every other led all at once.

Sequential lighting of two sets of 8 bits

#define CLK 2 // to MM5451 pin 21
#define dataBit  3 // to MM5451 pin 22

 byte singleled[]=  {1,2,4,8,16,32,64,128};
//   0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

  byte singleled2[]=  {1,2,4,8,16,32,64,128};
 //  0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

void setup() {
  pinMode(CLK, OUTPUT);
  pinMode(dataBit, OUTPUT);
  digitalWrite(CLK, 0);
  digitalWrite(dataBit, 0);
  Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop() {

  for (int i=0; i<8; i++)   {
        // start bit
    digitalWrite(dataBit, 1);
    pulseCLK();
    // the "+ 0x80" turns on DP
    ssrWriteLSB(singleled2 [i]); // MOD myCount = 0-9
    ssrWriteMSB (singleled [i]); // eight LEDs binary count 0-255
      delay(500);
   // ssrWriteMSB(myCount);
    //Serial.println(myCount);
    delay(500);
   // Serial.println(myCount);
    zeroWrite(29); // pad remaining bits with 0s
    delay(500);
  }

} // end loop

void pulseCLK()   {
  digitalWrite(CLK, 1);
  digitalWrite(CLK, 0);
}

// LSB out first!
void ssrWriteLSB(byte value)   {
  Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x01;
    if (temp == 0x01)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
   value = value >> 0x01; // shift right
  }
}

// MSB out first!
void ssrWriteMSB(byte value)   {
 Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x80;
    if (temp == 0x80)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
    value = value << 0x01; // shift left
  }
}

void  zeroWrite(byte num1)   {
  digitalWrite(dataBit, 0); // data bit LOW
  for(int x = 0; x < num1; x++) pulseCLK();
}

Turns on every other light all at once:

#define dataBit 3
#define clk 2

void setup()  {
  Serial.begin(1200);
  pinMode(dataBit, OUTPUT);
  pinMode(clk, OUTPUT);
  digitalWrite(dataBit, 0);
  digitalWrite(clk, 0);
}

 void loop() {
     //digitalWrite(dataBit,1);
     for(int index=0; index < 36; index++)  {
          digitalWrite(dataBit,1);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
          digitalWrite(dataBit,0);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
      }
  }

Thanks in advance.

Bryan

I think you need something like this.

#define CLK 2 // to MM5451 pin 21
#define DATA  3 // to MM5451 pin 22

void setup()
{
    pinMode(CLK, OUTPUT);
    pinMode(DATA, OUTPUT);
    digitalWrite(CLK, 0);
    digitalWrite(DATA, 0);
    Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop()
{
    for( byte led=0; led<35; led++ )
    {

        lightLed(led);

        delay(1000);
    }
}

void lightLed(byte index)
{
    //always send a one first
    sendOne();
    // turn off all leds preceding index
    for( byte i=0; i<index; i++ )
        sendZero();
    // one led on
    sendOne();
    // pad with leds off
    for( byte i=index+1; i<35; i++ )
        sendZero();
}

void sendOne()
{
    digitalWrite(DATA, HIGH);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}
void sendZero()
{
    digitalWrite(DATA, LOW);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}


Bridging the wifi networks on nodemcu: how to set the esp8266 as wifi extender, simplest case It seems to me that humidity is getting high in one room in the basement in my house. To monitor the situation temporarily, I would like to build a very small wifi-mesh network to exchange these humidity data to a locally installed raspberry pie server. Most of the time the networking would be in idle state, every some 5 minutes sending the humidity sensor data over mqtt to the server.

What is the simplest code that sets up an esp8266 to connect to an existing wifi network and act as an access point and wifi extender a couple of yards further?

I tried this code:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SSID_Internet";
const char* password = "qaz12345";

const char* newssid = "SSID_Extender";
const char* newpassword = "qaz12345";

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

  // set both access point and station
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAP(newssid, newpassword);

  Serial.print(newssid);
  Serial.print(" server ip: ");
  Serial.println(WiFi.softAPIP());

  WiFi.begin(ssid, password);
  int wifi_it = 0;
  int wifi_status;
  while ((wifi_status = WiFi.status()) != WL_CONNECTED) {
    Serial.println("Trying to connect to wifi");

    wifi_it++;
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  long rssi = WiFi.RSSI();
  Serial.print("Signal strength: ");
  Serial.print(rssi);
  Serial.println("dBm");
}

void loop(void){

}

It successfully registers the esp8266 to the wifi, sets up an AP, but if I connect to SID_Extender with my mobile phone, the internet traffic is not forwarded further.

There are projects that allows to configure multiple esps in user friendly manner, but I am wondering how to setup such an esp myself.

The esp8266 will not bridge the networks. You can perhaps bridge the communication from your other ep8266 on the TCP level with WiFiServer and WiFiClient. Send the sensor value to middle esp8266 running AP and it sends the value to Raspberry.

With MQTT you could create some MQTT proxy. Receive the data with WiFiServer and forward it with WiFiClient. without parsing or anything, only copying the chars between servers client and local client in booth directions

something like this (not tested):

void loop() {

  if (!serverClient || !serverClient.connected()) {
    serverClient = server.available();
  }
  if (!serverClient || !serverClient.connected()) {
    if (client.connected()) {
      client.stop();
    }
    return;
  }

  if (!client || !client.connected()) {
    if (!client.connect(raspiIP, MQTT_PORT)) {
      Serial.println("Can't connect to MQTT");
      delay(1000);
      return;
    }
  }

  while (serverClient.available() > 0) {
    client.write(serverClient.read());
  }
  while (client.available() > 0) {
    serverClient.write(client.read());
  }
}


How to write makefile-compatible sketches? I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.

I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?

Update 1

Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.

The official(?) makefile available here explains what to do if using the makefile instead of the IDE:

# The Arduino environment does preliminary processing on a sketch before
# compiling it.  If you're using this makefile instead, you'll need to do
# a few things differently:
#
#   - Give your program's file a .cpp extension (e.g. foo.cpp).
#
#   - Put this line at top of your code: #include <WProgram.h>
#
#   - Write prototypes for all your functions (or define them before you
#     call them).  A prototype declares the types of parameters a
#     function will take and what type of value it will return.  This
#     means that you can have a call to a function before the definition
#     of the function.  A function prototype looks like the first line of
#     the function, with a semi-colon at the end.  For example:
#     int digitalRead(int pin);

...but this doesn't explain how use both the IDE and a makefile.

Update 2

I recently found PlatformIO which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach.  Good support from the authors as well.

By gcc/g++ I think you're referring specifically to avr-gcc/avr-g++.  Your arduino code probably won't be considered valid C/C++ code because gcc will try to compile with your PC as the target system. Many of the Macros in "WProgram.h" will refer to inaccessible memory on your target system.

Providing you include the header file "WProgram.h" and you build your code with the Arduino Makefile above (which uses avr-g++ not g++), your cpp files should compile and link correctly.  Likewise, you will be able to open your Arduino code within the IDE and Verify your code there.  The IDE puts in the "WProgram.h" file for you, so technically it would be included twice.  However, the include guards will prevent any duplicate code from being compiled.


do digital input pins act as a positive or negative I've gotten contradicting information on the subject.  Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH.  On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V).  which one is it?

Digital pins sink or source current. They don't provide negative voltages. If the pin is set to INPUT then it is high impedance and will not "send out positive voltage".

However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.


Is every Arduino comes with onboard compass? The doubt was came in mind after seeing Arduino documentation. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?

No current Arduino board comes with an on-board compass. That function description comes from the documentation for the Arduino Robot, which is a retired product.

There may be other "maker" dev boards, such as the Adafruit Circuit Playground Express which have on-board compass peripherals.


Changing type of one variable dramatically changes compile size I have a sketch containing the following method:

// Writes zeros to the complete screen clearing it:
void clearScreen(uint8_t val) {
  setDrawArea(0x00, 0x7f, 0x00, 0x07); // complete screen
  SSD1306.ssd1306_send_data_start();
  for (int c = 0; c < 128 * 8; c++) {
    SSD1306.ssd1306_send_byte(val);
  }
  SSD1306.ssd1306_send_data_stop();
}

The whole sketch compiles with a size of 6730 Bytes. While refactoring the code I mistakenly changed "c" to uint8_t. After this I compiled to 4124 Bytes. Does this come from the compiler recognizing that the loop condition will never be reached and cut off all code behind or is this some kind of strange optimization event? I'm asking because I can't test the sketch in the moment.

Without being able to proof it (since I don't have your libraries and you gave only a small part of the sketch), I think this is what happens:

user3629249 is half right. If you change c to type uint8_t it only has 8 bits (hence the Name), so its maximum value will be 255. When you add 1 to it at this value, the variable will overflow and going back to 0. Thats normal overflow behavior, like used with the Arduinos Timer registers. (No undefined behavior there) So the maximum value c can reach is 255.

When compared to a bigger literal the value of c gets promoted to the correct type, so that the two values can be compared. But a variable that is at maximum 255 is always lower than 128*8. So you have an infinite loop there. The compiler can see this and doesn't include the functions from the rest of clearScreen(), since that is unreachable code.

All in all your code won't work as intended with uint8_t. You need a bigger type, that can hold the full range, that you operate. And this optimization is not strange, but very reasonable, since you really don't need the rest of clearScreen() in that case.


Arduino L led glows continuously can someone tell me why my L led on arduino uno glowing continuously I tried restarting my pc, changing USB port
I also tried uploading an empty file and resetting the  Arduino board but nothing seems to work. Does it mean I have to buy a new one?

Don't let that pin float undefined: If undefined (INPUT), pull it to GND to have the led OFF.

If ever possible, try to use the LED_BUILTIN pin as an OUTPUT pin.

And signal some information there. On an UNO (or other 328-based Arduino), this hint might collide with the SPI_SCK pin, which is D13 (PB5 on an atmega328). But as an SPI Master, this pin is at least OUTPUT (and thus will signal SPI activity).


Flashing ATmega8U2 using another Arduino I have an Anduino Uno R1 and the ATmega8U2 on. It does not respond correctly. How can I use another Arduino Uno R3 in order to reinstall the correct firmware? What I want to avoid it to solder the resistor because I am not very good with the soldering iron.

As fas as I understand there are some pins close to the AREF pin that can be used in order to attach a programmer. Also how can I temporally attach them without the need of a soldering iron? On the R1 the pins are just some exposed metal. How can I connect to them?

Also, if I load into the other Arduino the programmer, then how can I load the firmware using GNU/Linux into the ATmega8U2?

There is an official guide. Arduino as ISP and Arduino Bootloaders

But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.


Simulation of Arduino Mega 2560 with GSM Module using Proteus I have really been suffering with my simulation! Tried connecting my arduino mega 2560 to COMPIM (used as GSM Module) in my circuit and also loaded sample code but damn! In vain! I wanted to view the data sent in virtual terminal but am getting nothing! and its also complaining of excessive CPU usage.

This is the circuit as seen below in Proteus.

And thereafter, the log messages are displayed as shown below.

Someone please help me out. Am I making a mistake oh? Infact the arduino code for displaying in the simulation is also giving me hard time. The one am using is as shown below.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    mySerial.println("Hello, world?");
  if (Serial.available())
    mySerial.println("Hello, world?");
}

Will b every grateful for any help offered.

You should download this GSM Library for Proteus . You can use this library to simulate your GSM module in Proteus software. You should also check this example where they have discussed Hoe to Send SMS with GSM module in Proteus ISIS. I hope it will help you out.

Thanks.


Question regarding powering Arduino through the USB Port If powering the Arduino (Mega) through the USB port, is a voltage of 5.19VDC acceptable?

Yes, the ATMEGA328 processor will work without any problem, in fact if you go in the power informations section on the datasheet, you will find that the processor can run from a little less of 3V to a maximum of 5.5V.

Just be careful, because the processor works at that power, but the board will need from 5 to 5.5V.


Powering an esp32cam by a battery I have an esp32cam that I've programmed and powered via an FTDI connected to a computer's USB. Now that this stage is over, I'd like to run it portably, using some sort of battery.
The esp32cam has a 5V input (also a 3.3V input which word is should be avoided because it causes brownout). I'm wondering if it's possible to power it (for a short period) using a 7.3V, 9V or 12.3V battery. All the datasheets I've seen seem to specify the input range is 5V, but, for the esp32 (non-cam version), unregulated 5V-12V seems to permissible. Is this true for the esp32cam? Also, what is the right way to search for this?

The official ESP32-CAM has a AMS1117 voltage regulator that creates the 3.3V for the ESP.
The AMS1117 has an Absolute Maximum Input Voltage of 15V. It has a Dropout Voltage of 1.1-1.3V.
So you should stay above 4.6V to be on the safe side.
Since it's a linear voltage regulator, using a higher voltage battery has no advantage, as the "excess voltage" is converted to heat. It could even damage the regulator if too much heat is created.
You should pick the battery with the lowest voltage that still produces 4.6V when almost empty. So you could use the 7.3V battery you indicated. I'm assuming this is a 2-cell Li-ion battery, that has a voltage of 8.4V when full, and around 6V when empty. Which nicely fits your requirements.


Unusual use of << operator... not a bit shift? Poking through the example code of SDFS, I saw the following:

static ArduinoOutStream cout(Serial);
// F stores strings in flash to save RAM
cout << F("\ntype any character to start\n");

What exactly is << doing in this case? Moreover, F seems to never be defined prior to this. This seems like a useful trick, but I don't understand how it works.

full code available here: https://github.com/greiman/SdFs/blob/master/examples/SdInfo/SdInfo.ino

What exactly is << doing in this case?

It's directing the data into an output device (stream).

http://www.cplusplus.com/doc/tutorial/basic_io/

Yes, it's confusing using the same symbols for more than one thing...

  Moreover, F seems to never be defined prior to this.

F() is a macro. It's defined by the Arduino core in WString.h:

#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))


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

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

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

The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).

I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source BOSSA.  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.


Toggling a blinking led ON & OFF I am trying to implement a toggle switch to turn blinking ON & OFF. However, the code only turns the led ON or OFF and that too unreliably. Can you help me understand why it isn't working?

   const int redLed = 10;
const int buttonPin = 2;
unsigned long newTime;
unsigned long oldTime = 0;
byte newButtonState;
byte oldButtonState = 0;
boolean ledState = false;
boolean blinkState = false;
boolean state = LOW;

void setup() {
  pinMode(redLed, OUTPUT);
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {

  newButtonState = digitalRead(buttonPin);
  delay(100);

  // check if button state has changed
  if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
      // check led state
      if (ledState == false) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }
      if (ledState == true && blinkState == true) {
        newTime = millis();
        if (newTime - oldTime >= 250) {
          state = !state;
          oldTime = newTime;
        }
        digitalWrite(redLed, state);
      }
    }
  }
  oldButtonState = newButtonState;
}

Note, this is not an answer, but I want to show some code examples based on the comment:

You can use as said in the comment:

Remove '== true' in a boolean condition
Replace '== false' by '!' in a boolean condition

You will get this:

  // check if button state has changed
  if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
      // check led state
      if (!ledState) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }
      if (ledState && blinkState) {
        newTime = millis();
        if (newTime - oldTime >= 250) {
          state = !state;
          oldTime = newTime;
        }
        digitalWrite(redLed, state);
      }
    }
  }
  oldButtonState = newButtonState;
}

About the following fragment:

  if (!ledState) {
    ledState = true;
    blinkState = true;
  } else {
    ledState = false;
    blinkState = false;
  }

Since you write ledState and blinkState in both clauses, and the condition is simple (so you don't need to put it in a temporary variable, you can replace this fragment by:

blinkState = !ledState;
ledState = !ledState;

Note you have to reverse the order as blinkState depends on ledState.


Arduino Uno Wunderground weather station - Ethernet connection failed I'm new to Arduino. For my first project, I've decided to build a weather station where data is collected via sensors and is then sent to Wunderground. I'm using an arduino uno, an ethernet shield as well as a DHT22 sensor for temperature and humidity.

Everything worked for an hour and then I'm getting "connection Failed" constantly.

I would really appreciate it if you could look into my code. I've tried everything and it doesn't explain the sudden failure of the project. I occasionally get a successful upload after dozens of connection failed messages.

Here's my code. I've removed my weather station password for security reasons.

#include <Wire.h>
#include <SPI.h>
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "DHT.h"

// Sensor Pins
#define DHTPIN 7
#define DHTTYPE DHT22
// Variables
float temp;
float hum;

byte mac[] = {
  "de,ad,be,ef,fe,ed"
};
EthernetClient ethernetClient;
unsigned int localPort = 8888;
// Wunderground server details
char SERVER[] = "rtupdate.wunderground.com";
char WEBPAGE[] = "GET /weatherstation/updateweatherstation.php?";
char ID[] = "ICHESTER24";
char PASSWORD[] = "iwqnrlex";

DHT dht(DHTPIN, DHTTYPE);
unsigned int connections = 1;
unsigned int timeout = 30000;

void setup(void) {
  Serial.begin(38400);
  Wire.begin();
  dht.begin();

  // Connect to internet
  Serial.print(F("\nInitialising Ethernet module"));
  if (Ethernet.begin(mac)){

    Serial.println("Initialisation completed successfully!");
  }
  else {
    Serial.println("Something went wrong during ethernet module setup!");
  }
} //END OF SETUP

void loop(void) {
  hum = dht.readHumidity();
  temp = dht.readTemperature();
  float tempf = (temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  float dewptf = (dewPoint(tempf, hum));
  Serial.println("++++++++++++++++++++++++++");
  Serial.println("temp = ");
  Serial.println(tempf);
  Serial.println("Humidity = ");
  Serial.println(hum);
  Serial.println("DewPoint = ");
  Serial.println(dewptf);
  // Send all data to WUNDERGROUND
  if (ethernetClient.connect(SERVER, 80)) {
    ethernetClient.print(WEBPAGE);
    ethernetClient.print("ID=");
    ethernetClient.print(ID);
    ethernetClient.print("&PASSWORD=");
    ethernetClient.print(PASSWORD);
    ethernetClient.print("&dateutc=");
    ethernetClient.print("now");
    ethernetClient.print("&tempf=");
    ethernetClient.print(tempf);
    ethernetClient.print("&humidity=");
    ethernetClient.print(hum);
    ethernetClient.print("&dewptf=");
    ethernetClient.print(dewptf);
       ethernetClient.print("&softwaretype=Arduino%20UNO%20version1&action=updateraw&realtime=1&rtfreq=2.5");//Rapid Fire
    ethernetClient.println();
    Serial.println("New data uploaded");
  }else{
    Serial.println("Connection Failed...");
  }
  delay(2500);

}
void resetEthernet() {
 ethernetClient.stop();
 delay(1000);
 Ethernet.begin(mac);
 delay(1000);
 ethernetClient.available();
}
double dewPoint(double tempf, double humidity)
{
  double A0= 373.15/(273.15 + tempf);
  double SUM = -7.90298 * (A0-1);
  SUM += 5.02808 * log10(A0);
  SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
  SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
  SUM += log10(1013.246);
  double VP = pow(10, SUM-3) * humidity;
  double T = log(VP/0.61078);
  return (241.88 * T) / (17.558-T);
}

I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection.
This means after sending u need to close the connection. (else it will work 4 times).

ethernetClient.stop()

Just before or after

Serial.println("New data uploaded");

https://www.arduino.cc/en/Reference/ClientStop


Command through Serial monitor does not properly work in Arduino I am executing a function in Arduino by giving String input to the serial monitor.

The issue here is when i enter "SHOW$" (without quotes) the function showData() works but when i enter the same "SHOW$" (without quotes) it doesn't gets called.
I want to call the function showData() every time i enter the "SHOW$" text into the serial console.

My question here is to what mistake i am doing here, and what is the solution for this.

String strReq = "";
char inChar = 0;

void setup() {

  Serial.begin(9600);

}

void loop() {

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

    if (inChar == '$') {

     Serial.println(" Received String :");
     Serial.print(strReq);

     if (strReq.equalsIgnoreCase("SHOW"))
       showData();

     Serial.flush();
     strReq = "";

    } else {

      strReq = strReq + inChar;

    }

  }

}

void showData() {

  Serial.print("Showing Information");

}

The root of your problem seems to be not knowing what Serial.flush() does.

It pre-Arduino 1.0.0 times Serial.flush() used to clear any data in the serial's RX buffer. It would throw it away.  In your code that would throw away the line ending \r\n that is sent along with the command.

However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer.  This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.

This change was not widely documented, but it is mentioned in the manual:

  Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with Serial.flush() acting like it does in current versions, you would get a different string the second time around.  You would see:

SHOW$
\r\nSHOW$
\r\nSHOW$

and so on.

You have come up with a "fix", which uses String::trim() to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings.  However it would be far better to ignore them in the first place and not need to do the trimming.

The simplest way would be to only add characters to your string if they are printable:

if (inChar == '$') {
 Serial.println(" Received String :");
 Serial.print(strReq);
 if (strReq.equalsIgnoreCase("SHOW"))
   showData();
 Serial.flush();
 strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
  strReq = strReq + inChar;
}

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.


Looking for a wireless soil moisture sensor I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?

The project is very much possible but it will be easier if you attach the moisture sensor directly to the arduino and add a wifi shield or a bluetooth shield to the arduino itself and make it communicate with computer or phone. You could also program the arduino to directly water the plants if it finds that they dont have much moisture. You will rarely find a sensor that transmits data wirelessly and still be economically feasible. The Sparkfun SEN-13322 moisture sensor is good for the purpose but again connect it to arduino direclty.


Calling functions between 2 classes Class myIOT2 contains a function that need to be called from class IPmonitoring:
bool myIOT2::checkInternet(char *externalSite, byte pings)
{
    return Ping.ping(externalSite, pings);
}

This function is needed as a pinger in IPmonitor:
void IPmonitoring::start(cb_func ping)
{

        _ping_cb = ping;
}

and this cb_func is defined by (inside IPmonitor.h):
typedef bool (*cb_func)(char *externalSite, byte pings);
cb_func _ping_cb;

inside my sketch (relevant parts only) I fail when iot.checkInternet is passed, while using a function test that calls iot.checkInternet succeeds:
myIOT2 iot;
IPmonitoring WiFi_service(ROUTER_IP, "Router");

bool test(char *a, byte b)
{
        bool x = iot.checkInternet(ROUTER_IP);
        return x;
}

void setup()
{
WiFi_service.start(iot.checkInternet); // <---- Trial a)fails
WiFi_service.start(test);              // <-----Trail b)succeeds
}

error is :
home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino: In function 'void setup()':
IPmonitor:436:45: error: no matching function for call to 'IPmonitoring::start(<unresolved overloaded function type>)'
         WiFi_service.start(iot.checkInternet);//
                                             ^
/home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:436:45: note: candidate is:
In file included from /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:2:0:
/home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note: void IPmonitoring::start(IPmonitoring::cb_func)
     void start(cb_func ping);
          ^
/home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'IPmonitoring::cb_func {aka bool (*)(char*, unsigned char)}'
Multiple libraries were found

What is done wrong ? and why test succeeds ?

There is a fundamental difference between a simple function and a function that is a member of a class.  You can't use a function pointer to point to a member function of a class: simply because that member function also includes information about the class instance that it belongs to.
The proper C++ way to handle it is to use std::function, but the Arduino AVR compiler lacks the full STL (Standard Template Library), so that can't be used on normal Arduinos. Other cores do have it, so you may well be able to use it on the ESP8266.
If you want to make your code portable between systems that may not have the full STL then there's other tricks you have to do:

Use a wrapper function (which as you have found works), or
Make a polymorphic class and store a pointer to the instance cast to the parent class - the parent class defines the functions that are allowed to be called from the pointer.


Arduino serial plotter with independent Y axis, is it possible? The Arduino IDE has a built in functionality that allows the user to plot a value (such as temperature) over time.

I would like to plot two variables with different ranges on the y-axis (pressure in the range of thousands and temperature which varies from 20°C to 40°C).

I could make it work to have both being plotted, but the range differences does not allow me to see small changes in one/both quantities. Is there a way to two, or more, Y axis each one with its own scale?

No. The Arduino Serial Plotter only supports one Y axis.

An alternative would be to capture the data into a file as CSV data and use some other software to plot it - you could import the data into Excel / LibreOffice, or (as I prefer for quick graphing) use something like GnuPlot (or whatever is similar for your chosen OS).

For instance, this is a GnuPlot configuration for plotting two independent axis datasets and the results:

set datafile separator ","
set terminal png enhanced size 1360,768
set output 'testCharge.png'
set ytics nomirror
set ylabel "Current (A)"
set y2label "Voltage (V)"
set y2tics nomirror
plot "testCharge.csv" using 3 smooth bezier title "Current" w l, \
     "testCharge.csv" using 4 title "Cutoff" w l dashtype 2, \
     "testCharge.csv" using 2 smooth bezier title "Voltage" w l axes x1y2

The data I use is formatted thus:

Phase,Voltage,Current,Cutoff
0,3.58,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.61,1.098,0.033
0,3.61,1.098,0.033
... etc ...

And the results:

Incidentally, that's me charging a Li-Ion battery and monitoring the voltage and current.


Servos not working properly with joystick So, I was working with a project in which I used a joystick module to control two servos at the same time. The joystick controls the servos in a way that when the joystick is moved along x-axis, both servos move in the same direction but when joystick moves in y-axis, the servos move in different directions. I have this program:

#include <Servo.h>
Servo servo1;
Servo servo2;
int joyx = 0;
int joyy = 5;
int joyval;
int joyvalx;
int joyvaly;
void setup() {
    Serial.begin(9600);
    servo1.attach(3);
    servo2.attach(5);

}

void loop() {
    Serial.println(joyvalx + "," + joyvaly);
    int x = analogRead(joyx);
    int y = analogRead(joyy);
    if(x != joyvalx){
        joyval = map(x, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(joyval);
    }
    if (y != joyvaly){
        joyval = map(y, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(1023-joyval);
    }
}

However, the servos don't seem to work properly. One servo works fine but the other just gets stuck. Also, if I use the code for only one direction (x-axis or y-axis) by removing the code for the other, then both servos work good. I can't understand the problem. If anyone does, please help me.

The problem, as jsotola pointed out, is that your code writes totally different values to the servos very fast. You don't combine the two values from the joystick, but just overwrite the previous servo value. So this cannot work.

As I interpret your description, you want the x axis to move both servos the same amount in the same direction (in unity), while the y axis determines the difference of position between them. If you move the y axis to one side, the first servo will go a bit clockwise, while the other goes a bit counter-clockwise. When you then move the x axis, both servos will move to the corresponding direction, while maintaining their position difference.

It is better to first write a formula, how you will calculate each servo position from the given joystick values. The above behavior can be described with these formulas:

servo_1_value = mapped_x + mapped_y;
servo_2_value = mapped_x - mapped_y;

Now you have to map the joystick values correspondingly:

mapped_x = map(x, 0, 1023, 0, 180);
mapped_y = map(y, 0, 1023, -90, 90);

Note, that you should change the parameters for mapping y to the values you need. In the above code they are set to the maximum (meaning that moving the y axis to either end will effectively disable the x axis, since the servo cannot move past 0 or 180 degrees).

You don't really need to check, if the value changed. But if you really want to, you should check the calculated values for each servo separately. Something like this:

if(servo_1_value != old_servo_1_value){
    servo1.write(servo_1_value);
}
if(servo_2_value != old_servo_2_value){
    servo2.write(servo_2_value);
}

But you don't really need to check for a change here.


Coding or Wiring? Dual Piezo sensor not triggering LED lights I am running two piezos off an Arduino UNO and trying to get 10 LED lights to trigger when the piezo voltage exceeds a certain threshold. Problem is, the LEDs wont fire when the Piezo voltage exceeds that threshold and I'm not sure if it is a coding or wiring problem.

Below are pictures of the wiring (Top and bottom) and code. Any help is much appreciated!!

/*
  Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

  -----------------------------------------------------*/

//Piezo 1 Pin (PiezoPin1)
//Piezo 1 connected to A0
int PP1 = 0;

//Piezo 1 Pin (PiezoPin1)
//Piezo 2 connected to A1
int PP2 = 1;

//Sets the threshold for the detected sound to trigger the LED
const int threshold = 0.01;

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

  for (int i = 4; i < 12; i++) {
    pinMode(i, OUTPUT);
    //sets the led pins 2-11 to output
  }
}

void loop() {
  //Ensure to turn off ALL LEDs before continuing
  for (int i = 4; i < 12; i++) {
    digitalWrite(i, LOW);
  }

  /* Read the Piezos
    Reads both piezos and outputs the values. Triggers LED lights
    to fire when a peak voltage is exceeded
    Adjust the value based on the peak signal voltage you
    want to trigger the LED lights*/
  int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
  float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
  int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
  float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
  Serial.println(Piezo1V); //Print the voltage from Piezo 1
  Serial.println(Piezo2V); //Print the voltage from Piezo 2
}

// The blink function - used to turn the LEDs on and off
void blink(int LEDPin11, int LEDPin2, int LEDPin3, int LEDPin4, int LEDPin5, int LEDPin6, int LEDPin7, int LEDPin8, int LEDPin9, int LEDPin10, int Piezo1V, int Piezo2V, int threshold) {
  if (Piezo1V >= threshold || Piezo2V >= threshold) {  //toggle status of LED pins linked to PP1
    // Blink the LEDs on for both Piezos
    { digitalWrite(LEDPin2, HIGH);
      // Delay so that you can see the LEDs go On.
      delay(10);
      // Turn the LEDs Off
      digitalWrite(LEDPin2, LOW);
      // Increase this Delay if you want to see an actual blinking effect.
      delay(10);
    }
    { digitalWrite(LEDPin3, HIGH);
      delay(10);
      digitalWrite(LEDPin3, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin4, HIGH);
      delay(10);
      digitalWrite(LEDPin4, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin5, HIGH);
      delay(10);
      digitalWrite(LEDPin5, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin6, HIGH);
      delay(10);
      digitalWrite(LEDPin6, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin7, HIGH);
      delay(10);
      digitalWrite(LEDPin7, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin8, HIGH);
      delay(10);
      digitalWrite(LEDPin8, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin9, HIGH);
      delay(10);
      digitalWrite(LEDPin9, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin10, HIGH);
      delay(10);
      digitalWrite(LEDPin10, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin11, HIGH);
      delay(10);
      digitalWrite(LEDPin11, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin10, HIGH);
      delay(10);
      digitalWrite(LEDPin10, LOW);
      delay(10);
    }
  }
}

Well, you never call blink, so leds never get a chance to light up.

Also, you are turning down the led at the begining of each loop. That will cause flickring.

And you don't need so many parameters for blink. In fact, what you need is a little function for blinking just one led.

I think this sketch is what your are looking for (but I can't assure it's correct)

/*
  Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

  -----------------------------------------------------*/

//Piezo 1 Pin (PiezoPin1)
//Piezo 1 connected to A0
int PP1 = 0;
//Piezo 1 Pin (PiezoPin1)
//Piezo 2 connected to A1
int PP2 = 1;

//Sets the threshold for the detected sound to trigger the LED
const int threshold=0.01;

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

    for(int i = 4; i<12; i++) {
        pinMode(i, OUTPUT);
        //sets the led pins 2-11 to output
    }
}

void loop()
{
    /* Read the Piezos
      Reads both piezos and outputs the values. Triggers LED lights
      to fire when a peak voltage is exceeded
      Adjust the value based on the peak signal voltage you
      want to trigger the LED lights*/
    int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
    float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
    int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
    float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
    Serial.println(Piezo1V); //Print the voltage from Piezo 1
    Serial.println(Piezo2V); //Print the voltage from Piezo 2

    if(Piezo1V >= threshold||Piezo2V >= threshold)  //toggle status of LED pins linked to PP1
        // Blink the LEDs on for both Piezos
    {
        {
            littleBlink(2);
            littleBlink(3);
            littleBlink(4);
            littleBlink(5);
            littleBlink(6);
            littleBlink(7);
            littleBlink(8);
            littleBlink(9);
            littleBlink(10);
            littleBlink(11);
        }
    }
}

void littleBlink(int pin)
{
    digitalWrite(pin, HIGH);
    delay(10);
    digitalWrite(pin, LOW);
    delay(10);

}


How can I configure Arduino after programming it (for post upload wifi configuration)? I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use.

The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.

If there anyway I can do this with an Arduino interface? If not, what could I use instead?

I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface.  I've been dealing with the same question myself and this might be a workable solution.  The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.

Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield.  You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.


esp8266 not getting programmed I am working on an esp8266 and I am connecting it with Arduino Uno. I have programmed the Arduino but when I write AT command on the serial monitor it doesn't show anything.The connections which i have made are:

tx uno - rx esp
rx uno - tx esp
gnd uno -gnd esp
vcc and ch_pd - 3.3v supply

I am using an external supply and not the 3.3v from the Arduino.
I need help with this.

Be careful, you could fry your ESP like that.  You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno.  There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro.  I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.

I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.

Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.


What is wrong with this code? So I am writing code to control a servo with an RC radio. I am using an Arduino Mega.  I get this error whenever I compile.  I am not that experienced with Arduino so I am probably not doing something right. Thanks for the help!

  Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Mega or Mega
  2560, ATmega2560 (Mega 2560)"

  C:\Users\ethan\Desktop\Periferals_control\Periferals_control.ino: In
  function 'void loop()':

  Periferals_control:46: error: expected ';' before '{' token

  {

  ^

  exit status 1 expected ';' before '{' token

  This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

#include <Servo.h>
Servo servo1;
Servo servo2;
//the following are all ~PWM capable ports
int servoElevator_PwmIn = 6; //Elevator Servo
int servoGrabber_PwmIn = 7; //Grabber Servo

//Channels on AT9
int leftStickVertical = 2; //Channel 3
int rightStickVertical = 3; //Channel 7

int elevatorServoStop = 50;

void setup() {

  //pinMode(servoGrabber_PwmIn, OUTPUT);
  //pinMode(servoElevator_PwmIn, OUTPUT);
  pinMode(leftStickVertical, INPUT);
  pinMode(rightStickVertical, INPUT);
  Serial.begin(9600);

  servo1.attach(6);
  servo2.attach(servoGrabber_PwmIn);
}

void loop() {

  int leftStickVerticalPwm = pulseIn(leftStickVertical, HIGH, 25000);
  int rightStickVerticalPwm = pulseIn(rightStickVertical, HIGH, 25000);
  Serial.print(leftStickVerticalPwm);
  Serial.print("\t");
  Serial.print(rightStickVerticalPwm);
  Serial.print("\n");

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }
}

if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }

You cannot have another comparison in an else statement. You might have meant else if in the last clause.

Clarification if you're not well familiar with C/C++: If you have an if statement, it can be followed by arbitrary many else if clauses and at maximum one else clause which will execute when all other conditions fail. For example:

 int a = 10;
 if( a == 9 ) {
       //Executed if a = 9
 } else if( a < 20 ) {
   //If above not executed, this will be executed if a < 20
 } else {
   //This is executed if none of the conditions above hold.
   //A pure "else" does not have a condition and only one may
   //exist in an `if` statement.
 }


How to write a float value EEPROM I'm using this library for my DS3231 which have a Atmel 24C32 on it.
i have a float value which increases by 0.5, like:

27.50

28

28.50
...

the code is like this:

float lowTemp= 10.5

float highTemp= 10.5

void setup(){
  lowTemp = i2c_eeprom.read(100);
  highTemp = i2c_eeprom.read(101);
}
void loop(){
  if ((menuswtichStatus == HIGH) && (lcdWelcome == HIGH)) {
    previousMillis = millis();
    lcd.clear();
    menuScroll++;
    lcdClear = 1;
    lcdClear2 = 1;
  }
  if (menuScroll == 1) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Minimum  ");
    lcd.print(lowTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      lowTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      lowTemp -= 0.5;
    }
  }
  if (menuScroll == 2) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Maximum  ");
    lcd.print(highTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      highTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      highTemp -= 0.5;
    }
  }
  if (menuScroll == 3) {
    lcd.setCursor(0, 0);
    lcd.print("   Saving the");
    lcd.setCursor(0, 1);
    lcd.print("   Settings...");
    delay(1000);
    i2c_eeprom.write(100, lowTemp);
    i2c_eeprom.write(101, highTemp);
    delay(1000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("    SETTINGS");
    lcd.setCursor(0, 1);
    lcd.print("     SAVED!");
    delay(2000);
    menuScroll = 0;
    lcdClear = 0;
    lcdClear2 = 0;
  }
}

i have the library and stuff up there, it's just an example of my code...

The float value is not saving(written), what's the solution?

You have multiple options:

According to jsotola's remark: the easiest is to multiply your value by 2, store it, and after reading, divide it by 2. In one byte you can store a value from 0 to 127.5 (255 / 2), or if you use signed from -64.0 to +63.5. Of course you also can use an offset in case you know the value cannot be less than e.g. -20.
If you need a higher range, you can still multiply it by 2, but store it in two bytes. Split the value in a 'high value' (value % 256) / 256, and a 'low value' (value % 256).
If you want to store the value completely, than use sizeof(float) to find the length, and a for loop to write each byte, starting from the first byte of the float until the last one.