Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345 Below are the X,Y,Z registers for HMC5883L.

while this is the Arduino code for HMC5883L to acquire X,Y,Z reading.
If you look at this code, we do not mention the X, Y, Z address specifically.

  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0b00000001);
  Wire.endTransmission();
  delay(10);

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
int readValue()
{
  int val = Wire.read()<<8;
      val |= Wire.read();

  return val;
}

We only write Wire.request() and do not mention X,Y,Z addresses specifically for HMC5883L.
While in the case of ADXL345 we mention every register of X,Y,Z separately to acquire data. Which is exactly my question like why not simply use Wire.requestFrom() for ADXL345 too. When will we access each X,Y,Z register separately? and when will we do not?

Below is Arduino ADXL345 code for reading X axis data.

  Wire.beginTransmission(0x53);
  //Ask the particular registers for data
  Wire.write(0x32);
  Wire.write(0x33);
  Wire.endTransmission();
  Wire.requestFrom(0x53,2);
  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
    X1=X1<<8;
    X_out =X0+X1;
    Xa=X_out/256.0;
  }

Datasheets for both sensors are available on the link.

The code above is not mine.
https://drive.google.com/open?id=1AswNTdBz55Rfg3nu4-YsLFj4ANrsCL5I

If you read the datasheet for the mentioned magnetometer, it is clearly mentioned that the data is to be read at once. Below is the implementation of pseudo code mentioned in the datasheet.

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  //send 0x3C 0x00 0x70 (8-average, 15 Hz default, normal measurement)
  Wire.begin();
  Wire.beginTransmission(0x1E);
  Wire.write(0x00);
  Wire.write(0x70);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x01 0xA0 (Gain=5, or any other desired gain)
  Wire.beginTransmission(0x1E);
  Wire.write(0x01);
  Wire.write(0xA0);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x02 0x00 (Continuous-measurement mode)
  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission();
  delay(10);

}
void loop()
{

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
  data = String(x) + "   ,   " + String(y) + "   ,   " + String(z);
  //Send 0x3C 0x03 (point to first data register 03)
  Serial.println(data);
  Wire.beginTransmission(0x1E);
  Wire.write(0x03);
  Wire.endTransmission();
  delay(100);
}

Similarly, it is mentioned in the datasheet for ADXL345 as well that the data should be read separately from each axis register separately.


Why do MEGA2560 digital pins go high on serial disconnect? I'm trying to set up a system using an that delivers a specific number of digital pulses to a device using one of the digital pins. The number of pulses delivered is specified over a the Mega's USB serial connection using a Python script (or terminal for debugging).
When I close the serial connection to the Arduino, I get a short "blip" that looks like a digital high (see image below). This happens when I disconnect in PySerial using Serial.close() or when I simply close my Arduino IDE terminal window.
It does not occur when I press the reset button on the board
Any ideas on how to get rid of this?  Thanks!

When you connect and disconnect from the Arduino, the usb host chip resets the entire device. If you do not want this you can cut the RESET trace on the board.

some boards have a jumper here instead that can be removed.

more info here

https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


Arduino + WiFi 101 Gerber Files Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101?  I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side.

Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP?  I am under the impression that it is open source but I'm not sure where the OS boundary ends.

On the Arduino UNO and Wifi shield websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says

  The Uno is open-source hardware! You can build your own board using
  the follwing files

With the free version of Eagle, you can open it and export to gerber file format.


How to connect more than one arduino serial port together The idea is to connect more than 1 arduino slave to master as shown in schamatic

simulate this circuit – Schematic created using CircuitLab
The problem is TX slave can not just combine to master RX.
It need to done some trick like tri-state buffer to make slave TX one at time.
Anyway, avr port can config as tristate buffer.
(Q1)Is there any software solution to done this?
Second If I connnect TX to RX for half-duplex communication (using 1 data line). How to make Rx stop listenning to its self while transmiting data?

You can do it with two diodes and a resistor:

simulate this circuit – Schematic created using CircuitLab
You'll still have to implement some system to prevent collisions, but electrically that will be sound.


How does one use (specically the wiring) the OV7670 camera with the Arduino Uno? If one could tell me where each of the pins on the back of the camera go to, that would be great. if someone added the code also that would be awesome.

You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno.
And you need to connect A7 to XCLK signal via 2 registers.

You can find schema and code in my blog: How to connect Arduino Uno and OV7670


Connecting to Arduino Ethernet Shield How do I figure out how to connect to my arduino using ethernet shield?

It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.

The client example works, so it's not broken or anything.

I'm using Arduino 1.6.5 IDE on a Mega 2560. I'm trying to run the Examples/Ethernet/WebServer example.

Your question is kind of trivial, but from what I understood you're typing the IP address (that the Arduino displays on the serial monitor)  into your browser.

First, make sure you connect your Ethernet shield to your router using an ethernet cable. (Now it's connected locally...)

Second, even if you type in your Arduino's IP address into the browser, the browser will return nothing because the Arduino simply has nothing to display, and hasn't been programmed to accept requests.

To actually have the Arduino display something you can try the Webserver example sketch or you can follow this great Tutorial that I found very useful for beginners.

BTW ports are only used to expose your Arduino to the Internet, in other words if you don't portforward to your Arduino, your Arduino won't be able to get requests from outside your local network (Wi-Fi,Ethernet).


Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4 Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4.
Problem: Only want a single segment/fx_mode to run at any one time.

#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {

ws2812fx.init();

ws2812fx.setBrightness(85);

// divide the strip of 60 LEDs in to 4 segments

ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);

ws2812fx.setSegment(1, 15, 29, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.setSegment(2, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);

ws2812fx.setSegment(3, 45, 60, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.start();
}

void loop() {

ws2812fx.service();
}

The used library doesn't give you the direct possibility to automate the segment changes. So you need to write that code yourself.
Currently you are setting up all segment in setup() and starting them together via start(). Instead you should add the corresponding segment only, when it should be on, and removing all segments, that should not run. In the following I don't remove and add a segment, but I'm replacing the previous segment (described below)
I propose a code like the following, to light up each element after the other for a specific time each (not tested):
#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

#define SEGMENT_INTERVAL    3000
unsigned long segment_timestamp;
uint8_t current_segment = 0;
#define SEGMENT_N   4

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
    ws2812fx.init();
    ws2812fx.setBrightness(85);
    ws2812fx.start();
}

void loop() {
    if(millis()-segment_timestamp > SEGMENT_INTERVAL){
        segment_timestamp += SEGMENT_INTERVAL;
        switch(current_segment){
            case 0:
                ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);
                break;
            case 1:
                ws2812fx.setSegment(0, 15, 29, FX_MODE_SCAN, RED, 3000, true);
                break;
            case 2:
                ws2812fx.setSegment(0, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);
                break;
            case 3:
                ws2812fx.setSegment(0, 45, 60, FX_MODE_SCAN, RED, 3000, true);
                break;
        }
        current_segment = (current_segment + 1) % SEGMENT_N;
    }
    ws2812fx.service();
}

What happens here? First we use the millis() function in the pattern of the BlinkWithoutDelay example to time the change of segments to every 3s (3000ms) without blocking the execution of the other code (here the service routine of the LED animation). I will not go into detail here, since this principle is described at numerous places through the web and this site. Just search for something like "Arduino millis" or "Arduino Blink without delay". Now is only important, that the code inside the if statement will be executed every 3s (can be changed with SEGMENT_INTERVAL).
In the if statement we use a switch statement to set the corresponding segment, that should be activated at that time. Here we always set the segment 0, since only one segment is active at any time. Instead of removing the previous segment and adding the new one, we just change the previous segment to the data of the new segment.
With the line
current_segment = (current_segment + 1) % SEGMENT_N;

we increment to the next segment, while wrapping around from segment 3 to segment 1 via the modulo operator %. This is needed to loop through the segments.
The call to ws2812fx.service() is still needed, since it handles the actual animation of the current segment.

Note, that the above code can still be improved. You could save all the segment data in an array of structs and replace the switch statement with one line, using the current_segment'th element of the array. I will leave that improvement to you.


Navigating menus using buttons on Arduino I have made a very short version of my code. It has the basic problem I am facing. I explain my code and problem below.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

int menu = 0;
int subMenu = 99;
void loop() {

  uint8_t buttons = lcd.readButtons();

  lcd.setCursor(0,0);

  if (menu == 0) {
  lcd.print("Select menu option");
    if (buttons & BUTTON_SELECT) {
      lcd.clear();
      menu = 99;
      subMenu = 1;
    }
  }

  if (subMenu == 1) {
    lcd.print("in sub menu 1");
    if (buttons & BUTTON_SELECT) {
       lcd.clear();
       lcd.setCursor(0,1);
       lcd.print("shouldnt happen");
    }
  }
}

I am setting a variable menu, which will keep track of what main menu I am on, and a subMenu, which keeps track of what sub-menu I am on.

The default value of menu (0) prints on the LCD "Select Menu Option".

When pressing SELECT, the LCD is cleared. The menu is being set to an unknown number, so that it doesn't print anything, and subMenu is set to 1.

If subMenu is equal to 1 (which it will be if the user chooses presses SELECT), the LCD prints "in sub menu 1".

Inside this, if the button SELECT is clicked, it should print "shouldnt happen".

The issue I am facing is that when clicking SELECT for entering the menu 1, the SELECT is also carried out to the sub-menu, so instead of waiting for a second key press to confirm going into the sub menu, it goes straight into it.

This makes sense because it is check that SELECT has been pressed, prints a new page, with the button SELECT still having been pressed, so it validated the condition for key press in the sub menu as well.

The user input to LCD display response should be the following:

Select menu option -> presses SELECT -> in sub menu 1 -> presses SELECT -> shouldnt happen

Currently however, it is like this:

Select menu option -> presses SELECT -> in sub menu 1 shouldnt happen

How can I make it so that these key presses only act on the menu on which they are?

Thanks, let me know if something confuses you, I can explain in more details

I'm not sure about built-in buttons, however on my projects I always add a debounce feature to any buttons.  Adjust this to your uses. If there's any issues let me know and I'll test it properly as I'm not at my programming workstation to fully test at the moment.

For example:

// Updated to include if statements and copy/pasted version of successfully
// compiled version.

// Had to use LiquidCrystal library as I don't have the AdaFruit Display libraries.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//

int menu = 0, subMenu = 99, debounce = 200;
unsigned long pMillis = 0, cMillis;

void setup(){
  lcd.begin(16,2);
};

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();
  lcd.setCursor(0,0);
  if(cMillis >= (pMillis + debounce)){
    if (menu == 0) {
      lcd.print("Select menu option");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  menu = 99;
       *  subMenu = 1;
       *  };
       */
    };
    if (subMenu == 1) {
      lcd.print("in sub menu 1");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  lcd.setCursor(0,1);
       *  lcd.print("shouldnt happen");
       *  };
       */
    };
  pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
  // I always put something similar to this at the end
  // to make sure that when millis() cycles back to 0
  // pMillis is reset to less than cMillis.
  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
};

Edit/Update:  This compiles fine using the standard LiquidCrystal library, I am unable to test the AdaFruit display as I don't have one.  If this still doesn't work, I'll upload it to the Arduino when I get back and see what's up.

New test:

// Your libraries here

int menu = 0,
    subMenu = 99,
    debounce = 200;

unsigned long pMillis = 0,
          cMillis;

void setup(){
  lcd.begin(16,2);
}

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();

  if(buttons & BUTTON_SELECT){ // I used "if(digitalRead(buttonPin) == HIGH){ ... }"
    if(cMillis >= (pMillis + debounce)){
      //I'd normally put counter/menu logic in here for the different buttons, for example:
      //"subMenu += 1;
      // if(subMenu >= totalSubMenus) { subMenu = 0; };"
      subMenu = 1;
      pMillis = cMillis;
    }
  }

  if(menu == 0){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Select Menu Option");
    menu = 99;
  }
  if(subMenu == 1){
    lcd.clear();
    lcd.setCursor(0,1);
    lcd.print("In Sub Menu 1");
  }

  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  }
}


SR505 PIR sensor Time Delay Using Ticker Library NodeMCU I am trying to make the value of PIR sensor value HIGH for certain time using code. SR505 have a default time delay of 8 seconds. But I want to increase it to 20 seconds.

I am thinking of increasing it using TICKER library. I have tried and tested a basic code and seems to be working fine. But I want to implement it with Ticker which will keep the value HIGH for 20 seconds as soon as the timer goes above 20 seconds and PIR is not detecting the motion then it will go set again the timer to 0.

Here is how my code looks like:

#include <Ticker.h>

#define SIGNAL_PIN D2

Ticker flipper;

void setup()
{
  Serial.begin(9600);
  pinMode(SIGNAL_PIN, INPUT);
  digitalWrite (SIGNAL_PIN, LOW);

}

void flip(){
  Serial.println("From callback");
  digitalWrite (SIGNAL_PIN, HIGH);
}

void loop() {
  if(digitalRead(SIGNAL_PIN)==HIGH) {
    Serial.println("Movement detected.");
    flipper.attach(1, flip);
  } else {
    Serial.println("Did not detect movement.");
    flipper.detach();
  }
  delay(1000);
}

Thank you!

You really don't need the Ticker library. Just maintain a timestamp of the last time the PIR was seen to be HIGH:

void loop() {
    static uint32_t lastSeenHigh = millis();
    static bool pirState = false;

    // If it's active then record that fact along with the time
    if (digitalRead(SIGNAL_PIN) == HIGH) {
        lastSeenHigh = millis();
        pirState = true;
    } else {
        // otherwise, if it's been 12 seconds since last seen
        // active, record that it's inactive.
        // 20 seconds, minus the 8 second active time, times 1000 is
        // 12000 milliseconds to extend the time by
        if ((millis() - lastSeenHigh) > 12000) {
            pirState = false;
        }
    }

    if (pirState == true) {
        // Do whatever you want in here when the PIR is active
    }
}

With that (untested) code:

Any time the PIR is active the current time is recorded and the state is set true
When the PIR is LOW and at least 12 seconds have passed since the last activation, set the state to false.


How to use I2S in ESP boards? I have researched this a lot, but haven't found anything on which I can trust.
I want to use a particular ESP board to play audio. To play audio, I2S support is required. But, I know that not every ESP board break out the I2S pins from the chip. According to me, buying an ESP32 only to use the I2S would be a waste of money. So, my question is, if I just want to use I2S, which board is would be suitable? Please provide some references if you can.

Few months ago I tested successfully I2S with this library, I used the default pins:

bck_io_num = 26
ws_io_num = 25
data_out_num = 22

which are available on many boards such as Lolin D32.


Class is not tracking changes to a private field I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object.
This is the main sketch

#include "command.h"
#include "widget.h"

Command command;
Widget widget;
void setup() {
  command.init();
  widget.init(command);
}

void loop() {
  command.update();
}

command.h

#include "Arduino.h"

#ifndef Command_h
#define Command_h

typedef struct  {
  char id;
  char name[20];
} Device;

class Command
{
  public:
    Command();
    void init();
    void registerDevice(Device _cmd);
    void update();
  private:
    Device Devices[20];
    byte DevicesPtr = 0;
};

#endif

command.cpp

#include <Arduino.h>
#include "command.h"

#define DEVICES_MAX 9

Command::Command() {
  DevicesPtr = 0;
  Device Devices[DEVICES_MAX];
}

void Command::init() {
  Serial.begin(9600);
}

void Command::update(){
  Serial.print( DevicesPtr );
  Serial.println( " devices registered" );
  delay(500);
}
void Command::registerDevice(Device _cmd) {
  _cmd.id = '0' + (++DevicesPtr);
  Devices[DevicesPtr] = _cmd;
  Serial.print("Devices registered ");
  Serial.println(DevicesPtr);
}

widget.h

#include "Arduino.h"
#include "command.h"

class Widget
{
  public:
    static void init(Command _command);

  private:
};

widget.cpp

#include "widget.h"
#include "command.h"

void Widget::init(Command _command) {
  Device device;
  strcpy(device.name, "Widget #1");
  _command.registerDevice(device);
}

It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.

This is call-by-value (the incoming command is not updated, a copy is passed as parameter):

void Widget::init(Command _command)
...
widget.init(command);

This is call-by-reference (a pointer to command is passed as parameter):

void Widget::init(Command* _command)
{
   __command->registerDevice(...);
}
...
widget.init(&command);

Alternative syntax is:

void Widget::init(Command& _command)
{
   _command.registerDevice(...);
}
...
widget.init(command)

Cheers!


TCP or HTTP connection between web server and arduino If arduino works as a client and tries to connect to web server (the server is mine), should I connect to it via TCP or HTTP connection? Data will be simple strings (20 chars at max) so TCP connection should probably be enough?

The connection has to work in both ways - web server sending data to arduino and arduino sending data back to server.

It's time you learned the OSI 7 layer model: PDNTSPA.

HTTP is a Presentation (protocol) that runs over a TCP Session.  If you are interacting with a web server then you will be opening a TCP socket and sending HTTP requests.

There is no other way of talking to a web server. It only speaks HTTP, and you can only connect to it through TCP.


connecting 4 wire camera to esp8266 I am looking for the arduino code to stream video to a webpage using the ESP8266.
here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793

The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.

Any help or pointers would be most appreciated.

As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series).
The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.

No.  Your link is to an analog NTSC camera.   Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.

It is simply not compatible to use this with a small embedded system.

If you really want a camera for a resource constrained embedded system, seek a still camera with a serial or SPI output.

Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.


Aurduino Smart Wifi Wall Socket i wanted to make a remote controlled wall socket over wifi (and maybe internet in the future) with an Arduino, i'm relatively new to Arduino, i know only the basics of programming. My idea was to use a Arduino Pro Mini, a relay, a Esp8266 wifi module to connect to my home wifi and maybe a module to monitor consumption like the ACS712 current sensor but i don't know how to make all of this work, maybe i can get the Arduino working but i don't know how to control it on the client side like an app or web interface on my phone/computer.

The hardware you have chosen is perfect for the job at hand.
But what @Hapi also mentioned was that you could probably do away by not using the Arduino !
The ESP8266 is in itself programmable. There are many Firmwares available to help you do so. (You can even program your own)

This can help you getting started : http://randomnerdtutorials.com/esp8266-web-server/

This is something like what you need at the end : https://hackaday.io/project/4562-esp8266-wifi-smart-garage-door

One thing to note : ESP8266 works with 3V, while your Relay would require 5V.
Happy hacking my friend.


How can i increase the range of values that a light sensor gives? I have constructed 2 ceptometers that measure light intensity. Each ceptometer consists of 50 photodiodes that are connected to 2 copper wires (+ and - of the photodiodes are on the same orientation). Those wires are soldered with cable (+ to the copper wire where the positive side of the photodiodes is and the ground wire soldered to the copper wire where the negative side of the photodiodes is). Then, pins were soldered to the cables so as to can be connected to the breadboard.
The paper where the protocol for the construction is present, states that a 1.5 ohms resistor needs to be connected to the copper wires so as to enhance the range of the signal that the ceptometers will give. However, it mentions that this step can be followed later and the resistor can be connected to the wires (that is something that makes sense). I need to mention that one more ceptometer is present that was constructed by another person the previous year and it has the 1.5 ohms resistor soldered on the copper wire. It is something very important to keep in mind for the rest of the text!
I decided to use an arduino uno for my experiment and I connected the 3 ceptometeres (the old from the previous year and the 2 that were constructed by me) to a breadboard. Firstly, I applied light to the ceptometers with a projector and I tried different resistors from 470R to 5K but the values I got were the same. I thought that a kind of signal disturbance or noise may has been caused and I made 3 opAmp circuits in 3 different breadboards. When the breadboards were connected to the Arduino I tried the same resistors again but the values I got were the same. For the old ceptometer that has the 1.5 ohms resistor soldered to the copper wires the change of resistors altered a lot the signal and it gave a wide range of values. Here I have to say that when I applied to the 1.5 ohms resistor to the new captometers I got a pure 0 as a value. And it was the same when I placed them under sunlight.
When I converted the output of the Arduino to voltage signal by multiplying it with 5 and then divide it with 1023 I had the same voltage signal as when I measured it with the multimeter. And it was the same under both artificial and sun light. So, I can imagine that it is something that depends on the resistor that is not applied to the copper wires. I mean that maybe this is the case that I do not get a wide range of values like the old ceptometer but only 20 units
My question is: Do you know any way to enhance the range of the output or do you have any recommendation? Thank you a lot in advance!
With kind regards,
Dimitrios

The circuit is a current-to-voltage converter.  The - input to the op-amp is held at 0 (the voltage at the + input, since it is grounded) so there will be no voltage across the diodes.  The current drawn by the diodes is supplied by the op-amp output through the feedback resistor, so the larger that value, the greater the output voltage will be at any given current.  The short answer is that to increase the output voltage, you need to increase the feedback resistor. (7 ohms seems pretty small to me, unless your diodes draw a LOT of current.)
The other complicating issue is that this circuit depends on the op-amp having a low input offset voltage, since its value (~2 mV for the LM358) causes output errors.  Normally a low-offset-voltage op-amp would be used here, but maybe the use of so many diodes makes a large enough current to swamp the offset error.  If increasing the feedback R doesn't help, you might try a different op-amp (even another LM358) in case the offset of the one you have is trying to force a negative output and that's why you see 0.
Edit 11-8-20:  I looked up the sensor used in the PAR-BAR article that seems to be the source of your circuit.  It pulls about 10 microamps at 1000 lux, so 50 of them would give 500 microamps.  If you want to get (say) a 5V output at 1000 lux, you'd need a feedback resistor of 5/0.0005 = 10 kOhms.  That's without the 1.5 ohm shunt.  Also, are you applying your test illumination evenly over all 50 sensors?  The above calculation assumes that all get 1000 lux.
If you have a single sensor available, I'd recommend breadboarding with just that and a 500 kOhm feedback resistor, and no shunt.  That way there will be no issue about equal illumination.  If you still have problems, and you are committed to the LM358 for some reason, try using a simple circuit to compensate for input offset.  These typically involve a potentiometer (could be a trimmer in the final unit) that adjusts a very small voltage applied to the + input.  In your tests you may find that it needs to be negative, which you would have to apply from some external source (since there is no - supply on the Arduino).  If that's needed to resolve your problem, consider a better op-amp or a different circuit configuration.
Edit 11-9-20: Had another look at the PAR-bar article and noticed that they are measuring differential voltage across the photodiode array, which is not the same as your current-to-voltage converter (although that is indeed typical of photodiode circuits).  The voltages that they get are 30 mV or less.  I suggest you get a DMM and measure the voltage across the array, without any connection to other circuitry.  Cheap DMMs have 200 mV full-scale, which should at least show you what's going on.  The article used an expensive datalogger and only suggests that Arduino-type solutions may be possible, but gives no circuits.  You probably don't need a true differential amp, since the photo voltage is always in the same direction.


Supplying near perfect DC signals from Arduino UNO My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter?

TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.

(1) A multipole active lowpass filter works wonders.
Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD & LT and NatSemi all have good free active filter design programs.

(2) A Simple sample & hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.

With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&H and update them occasionally top compensate for drift.  If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R  resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading.

If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept.


Stream video from camera to mobile and send control signal back from mobile to Arduino via WiFi I want to make an Ardunio based project in which I want to stream live video from camera (which is connected to Arduino borad ) to my Android app via WiFi and send back actions/control signals from my android app to Arduino to controller servo motor which are connected to Arduino board. Right now I only have Arduino mega with me. What else components are going to be required?

You need good MPU with enough buffer size and nand size for such an intense process

Search esp modules

Thanks.


Arduino Uno power input - is 5 V at 1 A enough? I have a Arduino Uno board and phone power bank

Power bank details

Capacity - 8000 mWh
Input  - DC 5 V and 1 A
Output - DC 5 V and 1 A

Can I give the power to Arduino Uno using this power bank, through the Arduino Uno USB?

I dont see why not - YES you can!

I regularly use usb powerbanks to power projects for testing. so long as you dont ask for too much current (unlikely but project specific) you will be fine!


Can I solder wall cord directly to servo? I have a servo which requires 7.4v and a wall power cord which says the output is 7.4v but the connector does not fit that of the servo. Is it safe to snip off the end of the wall cord and solder the internal wires directly to the servo?

First choice: Attach compatible, polarized connectors to both pigtails.

Alternatively, you can solder it up but the result is certainly less convenient to use. I like heat-shrink tubing for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires before I solder the joints. :)


Take the program from the arduino board How to remove the program from arduino board which is already there in it.?And I need that program in my arduino IDE how to take it please help me?

You can retrieve the program currently in your Arduino with the
avrdude tool. This tool comes with the Arduino installation. The way
to call it is somewhat OS-dependent. On Ubuntu, for an Arduino Uno, I
type:

avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:r:prog.hex:i

This creates the file prog.hex with your program in Intel
HEX format. You can save this
file if you want to re-install it on the Arduino later. You can also
turn this file into an assembly listing with avr-objdump:

avr-objdump -m avr -Dz prog.hex > prog.lst

You may be able to make some sense of this listing if

you are well versed in AVR assembly language
you have lots of spare time

As others have said, you cannot expect to get the original C++ source
back.


5 inch TFT LCD for Arduino I want to use a 5 inch 800x480 TFT display (touch not needed) with an Arduino (mega, uno or due). I'm thinking of buying this display: link (buydisplay.com). How can I connect this ?

I have also seen some pricier screens with serial i2c connection., but I don't understand the difference between this and using a shield?

Do anyone have any advice for displays to order and/or shields for Arduino ? Preferably a solution that I can reproduce by my self later for mass-production by doing be own circuit board.

Thanks in advance!

You need a driver board to run it. SSD1963 based ones are popular and are often included on the screen, especially the 7" ones on eBay.

Arduinos cannot drive a display directly. Small TFT screens often include the driver chip on them in the form of a Chip On Glass (CoG). That can't be done with the larger screens due to the sheer amount of memory needed to store the frame buffer. So an external chip has to be used, or a microcontroller with built in TFT interface.

Note that even with an SSD1963 (or equivalent - see the ones BuyDisplay sell are based on the RA8875) interfacing the Arduino to the TFT screen results will most likely be somewhat disappointing. Especially if you are interfacing using SPI or I2C which will create a bottleneck. Best is to interface with a 16-bit "8080" interface (16 data bits, read, write, chip select, reset and D/C), however that takes a lot of IO pins, and ideally a proper parallel interface to drive it quickly. And you want a lot of RAM for manipulating the data you want to display...


Send \r or \n via phone serial monitor I have a bluetooth adapter connected to uno, and using a serial monitor on phone.

In the arduino code im debugging there is this line waiting for new line signal in the serial stream:

char c = SerialBT.read();

if (c == '\r' || c == '\n'){

no matter what i try sending to via my phone i cant get this to evaluate as true...

if i send \n , i believe it is sending it as 2 chars \ and n , not as a single char.

is this a problem with the phone app or what ?

It turns out it was a problem with the android terminal program i was using, by switching to another that specifically has support and options for \n \r things it works now.


Bit shifting fails with warning: left shift count >= width of type Given the following minimal working example. I tested this initially with uint16_t and it worked with no warnings. After that, I adjusted everything to work with uint32_t.

#include <stdint.h> /* needed for the uint16_t type*/
#include <inttypes.h> /* needed for sscanf uint16_t format placeholder  */
#include "printf.h"

#define SET_CMD_ID(ID)    ( (ID) << 27)
#define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
#define SET_CMD_PKT(PKT)  ( (PKT)    )

void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.print(F("\n\rExample command\n\r: "));

}

void loop() {
  uint32_t payload = 0;

  uint8_t id = 3;   // 00000 - 5
  uint8_t cmd = 2;  // 00    - 2
  uint8_t type = 1; // 000000 - 6
  uint32_t pkt = 0; // 0000000000000000000 - 19

  payload =
        SET_CMD_ID(id)   |
        SET_CMD_CMD(cmd)  |
        SET_CMD_TYPE(type) |
        SET_CMD_PKT(pkt);
  Serial.print(F("Now sending "));
  Serial.println(payload);
  delay(2000);        // Try again soon
}

Verifying this sketch outputs:

/path/to/ino/Arduino32bitTest.ino: In function 'void loop()':
/path/to/ino/Arduino32bitTest.ino:5:37: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_ID(ID)    ( (ID) << 27)
                                     ^
/path/to/ino/Arduino32bitTest.ino:28:9: note: in expansion of macro 'SET_CMD_ID'
         SET_CMD_ID(id)   |
         ^
/path/to/ino/Arduino32bitTest.ino:6:39: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
                                       ^
/path/to/ino/Arduino32bitTest.ino:29:9: note: in expansion of macro 'SET_CMD_CMD'
         SET_CMD_CMD(cmd)  |
         ^
/path/to/ino/Arduino32bitTest.ino:7:41: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
                                         ^
/path/to/ino/Arduino32bitTest.ino:30:9: note: in expansion of macro 'SET_CMD_TYPE'
         SET_CMD_TYPE(type) |
         ^

Sketch uses 3,174 bytes (9%) of program storage space. Maximum is 32,256 bytes.
Global variables use 216 bytes (10%) of dynamic memory, leaving 1,832 bytes for local variables. Maximum is 2,048 bytes.

Executing the sketch on an Arduino Uno results in:

Example command

: Now sending 0
Now sending 0
Now sending 0
Now sending 0

I googled the message of the warning and found out that it could mean that I'm trying to shift 32bit which is undefined, but I'm not sure on that. So my question is:
What am I doing wrong here? How can I get this to work?

It's basically an inability of the compiler to auto-promote the source variables to a size big enough to fit the shifted version.

The default type for all operations, unless otherwise specified, is 16-bit. By shifting more than 16 bits you are overflowing that default type.

To get around it you have to manually tell the compiler that you want to work with 32-bits:

#define SET_CMD_ID(ID)      ( ((uint32_t)ID) << 27)
#define SET_CMD_CMD(CMD)    ( ((uint32_t)CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( ((uint32_t)TYPE) << 19)
#define SET_CMD_PKT(PKT)    ( ((uint32_t)PKT)    )


Generating a PWM frequency greater than 125 kHz using Arduino Uno I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?

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

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
  delayMicroseconds(900);
}

Update

On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.

My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

Second sketch:

// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output (but cro measures only 125 kHz)
   TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
   TCCR2B = _BV(WGM22) | _BV(CS20);
   OCR2A = 63;
   OCR2B = 0;

  // Set up the 8 MHz output
   TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
   TCCR0B = _BV(WGM02) | _BV(CS00);
   OCR0A = 1;
   OCR0B = 0;

  // Make the 250 kHz rolling
  while (1) {
    _delay_us(5);
    if (OCR2B < 63)
      OCR2B += 5;
    else
      OCR2B = 0;
  }
}

It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM


915Mhz vs Wifi (speed impact of duty cycle limitations) I am currently using an esp32 with Wifi. I need at least 15kByte/s constant throughout. This works fine but I am not happy with the range.
I came across the RFM69HCW 915MHz module. It is stated with 300 kbps.
Now what is confusing me are duty cycle regulations. Various countries have a 1% limit.
Is this limit considered in the 300 kbps? Or do I effectively only get 3 kbps because I cannot constantly send?

300kbps is the data transmission rate. Not the throughput rate.
That means that yes, if you only transmit for 1% of the time then for 1% of the time you are getting 300kbps - i.e., 3kbps as you correctly surmised.


How can I program an arduino in pure C? I am a beginner and I want to learn AVR C/C++. Can I do this using an Arduino?  (I'm asking this because I already have one).

If so, could someone tell me using which IDE can I write code in pure C/C++ and then flash it to the Atmega328P on the Arduino?  Or, should I get an AVR and a programmer instead?

I've searched all over the internet and I'm really confused by all the terminology. Could someone explain it to me?

Yes, get an AVR programmer instead.

1) You can flash your arduino board with avrdude/avr-gcc. Install these tools, find the datasheet of atmega328 (google it), use the board pinouts to connect to your programmer (stk500v2/ISP) and voila!

2) Keep in mind that by "manually" flashing your atmaga on arduino board you're removing bootloader that is needed to load your sketches from ARDUINO IDE.

3) Use your favourite C/C++ IDE


How to serially transfer/read an image to Arduino I am using Arduino Uno and the image size is 12.7 kb. I want to read a jpeg image from computer and convert into bitmap in arduino. Later on it will be implemented using SD card.Is it possible to read a .jpeg image from computer to Arduino using serial communication? If yes, then how?

You can send anything you like through the serial port. It is just 8-bit raw data. The onus is on you, however, to implement a suitable high level protocol with which to transfer the data.

One important thing to bear in mind though: JPEG is a highly compressed complex image format. I am not aware that anyone has ever managed to squeeze JPEG decompression into a lowly Arduino. Instead you will need to use a decompressed image format such as BMP, or do the decompression on the computer before-hand and send the raw RGB image data over the serial instead.


Higher precision logarithms I need to produce a log to base 10 with at least 4 decimal places. However, the log10 inbuilt function is giving the output with only two decimal places. What do I do? Is there a different function or a library that I can use?

You should be able to get 6 or 7 decimal places out of the Arudino float type. Try using Serial.print for floats with a number of decimal places. Something like this:

float x = log10(3.141592658);
Serial.print(x, 6);


Problem with my 2 motor system I am trying to operate two DC motors at once using a L293D chip. I have managed to control them however, one of the motors has a slight problem. Whenever I start the program (attached below), one of the motor (I tried switching them, it isn't a problem due to the motor itself) has a counterclockwise spin for a second before starting to spin clockwise as it is suppose to. When it is spinning counterclockwise, the other motor is not doing any movements.

Is something wrong in the code or in the circuit? (I've also attached a hyperlink to my circuit which I found online, as well as my code)

Thank you

#define E1 11  // Enable Pin for motor 1
#define E2 10  // Enable Pin for motor 2
#define I1 12  // Control pin 1 for motor 1
#define I2 13  // Control pin 2 for motor 1
#define I3 8   // Control pin 1 for motor 2
#define I4 9   // Control pin 2 for motor 2

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);
  pinMode(I3, OUTPUT);
  pinMode(I4, OUTPUT);
}

void loop() {
  analogWrite(E1, 255); // Run at full speed
  analogWrite(E2, 255); // Run at full speed
  digitalWrite(I1, HIGH);
  digitalWrite(I2, LOW);
  digitalWrite(I3, HIGH);
  digitalWrite(I4, LOW);
  delay(4500);
  // change direction
  digitalWrite(E1, LOW);
  digitalWrite(E2, LOW);
  delay(2000000000000);
  analogWrite(E1, 255);  // Run at full speed
  analogWrite(E2, 255);  // Run at full speed
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
  digitalWrite(I3, LOW);
  digitalWrite(I4, HIGH);
  delay(000);
}

http://hw.sudarmuthu.com/wp-content/uploads/sites/2/2013/06/basic-bot1.png

#define I2 13  // Control pin 2 for motor 1

Pin 13 is the LED and is blinked by the bootloader. You will have to use a different pin for your motor.


Can I connect my arduino ground to an external battery ground? Are they the same when said battery is powering the arduino? I need to power my camera peripheral with an external power supply, since apparently I can't power both the camera and the camera's relay switch with my 5V out pin (My relays cut out and continually reset themselves if I try to run my 5V to both the camera relay switch and the relay board VCC.)

So I'm powering the camera with a 5V battery pack and my arduino with my PC, but I still need to communicate with it via UART, so I need the camera ground to be the same as my arduino ground. Can I connect the two? Is this a bad idea? Because I'm doing it now and it seems to work. I just don't want to cause a problem later on down the road, whether I'm connected to my computer or on battery power.Any advice would be greatly appreciated.

A battery's ground is floating. That means that it's "happy" to take on any absolute value by simply connecting it to another ground - it just stops floating. This is why it's easy to connect a battery-powered phone directly to a computer to get the photos off or whatever.

The only time you shouldn't connect two grounds is if neither are floating. A good example would be the grounds of two different houses, which are physically connected to the Earth (as in the planet). It'd be difficult to budge the whole Earth's ground level!

But shouldn't they be the same? Unfortunately not. You could measure a distinct voltage difference (sometimes in the hundreds of volts) between two house earths due to the differences in their makeup.

One small note: if you do connect two grounds, only connect them in one spot. If you have two other ground pins a small distance away from the connected ones, there may be a voltage difference between them: now the two are explicitly relative to each other, so neither can be considered floating relative to each other. The pair as a system - if neither are earthed at least - is still floating.

These so-called "ground loops' can induce current where none is desired.


How can I run multiple programs on an Arduino? I'm trying to get students to experiment with Arduino. However, due to a lack of boards, two teams of students will collaborate on each board. They will push their own code (independent from each other) and use half the pins.

The "hardware" part isn't really a concern: students will push their sketches on a server that uploads them on the board, or something like that.

What I'm worried about is the software part. How can I allow two sketches to run on the same board, and allow the user to upload sketches without resetting the board?

As of my understanding, using the flash memory isn't an option, because the board must be reset before it can be written.

My first idea was to compile the students' C code into custom-made "assembly", and then push the assembly code to the board, which stores it into RAM and interprets it. However, my biggest problem would be implementing functions, I don't really have a clue of how I could do that. While common C functions could just be encoded in a fashion like FUNC printf STRING %s VAR a for printf("%s", a), I don't know how to encode user-defined functions. Besides, I don't even think the RAM is sufficient for running the client, storing two small programs, and running them.

Then, I thought about running the C code on the computer, but replacing digitalWrite with appropriate signals to the board. However, I'm worried about the performance of this, mostly when dealing with "high" speeds - say, using a custom-made library to print text on a LCD driver.

In addition to the other answers, I have a few ideas:

1.) Instead of doing variable prefixes, have them wrap all of their code inside a namespace! Please note that you can't wrap "setup" or "loop" in that namespace. Example

setup() {
  if(conditionIsTrue) {
    aGroup::setup();
  } else {
    bGroup::setup();
  }
}

loop() {
  if(conditionIsTrue) {
    aGroup::loop();
  } else {
    bGroup::loop();
  }
}

namespace aGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

namespace bGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

2.)

Please note you'll have issues with a student tries to access an analog pin and doesn't prefix it with A. For example, if I wanted analog pin 5, I should do analogRead(A5);, not analogRead(5);. That could cause some major issues.


How do I change the scope of an object? I am using the File/Examples/Adafruit MQTT Library/mqtt_ESP8266 example as a model for my code.  In the example, the mqtt object is created as a global variable, and everything works fine.  However, I need to create the mqtt object in setup(), because the constructor parameters are not known until then.  If I move the constructor call

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

from the global namespace to inside setup(), I can no longer see it from inside loop().

I have tried declaring a pointer to mqtt in the global namespace, but don't know how to change it to point to the mqtt object that is created in setup().  How can I do this?

David

In general there is several ways to do it, none of them is the perfect one...

pointer to mqtt at global scope Adafruit_MQTT_Client * mqtt_ptr; and initialize it by mqtt_ptr = new Adafruit_MQTT_Client(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); in setup. Then you have to use arrow operator instead dot to access its methods. Or you can make an alias in loop (or whenever you need it) by Adafruit_MQTT_Client& mqtt = *mqtt_ptr; and access it in the same way as before.
returning reference to static variable created inside of function (singleton), but you have to provide parameters every time, even they're needed only for the first time. The static variable gets constructed only for the first call of function.
For esp8266 there might be available std::optional template. It's similar to pointer, but you don't have to use arrow -> operator. But there might be extraneous copy when you assign (create) it's value.
You can also extend 1. or 2. by own class to hold parameters and then return instance of Adafruit_MQTT_Client


How I Can Send the status of switch in SMS by Arduino? How I want help ,, I want send status of Switch If switch > 20 send SMS status of switch OFF and when switch <20 than mean switch ON , Don't want send the value of reading.
I use Arduino uno

If I want use multiple switch and send all status of switchs in one message.
I mean if switch1 > 20 ON and switch2 <20
I want send status of switch In one SMS
Switch1 ON
Switch2 OFF
Switch3 OFF

How I can do this??

void loop()
Switch = analogRead(S_Switch);
if (Switch > 20 )
{
Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
Serial.print("\n******************\n");
Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
delay(1000);
Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
delay(1000);
Sim900Serial.println("MY Swicth statuse is :");
Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
 Sim900Serial.print("              ");
Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
delay(5000);
Sim900Serial.println();
}

Here, Updated Code...

const int switchOneInput = A0; // Switch 1
const int switchTwoInput = A1; // Switch 2

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

void loop()
{
  int switchOneStatus = analogRead(A0);
  int switchTwoStatus = analogRead(A1);

  // When Switch 1 is OFF and Switch 2 is OFF
  if(switchOneStatus < 20 && switchTwoStatus < 20)
  {
    smsOne();
  }

  // When Switch 1 is ON and Switch 2 is OFF
  else if(switchOneStatus > 20 && switchTwoStatus < 20)
  {
    smsTwo();
  }

  // When Switch 1 is OFF and Switch 2 is ON
  else if(switchOneStatus < 20 && switchTwoStatus > 20)
  {
    smsThree();
  }

  // When Switch 1 is ON and Switch 2 is ON
  else if(switchOneStatus > 20 && switchTwoStatus > 20)
  {
    smsFour();
  }

}

void smsOne()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsTwo()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsThree()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsFour()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}


Most power efficient way to constantly save 2 kilobytes of data per second I would like to constantly save data coming from sensors (for an activity tracker) while consuming as less battery as possible (I'd like to have a 4/5 days autonomy on a 3000 mAh battery) but I can't find the best way to save about 2 kBytes/s on a memory large enough to contain several days of data.

Sensors would be read at a rate of 20 times per second and produce about 100 bytes each time.

What options do I have in order to:

store such an amount of data (hardware)?
ensure the system can work properly with required autonomy?

There are two constraints here, and I think it might back you into a corner. Size and then power.

2Kbyte/s is 2*60*60*24/1024 = 168.75Mbyte/day. This is a lot. The only readily available technology that can be used with a small microprocessor that can store this volume of data is an SD card. There are no serial EEPROM or flash chips this large, and the Arduino, as far as I know, can't deal with the NAND flash used in USB sticks and SD cards.

However, SD cards can be relatively power hungry. They draw between 5mA and 100mA when writing, typically around 30-50mA. The SD spec says the maximum is 200mA. Writing is also quite lengthy as they operate on blocks of data rather than individual cells. I've never done a full analysis of how much power they use, but it is not insignificant and much, much more than serial EEPROM or flash.

So your only choice, if you have to store that much, is to go with SD cards.

I would investigate compressing the data. Even very basic schemes can make a huge difference.


How do I interface two Arduino boards so they act as one with double the code space? Can I connect two ARDUINO UNO circuit boards in serial to increase room for more code and more functionality. For instance I wish to connect six sensors to a board. I need code for all six sensors and there is not enough space on one board. If I connect two circuit boards in serial will that provide the space and functionality to run the code for all six sensors.
If not how is this accomplished? I am a beginner with ARDUINO and I have been assigned a big task to make the ARDUINO UNO circuit boards provide six different functions using sensors such as temperature, pressure, humidity, voltage, current and possibly other functions. I am new at this.

There is no simple way to combine multiple boards into a unified system. What you will need to do is delegate certain tasks to each board and then have them communicate via SPI, I2C, or UART between a master board and each slave board in the system. The master system will then present the interface of the system as a whole via serial, wifi, console, etc.


Arduino Mega 2560 LED is dim when powered from digital output My circuit is a simple one, I am using an arduino atmega 2560.
One 5mm red LED connected in series with a 150 ohm resistor.
If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma.
So my calculations were, 5-2=3volts.
3V/150=20 mA. So I put a 150 ohm resistor.
My code to control it is the following:

int red = 48;

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

void loop() {
digitalWrite(red,HIGH);
}

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly.
When I measured the voltage between pin48 and ground I got 1.7 volts.
When connected directly to the 5V and GND the voltage between them is 4.95V.
Measuring a pin with nothing connected set at HIGH results in a 4.99V reading.
Is my board malfunctioning or have I missed something?

The pinMode() arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.


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

As a contributor to Sloeber, an Eclipse Plugin dedicated to Arduino and other micro controllers, I can tell you it's all a matter of using the correct version of gcc and provide the correct options.

Even if that might seem simple, it's not like that, so my advice is to download Sloeber and look at the build console output where we print all the statements used to fulfill the build task: you can infer a lot from that.

As Sloeber is also open source, you can also inspect how we create those build commands for the different boards and tool chains.


Bit mask first 2 bits of 16 bits for accelerometer The datasheet for the accelerometer states that:

Here is the data output from the accelerometer:

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.

I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:

int bresult=0b0011111111111111&result;
Serial.print(bresult,BIN);

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?

The variable result is of data type "long"

According to an answer, I tried:

int bresult= result<<2;
Serial.print(bresult,BIN);

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger?
The image below shows result then bresult.

Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So

int bresult= result<<2;

Since <<2 is the same as *4 the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by 0.025 (or divide by 40), you end up having to multiply by 0.00625 (or divide by 160).


Convert character to Integer while leaving encoded I have two characters, that I get by Bluetooth.
char a = SerialBT.read();
char b = SerialBT.read();

According to the Arduino Reference, decoded data stored in a char gets encoded to ASCII text.
I want to combine them in an Intenger, but the following methods don't work:
int c = a + b;

int c = (int)a + (int)b;

int c = (a - 48) + (b - 48);

and

String c;
c.setCharAt(0, a);
c.setCharAt(1, b);

Thank you

OK, so after the lengthy requests for clarifications, it appears that
you are receiving a number in ASCII decimal ("12") and want to parse
it into an integer.
You may use the parseInt() method of the serial object, like:
int c = SerialBT.parseInt();

This can however make you program quite slow, as parseInt() uses a
timeout to know when to stop expecting more digits.
If you already have read the bytes, you can combine them with simple
arithmetics:
int c = 10 * (a - '0') + (b - '0');

Note that '0' is the same as 48, only it makes more explicit the
intent of your code.


Wrong data receiving in my Arduino by bluetooth I have programmed a client-server between an Arduino and my mobile app in Android. I´m using a buetooth HC-06. For the moment is a very basic code just to turn ON/OFF a led, regulate its voltage, and receive the charge of the battery.
This is my Arduino code for receiving the message:
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(10000); // set a timer of length 10000 microseconds (or 0.01 sec - or 1Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

This is the data that I´m receiving:

It supposed that i should only receive "O" or "F". Any suggestion??
thanks in advanced,

Well, after a lot of research, it seems that my main problem was that I´m receiving and sending information at the same time. And with the library Softwareserial, only 1 can be active at the same time.
I found two solutions, but to be honest I'm not complete satisfy with neither of them. However, for my application will work.
The first solution: Is to used the HardwareSerial (pin 0,1) itself, instead of using the pin 2 and 3. When I used those, it didn't have any problem. Although I decided no to used because it help me debugging my code.
The second solution: Is to decrease the frecuency of what I´m sending. For me its ok I send the data every second. So my code would be like this:
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(1000000);
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

I have read about this library (AltSoftSerial), but I couldn't get it work. I have usde the pin 8 and 9, but nothing.


Having some trouble incrementing counters So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 && ctr > 0){
      forthMotion(stepper1.currentPosition());
    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.

The line:

int ctr = 0;

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens every time loop() is executed.

Instead making it static will change it so that it only happens the first time loop() is executed so it retains its value across successive executions of loop().

static int ctr = 0;


Why is my Arduino still working? I read an article that said that shorting an IO pin to ground would destroy the pin.  I've done this before when I connected a buzzer to an IO pin and to ground without resistors, the buzzer is only 14 ohms so the current would be quite high through the pins.  Why is my Arduino still working,  and how should I know when to use resistors or what rating to use?

The Arduino is tougher than it looks. ;-) Or maybe you were just lucky.

The exact point of failure of an IC is hard to predict, because of part
to part variations, and because it can depend on many uncontrolled
factors (duration of fault, temperature, voltages and currents on other
pins, part history...). Then, the absolute maximum ratings are not the
predicted point of failure. They are rather a lower bound:

The part should not fail if you do not exceed the ratings
it may fail anywhere beyond those limits.

Time is, however, also a factor. The manufacturer says that operating
the part close to the limits for an extended period may shorten its
lifespan.


Pin Mapping of nRF2401L01+ using Adafruit's nRF24L01+ library I have an Arduino Uno and one of these nRF24L01+ from china (see image)

To use the module i wanted to use the library provided by Adafruit (http://playground.arduino.cc/InterfacingWithHardware/Nrf2401). My problem is, that they're using different names for some pins, because the library is designed for a different module with the following pin outs.

I don't know which PIN from the China module corresponds to the DAT and DR1 Pin on the Adafruit module.

So my questions are:

Is it OK to use the library in conjunction with the china module?
What are the DAT and DR1 PIN on the module from China ?

What I know so far:
- took a look into the library and into the documentation at playground.arduino.cc/InterfacingWithHardware/Nrf2401 and found out that the DR1 pin is for the available() function to check if data is available to be read.

DR1 is MISO
DAT is MOSI

Though I'd advice using the RF24 library, as it's a lot more recent than the one from 2009 you linked to.


How to directly solder wires to protoshield to connect them to Arduino pins I bought an assembled Arduino Uno protoshield version 5, similar to this:

I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).

I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:

  Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?

For the signals, get some AWG30 wire and solder them underneath to the female header pads. For power, get some AWG22 or AWG24 wire and solder them to the top of the male header pads.


Arduino clone woks only with USB - NOT with external power I have an Arduino UNO ch430 clone. It works with USB power supply, I can upload a Sketch and it works just fine. With external power supply, doesn't work. What do I mean? No LED lights up, high pins output  ~ 0V. I'm using that barrel jack plug with 9V (6 x 1,5V batteries). Input voltage is measured OK. The AMS1117 regulator has Vin pin = Vout pin; i mean it gets no input Voltage. On the other hand, the M7F rectifier diode that comes between the jack and the regulator takes all voltage. I don't understan why, given that the anode is at higher voltage than the cathode (+9V). It shouldn't block current flow.
I tried jumping the rectifier and getting the jack +pin directly to the Vin at the regulator: current starts to flow, but apparently so much that the ams1117 heats a lot and really fast. Well i don't know why it suddendly gets so much current, I have absolutely nothing pluged to the board and I couldn't find any stain or damaged spot on it.

I can't figure out what is happening. I hope you can help me, and thanks in advance.

This is an exact (i'm pretty sure) schematic of my board.
Link

It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.

You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.

Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.


Problem reading in Arduino serial port with 5K potentiometer I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.

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

void loop() {
  int sensorValue = analogRead(A1);
  Serial.println(sensorValue);
  delay(500);
}

It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:


How to get the angle from vertical window blinds How can i know the angle of the vertical window blind by placing a small sensor on one of the blind slat

i am trying to make a arduino/esp8266 controlled window blinds, the controlling can be easily achieved in horizontal blinds, but my apartment has a vertical blind which are not interconnected at the bottom

Tried so far:

open and close based on time which it takes to open and close, but it keeps drifting over time
Cannot use light sensor to sense the ambient light, does not give correct information (day and night)
Tried to put a potentiometer on top of one of the blind slat ( no enough room to place things there, potentiometers have more friction)

any suggestions for angle sensor ?

A hall-effect sensor, plus a small magnet attached (glue?) to the outside edge of one slat ought to be able to tell you the strength of the magnetic field, and thus the distance of the magnet from the sensor. From that, given that the rotation is with a fixed radius, you can deduce the angle while introducing zero additional friction.

Edit:
I had imagined something like:

However, looking again, this introduces difficulty in detecting the 90deg position, where the magnetic flux lines are exactly parallel to the hall-effect sensor plane.

If you experiment with this enough, you may be able to get repeatable values from the sensor to know the angle of the blind slats.

Edit 2:

The timing measure you noted in your question could also be a possibility. If you could use a microswitch or photo-interrupt sensor on the extreme ends of travel (0deg and 180deg), so that any time those extreme ends are detected, you can eliminate drift.


Using Arduino libraries for adding more functionalities to a bootloader I have a short question to ask before putting time for research.

I have an Arduino Leonardo with the LUFA mass storage bootloader flashed. Now what I need to do is to add more functionalities to the bootloader. Because in the final product, the Leonardo board will be connected to a fitness machine (permanently connected) and the machine has Windows OS. Then the Leonardo should be able to read an RFID card (I need to add an RFID reader to the board, each user has his own RFID card) and then mount a remote server directory to the local USB Host based on the selected user.

I will have to use a wifi shield too. My question is this: is it theoretically possible to add all these functionalities to the LUFA mass storage bootloader? Because it's not possible to use the Arduino IDE for this purpose, since I'm not uploading any sketch on top of the bootloader, rather than editing the existing mass storage bootloader with the required functionalities and re-flash the chip. Am I correct? (This is what I understood after some research. And I'm a noob :D).

Could you please elaborate what would be the first step for solving this issue?

@Majenko: I think, that the task IS possible, but it is really hard (and Leonardo may need more memory for that eventually and some shields too and so ...) but if I understand the problem, than the Leonardo should pretends to be mass storage device for that application, and pretend it have some folders and files on it, depending which RFID is used to activate it.

The application probabelly is NOT going to format the MSD because it would lose all the user data on it.

So Leonardo can do following:

pretend it is already formatted and have some known filesystem on it (vfat is easy enought and probabelly usable as many USB flash sticks came with it)
when the machine detects inserted USB, it ask for type - so it get MSD
then it will read partition table - Leonardo can emulate it easily, having "just one partition of given size and type" the partition can even be stored as a file on that fileserver to save Leonardo's memory.
next goes reading FAT table and root directory

knowing  the user from RFID it is possible to select the right directory on file server,
then enumerate lengths of all files inside (and directories)
make table with the names and "offset"
send back the FAT as if those files were ordered on the "disk" so each entry points to the following sector, until the last marks EOF
root directory begins after FAT and contains names of the files, their lenghts, dates and starting sectors (and some very basic right like read-only, system and such)
then follows files and directories

each time the machine asks for a "sector", it is possible to compute, in which file the sector is placed, read the portion of a file (potentially fill it with zeroes to "sector lenght" and return it as requested "sector"
if the sector is in directory instead, return the part of directory (that means filenames and such)
if the sector is outside it all (should not happen), return just zeroes.

On the other direction:

if you get something outside structure, put it to temp. file along with address of such stray "sector"
if you get something in a file, just replace the file content on given offset
if you get something in directory, you need to compare it with previous version and "rename file", "create file" or "delete file" acordingly.
it would probabely need two directories on the server for each user - one for actual files, other for "lost sectors" and "deleted files" which could be "reconected", "undeleted" or "attached later" to the files/directories. The second directory can be emptied after "removing USB MSD" when user with given RFID logouts.

It is lot of work, but basically it could be done. It also needs a lot of accounting on the Leonardo and lot of communication with the fileserver, but it is possible to do.

It suppose, that the files on fileserver would not be modified by somebody else while "mounted" and that the Windows machine would not "format" the USB to some kind of filesystem, the Leonardo does not understand (how to translate to the real files on server).

But for the supposed use I think those two conditions could be reasonable. The MSD probabelly just holds the "user profile" so the machine can put in records of hir/her activiti, some stats and so on, probabely it would be just a few growing files maybe even just in root directory.

Anyway I would not like to write such system, as it is terrifying lot of work and a lot of things could go wrong, if there is a bug (or bad connection).

Also the size of required memory for Leonardo is large - probabelly larger, than the Leonardo actually have, but it could be offloaded to the filesystem too (in "hidden directory" not shown to the machine) - which would be slow and hard to manage - or expanded by HW RAM, which would be a lot faster, but needs nontrivial settings.

(Remebers me, how I wrote resident program for DOS, which had just 130 bytes, which swaped in two 16KB widows of EMS where the rest of program (actually interpret of some pseudocode) was placed (it was like 4 or 6 such 16KB pages, but was able to swap itself acordingly) while the remaining two EMS pages was reserverd for data (like 300-400KB total of pseudocode and data) which was also swapped as needed to access everything. From DOS point of view it was just the 130B resident API, from the view of program, which was using it, it was 400KB engine running FORTH-like program and containing database. The result was like 3x faster processing of 2.000+ employes wages.)

Here are the memory restrictions even more tight, but I thing, that it is possible to do such thing, only it is extremely hard to make it work reliably.


Possible to condense this if statement? I have this if statement:

if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

Is there a way to condense that for the purposes of saving on some bytes?

Ultimately trying to say "At 5:10 every weekday do X"

The following saves a couple of program bytes (but no RAM) when now is a structure with a byte called DayofWeek:

 if ((byte)(now.DayofWeek+249)>250) ...
   -vs-
 if ((now.DayofWeek != 1 && now.DayofWeek != 7)) ...

It might save slightly more than that in your case, where now.dayOfTheWeek() appears to be a function reference.  This technique will work if function now.dayOfTheWeek() returns a byte, that is, an unsigned char.  The technique depends on value 7+249 overflowing to zero in byte arithmetic when truncated to a byte, because 7+249 is 0 modulo 256.

The cast to byte [or uint8_t] of now.DayofWeek+249 is needed because of int promotion as Edgar Bonet pointed out.


ESP8266 blue led stays stays on I have found a similar qustion to mine but there was no good response.

I've connected my ESP8266 to Arduino UNO.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used AT+IPR=9600 command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.

Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.

Could anyone please help me?

Did you change the firmware? I think Baud rate can be changed only if you flash it with newer version of the firmware.


How to send characters to Arduino serial using Linux command line without tail -f? I want to send characters to Arduino serial port which makes the Arduino turn on/off an LED. Here is the code:

int led_main=8;

void setup()
{
    pinMode(led_main, OUTPUT);

    Serial.begin(9600);
}

void loop()
{
    char chr;

    if (Serial.available())
    {
        chr = Serial.read();

        if (chr == '0')
        {
            digitalWrite(led_main, LOW);
        }
        else if (chr == '1')
        {
            digitalWrite(led_main, HIGH);
        }
    }
}

The Arduino is recognized as either /dev/ttyACM0 or /dev/ttyACM1 in my system. When I run the command echo "1" > /dev/ttyACM0, it doesn't work. But, when I open a second terminal, run tail -f /dev/ttyACM0, and then in the first terminal, run echo "1" > /dev/ttyACM0, it turns on the LED as expected. So why do I have to open a second terminal and keep monitoring the output with tail -f in order for this to work? Is there a way to do this with a single command?

Arduinos have auto-reset circuit to reset the board if new connection is initiated on USB. It is good for convenient upload or to reset for debugging at Serial Monitor open. But it causes troubles if you want to communicate with MCU from computer over USB from command line tools, scripts, python, C++, C#, Java. Always on new connection the board resets.

One solution is to disable the auto-reset circuit. Other option is to wait a second after the connection while the board resets.


Driving an enable pin low via arduino I have the following V regulator, that has an enable pin that i'd like to control via an arduino:  https://www.pololu.com/product/2582

I tried using a relay (ELEGOO Relay Module 4 Channel DC 5V with Optocoupler for Arduino) with the following pins:

Relay pin1: 0v of 24v battery

Relay pin2: enable pin of pololu v regulator

I then enabled the above relay via an arduino digital out pin.

However it seemed to have no effect, the regulator never shut off.
If i manually join the two relay pins, pin1 and pin2 the regulator does shut off though ..  A and B in picture.

Any ideas why the relay is not working via the arduino?  or should it work? am i doing something wrong?  I am not too familiar with pull up or pull downs..

I have since disconnected everything and put it away, i am just looking for theory help, confirmation it should wotk.   I managed to get the relay working for leds at the time .. would the fact that current flows in the other direction for this pull down relay setup, be my issue and that i should swap around wires A and B?

(As a workaround i used a relay to switch on or enable the 24v Vin line out from the battery instead, that seemed to work okay..)

Unless you require galvanic isolation (and it's highly unlikely that you do) you don't need the relay.

The EN pin only needs to be above 1.3V to turn the unit on, or below 0.9V to turn it off. The voltage range is anything up to 30V.

Just connect the EN pin directly to an Arduino IO pin. Write a HIGH for on and a LOW for off.  And of course connect the grounds together.


ESP8266 as wifi Card? I am very new to arduino and electronics in general. Can i use the NodeMcu Esp8266 as one of those usb wifi dongles? I want to use it as a monitor mode capable wifi card, for my linux laptop.

No, you can't. All you have is a UART interface through a USB to UART adaptor. It can only ever be a UART.

The best you could get would be to write a program to run on the NodeMCU that did the monitoring for you (assuming you can get it into a suitable promiscuous mode) and report information back to you through the UART.


TQFP Atmega328pu-th cant upload sketch sync error (breadboard) So I have a USB to ftdi connected to my qtfp 32 socket trying to upload a sketch but I get a sync error , as far as I am aware I have uploaded the sketch correctly

Hey guys I managed to figure it out I had to remove the dtr pin from pin 29 , I made a video to help anyone else looking to do it, I don't know if it breeches any self promotion? But hope it helps because i found it difficult to find any resources. https://youtu.be/5CPYz6Kde7M


Help What am I doing wrong? Matrix Led I'm new and im trying out the Matrix LED
heres my code

#include <LedControl.h>

LedControl lc = LedControl(12, 11, 10, 1);

unsigned long delayime = 100;

void setup()
{
  lc.shutdown(0, false);
  lc.setIntensity(0, 8);
  lc.clearDisplay(0);
}

void writeArduinoOnMatrix()
{
  byte H[10] = {8, 8, B01100110, B01100110, B01100110, B01111110, B01111110, B01100110, B01100110, B01100110};
  byte E[10] = {8, 8, B01111110, B01111110, B01100000, B01111110, B01111110, B01100000, B01111110, B01111110};
  byte L[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};
  byte O[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};

  lc.setRow(0, 0, H[0]);
}

I keep on getting this error no matter what.
collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

Help What am I doing wrong?

Unfortunately I think you are missing the actual error message and have just copied the result.  I suspect if you scroll back up through the output it will say loop is missing.

All Arduino sketches (well almost all) have to have setup() and loop() functions.  The underlying 'stuff' will call setup() once and loop() repeatedly.

I hate global variables, but in this case I would be tempted to move those arrays out of the function and make the constant global values.  That way they will be in memory as the Arduino boots and you won't have to waste processor cycles setting them up.

It may be a silly question, but are you using the right hardware?  This might help check that http://playground.arduino.cc/Main/LedControl


Setting reading frequency SCT013 current sensor code using Arduino Uno I found this code below for the Arduino platform to obtain current measurements from the SCT013 sensor, and I am wondering how can I define the 'delay' or 'frequency' of my readings? I'd be looking for 200Hz.

Code:

//
#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance

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

  emon1.current(5, 60);             // Current: input pin, calibration.
  //calibration is explained bellow
}

void loop()
{
  double Irms = emon1.calcIrms(1480);  // Calculate Irms only

  Serial.print(Irms*230.0);        // Apparent power
  Serial.print(" ");
  Serial.println(Irms);            // Irms
}
//

you skip reading when the last read is less than 1000/200 = 5ms ago.

unsigned long lastRead;

void loop()
{
   unsigned long currentMillis = millis();
   if(currentMillis - lastRead >= 5){

      double Irms = emon1.calcIrms(1480);  // Calculate Irms only

      Serial.print(Irms*230.0);        // Apparent power
      Serial.print(" ");
      Serial.println(Irms);            // Irms
      lastRead = currentMillis;
    }

}


ESP8266 + NeoPixel - Cannot set pixel color, I got "Exception 29: StoreProhibited" I'm trying to use NeoPixel on the ESP8266.
I made simple test put all required code into setup() and loop() methods. Then, to keep everything in order I create a class LedModule which handle the led strip state, changes, etc.

Here some parts of my class

LedModule::LedModule(unsigned int numOfPixels, uint8_t dataPin)
{
    // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
    // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
    // example for more information on possible values.
    pixels = Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

    mState = LED_MODULE_STATE_IDLE;
    mIsLedStripOn = false;
}

...

// The method to set all leds of the strip to the same color
void LedModule::turnAllNeoPixelsTo(uint8_t red, uint8_t green, uint8_t blue)
{
    for (uint16_t i = 0; i < getLedCount(); i++)
    {
        // Avoid to light up the middle leds
        if (i < 5 || i > 9)
        {
            pixels.setPixelColor(i, red, green, blue);
        }
        else{
            pixels.setPixelColor(i, 0,0,0); // off
        }
    }
    pixels.show(); // This sends the updated pixel color to the hardware.
    mIsLedStripOn = true;
}

After this changes, when I call the method above, I got the exception:

Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
Decoding 15 results
0x4020ddbd: ieee80211_send_mgmt at ?? line ?
0x4020db5f: ieee80211_send_mgmt at ?? line ?
0x40102864: trc_NeedRTS at ?? line ?
0x4020fe6d: ieee80211_sta_new_state at ?? line ?
0x402101ab: ieee80211_sta_new_state at ?? line ?
0x4021060f: sta_input at ?? line ?
0x402109cb: ieee80211_parse_wmeparams at ?? line ?
0x402103ab: sta_input at ?? line ?
0x40204ce3: pp_tx_idle_timeout at ?? line ?
0x40204607: ppPeocessRxPktHdr at ?? line ?

It seems to crash during the pixels.setPixelColor(i, red, green, blue); method.

Your "constructor" isn't doing what you think.

In the example you point to you have, efectively:

Class object = Class(parameters);

Whereas in your code you have:

Class object;

object = Class(parameters);

In the first form it results in a new object constructed at declaration time. In the second it first creates a new "empty" object and then at a later date tries to copy a newly constructed object into it - which may be failing if the class doesn't support copying.

Instead you should be working with new and pointers.

In your class definition you create a pointer to your Adafruit class:

private:
    Adafruit_NeoPixel *pixels;

Then you create a new object pointing to it:

pixels = new Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

Accessing it is then done with -> instead of .:

pixels->setPixelColor(i, red, green, blue);


Servo Motors PWM pins, Arduino Uno I wanted to understand how people are connecting a servo motor to pins without PWM, so I went searching and I read that the Servo library uses the timer1 of pin 9 and pin 10 to be able to use other pins.

I would like to ask some questions about this.

Could I connect a servo motor on pin 12 by emulation of the library, and another servo on pin 9, another on pin 10 and another on pin 11 at the same time?
Or using the Servo library the PWM in pin 9 and 10 stops working?
I could then through library emulation connect one servo on pin 7, another on 8, another on 12 and another on 13 ?
4 emulations at the same time?

Have you read the Servo library page?

The library support upto 12 servos outputs. You can use any pin you want.

The library disables analogWrite() (PWM) functionality on pins 9 and 10.


How to determine minimum and maximum angle for cheap servos? I have some cheap KY66 (seems to be SG90 clone) servos.

When I turn them to 0°, the servo tries moving and moving, without actually getting to 0°. I read that they are reaching the endpoint but the built-in potentiometer does give a reading of 0.

By changing the code and fiddling with the angle, I find that the minimum for one particular servo is 25°.

I'm now trying to figure out how the Arduino could determine this value automatically. I have tried

servo.write(0);
delay(3000);
int direction = servo.read();

and expected to get back a value near 25, but it was 0 instead. So the result of read() does not seem to be an actual reading, but more the "last known" setpoint.

I've also tried to relax the servo before reading:

servo.write(0);
delay(3000);
int direction = servo.read();

with no better result.

I like to figure out the minimum and maximum angle of the servo

because I don't like the servo to make much noise (it really doesn't sound healthy)
without having the user to figure out by himself and the need of re-programming the Arduino.

I know that these cheap servos only have 3 pins. 2 pins are for power supply only, so there's only 1 pin left.

My questions:

Is the data pin uni-directional (PWM output from Arduino to servo)?
Will it ever be possible to implement what I want without additional hardware?
How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?

I think you have 2 choices: either measure and store for each one individually, or find the worst case for all of them and code around that.

Do you really need the full travel? If you're using the servo to push/pull, the servo-travel endpoints are pretty weak anyway.

  I wanted a robot look left and look right, which is 0° or 180°.

Maybe you can make up the limited angular travel of the servo in the linkage between the it and the camera platform.