Programming Questions / Capacitive Soil Moisture Sensor Good day All,
This is my first time posting to this forum and kind off my last resort as I would've liked to figure it out myself. I am trying to create a soil moisture probe which can be used on farms to determine soil moisture at different depths. The project consists of a Arduino Nano, a DIY capacitive moisture reading setup (schematic attached- My setup is the same except for the LED moisture indicator)) and an LCD screen to display the required value.
My initial setup was a Arduino Nano (328P Old Bootloader) with a resistive soil moisture sensor. However, these sensors (as they are resistive) do not give reliable readings when measuring at different spots in a field. I believe it is largely influenced by pH, salt content etc.
My next approach was to build a DIY capacitive soil moisture sensor. After searching the web I came across a setup on hackster.io ( https://www.hackster.io/Pedro52/arduino-capacitive-soil-moisture-sensor-diy-with-esp32-d7ad72 ) where a signal is sent via a ESP 32 microcontroller to a probe in the soil and a signal is returned. I implemented the same setup with the same components however I only used optimization of the timers on the Nano to generate the PWM wave (Once again this code was also obtained from another website and I am still a bit confused on how the code works).
I seem to get a reading from the sensor but the zero value seems to very volatile. Even if the wire is only picked up, the output reading changes. Is there a way to get around this and can someone please help me to get my system working optimally.
It would be highly appreciated.

 /

    /The setup uses a Chinese Arduino Nano, a 10M ohm, a 10k ohm, a 1N4007 diode and a 1 microfarrad capacitor as shown in the schematic.
    //The LED moisture indicator in the schematic can be ignored

    //#include <LiquidCrystal_I2C.h>
    //#include <LcdBarGraphRobojax.h>
    #include <Wire.h>

    //LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);
    //LcdBarGraphRobojax lbg(&lcd, 16, 0, 0);

    float Moistlevel = 0;
    float Moistpin = A1;
    float Moisture = 0;
    float RESET;
    float factor;
    const byte CLOCKOUT = 9;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  TCCR1A = bit (COM1A0);                  //Code which I obtained to initiate the onboard timer 1 to give a signal through D9
  TCCR1B = bit (WGM12) | bit (CS10);
  OCR1A =  0;                             // Apparently this should be changed for prescaling. Is it necessary?

  RESET = analogRead(Moistpin);           // Take a initial reading to zero the setup

  for (int j = 1; j < 5 ; j++)            // Take another 5 readings of which the average will be determined
  {
    RESET = RESET + analogRead(Moistpin);
    delay(200);
  };

  RESET = RESET / 6;

  Serial.print(RESET);
  Serial.println();

  Serial.print("Moistlevel");
  Serial.print("\t");
  Serial.print("\t");
  Serial.print("Moisture");
  Serial.println();
}

void loop() {

  Moistlevel = analogRead(Moistpin);                  //Take an average reading every second

  for (int i = 1; i < 5 ; i++)
  {
    Moistlevel = Moistlevel + analogRead(Moistpin);
    delay(200);
  };

  Moistlevel = Moistlevel / 6;
  Moisture = (RESET - Moistlevel) / (RESET / 100);    //Conversion to go from a voltage reading to a percentage reading

  if (Moisture < 0)                                   //Moves the initial if a negative moisture is obtained.
  {
    RESET = Moistlevel;
  };

  Moisture = (RESET - Moistlevel) / (RESET / 100);    //Obtains the new moisture value and prints it.

  Serial.println(Moistlevel);
  Serial.print("\t");
  Serial.print("\t");
  Serial.print("\t");
  Serial.print(Moisture);
  Serial.println();
  delay (500);
}

Thanks to all for the advice,
I have chosen to divert the whole system and rather make use of a 555 timer to sent a frequency to the measuring pins. It has been tested and seems to resolve the issue completely.


communication between two arduinos using ENC28J60? How can i connect and send data between two arduinos using a ENC28J60 ethernet adapters on both of them. Is there any guides or example codes for me to take a look from or any library which i can use to achieve this communication?
I have one arduino connected to an ultrasound sensor and the other to an relay module so that one arduino measures the distance between certain objects and send the distance to the other arduino which then processes it to check if it is within a certain limit if not then turn on the relay. I could have used two esp32 with one in AP mode but the range is not enough and serial communication is not possible as the cables are fragile and the distance is too large and also i couldnt find another way of sending the data.
Open to any suggestions even changing the method of communication? or using of any other ethernet modules?

You can use the EthernetENC library. See the examples of Arduino Ethernet library on how to use Ethernet libraries for Arduino.
EthernetClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. EthernetServer listens on a port. If server is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a EthernetClient object wrapping the socket. Everything you write or print to a EthernetClient is send to that one remote socket.
If the client board creates a EthernetClient and connects it to IP address and port of the EthernetServer on your 'server' board, then you get there a EthernetClient from server.available() and this two EthernetClient objects are connected. What you write/print on one side you read only from the EthernetClient object on the other side.
client socket
   if (client.connect(serverIP, PORT)) {
     client.print("request\n");
     String response = client.readStringUntil('\n');
     Serial.println(response);
     client.stop();
   }

server side
   EthernetClient client = server.available();
   if (client && client.connected()) {
     String request = client.readStringUntil('\n');
     Serial.println(request);
     client.print("response\n");
     client.stop();
   }


How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation? I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer  as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.

The magnetometer will be very difficult to use because you have no idea what the local magnetic field will look like around the user.

The gyroscope can help you keep track of angular orientation data during accelerations, but unless you know exactly how this is going to be attached to the human it will not help because you cannot orient the relative angles to the subject. A person can fall with or without rotating in the air as well, so I don't see it helping much anyway.

Kalman filters are great, but overkill; you are not doing inertial navigation over long distances, so don't bother. Simple averaging will suffice.

The accelerometer should be able to detect falls by itself. The only way it will ever "Zero out" is in freefall, and if that zeroing is long enough and then followed by a very hard acceleration against the direction of gravity (the crash) you can call it a fall. Unless the person has some kind of engine to produce thrust, or is going so fast air resistance is a factor, there will be no accelerations in the air. Simplely calibrating of the threshold for being in freefall, the time necessary to call it a fall, and the necessary strength of the following crash should be able to detect falls or jumps with almost no false positives.

For instance if you want to track short falls where the object is never fully off the ground, a large dip in acceleration data will still be seen, so just set the "zero" threshold high.


FTDI stdk 500k not responding I programming atmega328P bootloaded with an FTDI.

Some tutorial mentions that you have to connect the DTR to the reset pin:

http://electronics-diy.com/FT232RL_USB_to_Serial_Adapter_for_PIC_AVR_ATMEGA_ARDUINO_MCUs.php

Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:

 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : avrisp
         Overriding Baud Rate          : 9600
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

avrdude done.  Thank you.

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:

Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
[Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
[Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
[Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
[Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
[Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
[Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

Well my questions now are:

1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the BOARD and what should be the PROGRAMMER?

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Although I tried almost all... I think something else is wrong.

2, Should I be able to get any result with doing the previous:

 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.

Thanks

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?

See: How to make an Arduino-compatible minimal board

From that page, this is how I hooked up my FTDI cable:

And a close-up:

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.


How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port.

I am using a black pill to read RFID-rf522 to read a tag (SPI) and send it to raspberry pi through a USB (using DM and DP pins).

Quick responses are welcomed.

You can use the one provided by generating it with STMCubeMx. This is going beyond arduino though. But it is highly feasible.


Compute SHA256 of string and output to string In my Arduino project I want to compute the SHA256 hash of a string and store the result to a string, and do this recursively many times (i.e. compute hash of hash of hash etc...). So my goal is to have a reliable function as follows:

String h(String input) {
...
return output;
}

where for example h("abc") would return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".

I downloaded this library
(from Tools->Manage libraries, it is also in github) and then ran the example in TestSHA256.ino which passes all the checks. However I'm stuggling to make my function work since the library doesn't have a specific example on how to compute and return a SHA256 hash.

I have been looking in function testHash_N() in TestSHA256.ino, which appears to create a hash (from struct TestHashVector data) and compare it with the precomputed hash (from struct TestHashVector hash[]).

The hash seems to be computed in lines 89-96 in TestSHA256.ino.  I just want to take the actual hash string result, so for testVectorSHA256_1  in the example, I would need to have a string = "ba7816bf....15ad" as the result.

I understand that this is related to memory referencing in Arduino but I'm not experienced so I'd be grateful if you helped me with this.

EDIT: My code snippet so far is as follows, but it doesn't output the correct hash..

#include <Crypto.h>
#include <SHA256.h>
#include <string.h>

#define HASH_SIZE 32
#define BLOCK_SIZE 64

char hex[256];

char *hashvalue;

SHA256 sha256;

byte buffer[128];

char *btoh(char *dest, uint8_t *src, int len) {
  char *d = dest;
  while( len-- ) sprintf(d, "%02x", (unsigned char)*src++), d += 2;
  return dest;
}

char* h(Hash *hash, char* hashvalue)
{
    size_t size = sizeof(&hashvalue);
    size_t posn, len;
    size_t inc = sizeof(&hashvalue);
    uint8_t value[HASH_SIZE];

    hash->reset();
    for (posn = 0; posn < size; posn += inc) {
        len = size - posn;
        if (len > inc)
            len = inc;
        hash->update(&hashvalue + posn, len);
    }
    hash->finalize(value, sizeof(value));

    return(btoh(hex, value, 32));
}

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

    bool tmp;
    char *testvalue = "abc";
    Serial.println(h(&sha256,*testvalue));

}

void loop()
{
}

I suggest the following function. That replaces a string by its hash.
It's done in place in order to save memory. Make sure the buffer you
give it is at least 65 bytes long. Warning: not tested.

#include <Crypto.h>
#include <SHA256.h>

#define HASH_SIZE 32

SHA256 sha256;

/*
 * Replace a string by its hash, in place.
 * `data' should point to a buffer at least 65 bytes in length.
 */
hash_in_place(char *data)
{
    uint8_t value[HASH_SIZE];

    sha256.reset();
    sha256.update(data, strlen(data));
    sha256.finalize(value, sizeof(value));

    // Convert to hex into the original buffer.
    data[0] = '\0';
    for (size_t i = 0; i < HASH_SIZE; i++) {
        data += sprintf("%02x", value[i]);
    }
}


Is there a way to make wiring a bare microprocessor to a shield easier? I currently do most of my AVR work on breadboards, but the large variety of Arduino shields and code out there makes me wonder if I'm not beating my head against the wall sometimes, and looking up port to pin mappings both wastes time and slows me down. Is there any convenient way to adapt AVRs (other than those pin-compatible with current Arduinos) to Arduino shields?

You can make adapter boards (one for each mcu model).

The bottom side (male headers) would plug to the breadboard and the upper side would have female headers with the same pinout as an Arduino board (female hearers placed in the appropriate positions to match Arduino shields).

Such a board shouldn't be difficult to design.

Here is an image that resembles what I describe

It would adapt the pinout of a bare AVR to the pinout of a typical Arduino so that shields can by directly plugged on top of it.

Also a pinout diagram may come handy to speedup things when you use a bare chip with Arduino code.
(image source)

Another similar solution is a small printed sticker placed on top of the AVR
(image source)


Reserve /dev/ttyUSBx I have multiple Arduinos that I want to control using Python. My problem is that when I plug my Arduinos into the computer, they get assigned the port /dev/ttyUSBx where x increments with each one I connect.

Is there any way to reserve a certain number for a certain Arduino so that I can hard code that into the Python script? If not, can I scan the port to figure out which Arduino it is?

Yes. You need to create new unique names for them using udev rules.

By using the unique serial number, along with the VID and PID of the board you can use udev to create a symbolic link to a device name of your choice. Best to keep it to something that the Arduino IDE recognises if you want to access the link from within there for programming (otherwise you can choose what you like).

Rules are stored in /etc/udev/rules.d and take the form of .rules files with various instructions in.  One example, that should do what you want, is:

SUBSYSTEMS=="usb", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", SYMLINK+="ttyACM50", MODE="0666", GROUP="plugdev"

Of course, tweak it to your personal requirements.

Once you have crafted your rules be sure to restart udev:

sudo systemctl restart udev

or

sudo /etc/init.d/udev restart

and plug your board in.

Genuine Arduino devices usually use /dev/ttyACM* not /dev/ttyUSB*. If you have /dev/ttyUSB* then you are either on a very old device (with an FT232 chip) or a cheap Chinese clone.

If the latter then your mileage may vary somewhat.


Read function in Software Serial I have a question regarding how the read function works in Software Serial.

recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte.
For instance:
int x = rx.read(); //if the read is supposed to read 60, x prints 111100
int x = rx.read(); //if the read is supposed to read 226, x prints 11100010

How come the first statement doesn't print 00111100?

Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.

For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.


Temperature anomaly on BS18B20 + NodeMCU on Tingspeak Temperature drops occasionally from 59+C to -13C or to other random values. Used sketch and info from this site:
http://internetofthinking.blogspot.com/2016/02/upload-ds18b20-temperature-sensor-data.html

NodeMCU powered by phone charger 5v 1a via microUSB.
Placing 4.7 kOm resistor between data wire and 3v3 didn't help me.

Does anyone know how to solve this issue? Like filtering results and pushing to server only values that do not differ by more than n*C, or something like that?

Here is the sketch

#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS 2  // DS18B20 on arduino pin2 corresponds to D4 on physical board

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="-";
const char* MY_SSID = "-";
const char* MY_PWD = "-";
int sent = 0;
void setup() {
  Serial.begin(115200);
  connectWifi();
}

void loop() {
  float temp;
  //char buffer[10];
  DS18B20.requestTemperatures();
  temp = DS18B20.getTempCByIndex(0)+5;
  //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
  Serial.print(String(sent)+" Temperature: ");
  Serial.println(temp);

  //if (temp != prevTemp)
  //{
  //sendTeperatureTS(temp);
  //prevTemp = temp;
  //}

  sendTeperatureTS(temp);
  int count = myPeriodic;
  while(count--)
  delay(1000);
}

void connectWifi()
{
  Serial.print("Connecting to "+*MY_SSID);
  WiFi.begin(MY_SSID, MY_PWD);
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected");
  Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
   WiFiClient client;

   if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
   Serial.println("WiFi Client connected ");

   String postStr = apiKey;
   postStr += "&field1=";
   postStr += String(temp);
   postStr += "\r\n\r\n";

   client.print("POST /update HTTP/1.1\n");
   client.print("Host: api.thingspeak.com\n");
   client.print("Connection: close\n");
   client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
   client.print("Content-Type: application/x-www-form-urlencoded\n");
   client.print("Content-Length: ");
   client.print(postStr.length());
   client.print("\n\n");
   client.print(postStr);
   delay(1000);

   }//end if
   sent++;
 client.stop();
}//end send

Have you checked the device's Scratchpad CRC

Idk how to.

  How is your device hooked up (diagram)

Device is hooked up in normal mode, right like in this pic

DS18b20 (waterproof) is located on top of the boiler in a special pit for measuring temperatures, there are definitely no any sort of microwaves here, and the temp is not higher than 80C.
I'll try today to change the power supply, just in case, and later switch the sensor into parasite mode.


Arduino Uno Keeps Resetting (Power issue) Arduinites!

Hoping you can help a newbie. I'm putting together a board for a Christmas present this year. It's replacing the factory board that comes on a beer fridge/vending machine, with minimal interactions.

Basically, when the beer can falls into an outlet chute, it trips a switch that triggers some LEDs and audio. Pretty simple stuff. The fridge supplied +5v to the previous board, so I thought I could remove it and simply swap in the Arduino.

The code runs fine when the Arduino is powered by USB/laptop. I spliced a USB header onto the +5v wire supplied by the fridge and plugged it all in. Now, it will boot up, play some weird fuzz out of the speaker, and reset after about 10 seconds.

How can I use the +5v to power my nutty creation? The previous board had a capacitor on it which I removed (I know next to nothing about some of this stuff but it seems like maybe that would help?)

Here's a photo of what I'm working with. If I need to provide any additional information or photos I can do that.

If you have any advice, please ELI5 with regards to what I might be able to place in my circuit to get this working (links or definitions are incredibly helpful!)

Any help is appreciated!

How much current takes your board with all components? Maybe the 5V power supply can not give you the wanted current.

You can use a oscilloscope to see what is happening with the 5V when you use your board (maybe not enough current) for example interruptions on your connection or the voltage is not stable.
Maybe you can find a datasheed for the power supply for more information
try your board with another power supply to see if this is a problem of the board or the power supply

I just recognized in the third picture that the transformers output have 5V and 200mA. Your speaker will maybe have 8 Ohm (please write us the resistance). This means it will take 5V/8 Ohm this equals a current of 0,625 or 625mA. This current is 3 times higher than the output current of the transformer.

My theory 1 is:

Your circuit worked on your computers USB because you have got usb 3.0 and the max current for it is 900mA wich is much greater than 625mA and enough for leds, speaker and arduino. Your speaker is not connected directly to a pin and gnd. Some seperate electronics manages the pulses and takes directly the 5V of the USB.

My theory 2 is:
You used USB 2.0 (500mA) or USB 3.0 (900mA) and the speaker is connected directly to a pin (the resistance is ok or you added some resistance). The sound was probably not loud because the power was low. The current for both USBs were enough for leds, speaker and arduino.

Now to your problem with the resetting.

The solution:

Switch off the speaker and test your circuit without it. (I think it will work fine).

If it works: You took too much current and this current heated the pin and  influenced the charecteristics of the pin and finally the voltage at your pin (weird fuzz). Add a variable resistor in series to your speaker an try it.

If it not works: Measure the output voltage of the transformer and wirte us the value.


How to network multiple Arduinos so they react to the same signal I want to build a project that contains multiple Arduino nano's, each connected to one controlling Raspberry Pi.  I would like to send one signal (a string of characters or numbers) which would be the master state, which the other Arduinos would react to based on their programming.  What is the best way to do this?

Can the Arduino support a protocol for this, or will it need additional hardware?

Max distance: 30 meters

Rule 1 do not connect Arduino pins to long wires.

You can achieve your your goal in many ways, a serial interface looks good from here.  I am doing it with a RS485 interface, note it is an interface not a protocol. You can use CAN, Wi-fi and many others.  It sounds like all the units except 1 will be receiving data, the other is transmitting it to the other devices.  RS485 will work good and it needs only 5V.  It will work over several thousand feet and some reasonable speeds. You can use a UART either hardware or software to accomplish the task with a RS-485 driver at each node.  You need to remember you need to wire from point to point with the terminating resistors only on the end nodes.


How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor I would like to make an alarm system using ultrasonic sensor.

My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.

But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.

I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.

int echoPin = 10; // pin 10 for the echo

int trigPin = 9; // pin 9 for trigger
int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
#include <NewPing.h> // Library for improved ultrasonic sensor readings

#include <SoftwareSerial.h>

NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

int ledpin=7;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 250;           // interval at which to blink (milliseconds

void setup() {
    pinMode(ledpin,OUTPUT);
    Serial.begin(9600); //sets up serial monitor
}

void loop() {

    delay(50);

    Serial.print("Ping: ");
    Serial.print(sonar.ping_cm());
    Serial.println("cm");

    //warning
    Serial.println("cm");

    //warning
    if(sonar.ping_cm()>=30)
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledpin, ledState);
      }

    }
}

You are initiating the NewPing library with NewPing sonar(trigPin, echoPin,30);. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says

  sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from

if(sonar.ping_cm()>=30)

to

if(sonar.ping_cm()==0)


How can an Arduino output a specific (i.e. 56 kHz) carrier frequency? I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56 kHz carrier frequency for the transmitter and a second Arduino with a 56 kHz IR detector module for the receiver.

I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.

Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56 kHz pulse using the timers?

It is indeed possible to generate a 56 kHz signal with an Arduino timer.

A timer actually can be seen as a special register, in the MCU, that holds a value (starting at 0) that gets incremented at a frequency that is the MCU clock frequency (16 MHz on Arduino Uno), possibility divided by a factor called prescaler. When that value reaches a limit, called Compare Match, that you specify, then two things happen:

The timer register value is reset to 0.
One ISR (interrupt service routine) callback function gets called (you can define it to point to your own code).

The idea is to use that ISR to change the output of a logical pin every time it is called (HIGH, then LOW, then HIGH...).

Now, in order to generate a 56 kHz square wave, you'll need your ISR to be called 56000 * 2 times per second (* 2 because you need to change the output value twice per period).

You can choose the prescaler value you want for a timer among the following list:

1 (clock frequency is not divided, hence 16 MHz)
8 (clock frequency is divided by 8, hence 2 MHz)
64
256
1024

There are two sizes of timers/counters on Arduino Uno (they are called timer/counter actually): 8 bits and 16 bits.

On Arduino Uno (ATmega328P), you have three timers overall, but some may be used by the Arduino core library or other libraries used in your sketches (you'll have to check that by yourself):

timer0 (8-bit)
timer1 (16-bit)
timer2 (8-bit): this one has more prescaling options (1, 8, 32, 64, 128, 256, and 1024)

Now you need to generate a 56 kHz wave from 16 MHz, hence, without prescaling, you would need to count to:

16000000 / (56000 * 2) - 1 = 141.857 (- 1 because a timer counts from 0 to this value and resets only after it has been reached)

From this calculation, we can draw two observations:

141.857 is not an integer and thus you won't be able to generate a wave of exactly 56 kHz.
Without prescaling, you need a 16-bit timer as 285 is not representable as an 8-bit unsigned integer.

From now you have two options:

Use a 16-bit timer (timer1), use prescaler = 1, and select 142 as the Compare Match; that will give you the following frequency: 16000000 / (2 * (142 + 1)) = 55944 Hz
Use an 8-bit timer (timer0), use prescaler = 8, and select 17 as the Compare Match; that will give less precision with the following frequency: 16000000 / (8 * 2 * (17 + 1)) = 55555 Hz which is still within the required range.

Now, regarding how to write your sketch for that, I advise you to check out this instructable which is very complete and very interesting to read.

Of course, the ATmega328P complete datasheet is also important if you want to understand, in the slightest details, what you are doing.

Some important notes:

An ISR is executed with disabled interrupts and must thus be as short as possible. In particular, there are several functions from the Arduino library that shall not be called from an ISR.
Arduino Uno clock is not very accurate (it uses a ceramic resonator instead of a quartz, which would have been much more accurate), so this means the output frequency will shift further.


NodeMcu pins and an RGB LED I'm using a NodeMcu for my project and am running out of pins to use. I have a MFRC522 Module, IR Receiver, Buzzer and RGB LED connected. I am facing the problem that whenever I start scanning for RFID tags with the MFRC522 module, the onboard LED starts flashing very fast and the RGB LED changes to an undefined color.

I looked up the pin definitions of the NodeMcu, but couldn't quite find information on what pins I can use for this and which I can't, and why this only happens once I start up the RFID reader.

This is my wiring sketch:

I found this pin layout image, as well as the datasheet.

The code shouldn't be really relevant since it works before starting the RFID reader, but here is the setup of the reader, just in case:

#define SS_PIN D4   // SPI - Slave Select Pin
#define RST_PIN D2  // SPI - Reset Pin - not actually connected

MFRC522 mfrc522(SS_PIN, RST_PIN);

// Initial setup for SPI and MFRC522
bool rfidSetupCompleted = false;
void setupReader()
{
  SPI.begin();
  mfrc522.PCD_Init();
  rfidSetupCompleted = true;
}

These are the pin definitions of the RGB LED:

#define LED_BLUE D8
#define LED_GREEN D3
#define LED_RED D2

Any help is highly appreciated! I'm assuming I am using a pin that is used for other purposes (such as maybe D8), but I can't figure out which, and why. I did try to change up the pins and switched D0 and D8 (buzzer and one LED pin), but without luck. I also tried disconnecting each LED pin separately, but didn't learn anything from that either.

I fixed the issue by swapping pin D4 and D8, and then setting up the MFRC522 at the very start of the program. I originally set it up before I started using it, which caused the color to change during the first scan.


Arduino Yún shield password reset I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.

I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.

Is there any way I can reset the password?

Try connecting via ethernet to 192.168.255.1 with root/root

The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root

http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things


Arduino ds3231to TM1638 problems,alarm clock project Good morning,
I am coding an alarm clock on arduino by using a DS3231 and a TM1638.
The code works and the time updates in the serial monitor,although the time doesn't update on the tm1638.
I'll attach the code here:

#include <DS3231.h>
#include <TM1638.h>
#include <Streaming.h>
#include <SPI.h>
#include <Wire.h>
#include <InvertedTM1638.h>
#include <TM1638.h>
#include <TM1638QYF.h>
#include <TM1640.h>
#include <TM16XX.h>
#include <TM16XXFonts.h>
byte buttons;
#define TM1638_STB D5
#define TM1638_CLK D6
#define TM1638_DIO D7

TM1638 module(TM1638_DIO, TM1638_CLK, TM1638_STB);
// DS3231 uses I2C - device ID 0x68
// on Wemos mini pins SDA -> D1 and SCL -> D2
DS3231 rtc;
int hours;
int minutes;
int seconds;
bool h12;
bool PM;
int data;
RifTime t;
char buffer[24];

void setup()
{
  // set up the 7-segment display
  module.clearDisplay();
  module.setupDisplay(true, 2);
  Wire.begin();
  Serial.begin(115200);

  Serial.println(F("\nDS3231 Hi Precision Real Time Clock"));

  // Fill these variables with the date and time.
  int seconds, minutes, hours, dayofweek, dayofmonth, month, year;

  // Example for april 15, 2013, 10:08, monday is 2nd day of Week.
  // Set your own time and date in these variables.
  // dayofweek = 4; // Day of week, any day can be first, counts 1...7
  hours = 14;
  minutes = 30;
  seconds = 0;
  year = 2019;
  month = 8; // month 1...12
  dayofmonth = 28; // Day of month, 1...31

  data=( hours * 10000 + minutes * 100 + seconds * 1 );

  rtc.setClock(year,month,dayofmonth,hours,minutes,seconds);
}

void loop()
{
  rtc.getTime(t);
  Serial << rtc.toString(buffer) << endl;

  delay(1000); // do nothing

  module.setDisplayToDecNumber(data,4,false);

  if(seconds==60)
  {
    seconds=00;
    minutes++;
  }
  if(minutes==60)
  {
    minutes=0;
    hours++;
  }

  if(hours==24)
  {
    data=00000000;
  }

  if((data)==143000)
  {
    module.setLEDs(0x0001);
  }
  else
  {
    module.setLEDs(0x0000);
  }

}

You set the variable data only in the setup function.

You also do not print out data to Serial but the output of rtc.toString(buffer).

If data is not updated in the loop method, the display constantly shows the time you initially set in the setup method.


Servo doesn't move if I detach it AFER the write? So this is a bit weird, and I don't understand anything.
Basically, I'm just playing with my servo. I wrote a small program, which can be found at this link: https://pastebin.pl/view/8e9c9573 (Note: It's three files, I left some comments there, and the idk function is just my last resort, trying to separate myself from loop, I really don't know :/ ).
So I run controller.Setup() in the setup function, and then in loop I just move it to 180 and detach it, then I run into an infinite loop. Note: I know it's not very good code, but that's not what concerns me right now.
The problem is, when I add the call to detach (line 22), the previous move doesn't run! I think I'm going crazy, cause as soon as I remove the line and recompile, it actually moves.
I tried to remove the lock(Controller::m_Attached), and it still doesn't work. Please let me know if I didn't notice something, but I really don't understand.
Notes:

I'm using arduino-cli, here's my not-very-perfect Makefile: https://pastebin.pl/view/daa852ff
I use the Servo library: https://www.arduino.cc/reference/en/libraries/servo/
I'm using an Arduino Uno

EDIT:
Someone told me to post the code in the question, so here I go:
//Main.ino
#include <Servo.h>
#include "Controller.h"

Controller controller(3);

void idk();

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

void loop() {
    idk();
    while(true);
}

void idk() {
    controller.Move(180);
    controller.Unlock();
}

// Controller.h
#pragma once
#include <Servo.h>

class Controller
{
public:
    Controller(int servoPin)
        : m_ServoPin(servoPin), m_Attached(false) {}

    void Setup();
    void Move(int angle);

    void Lock();
    void Unlock();

private:
    Servo m_Servo;
    bool m_Attached;
    const int m_ServoPin = 3;
};

// Controller.ino
#include "Controller.h"

void Controller::Setup()
{
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
    Serial.print("[CONTROLLER] Attached Servo\n");
}

void Controller::Move(int angle)
{
    if (m_Attached)
        m_Servo.write(angle);
}

void Controller::Lock() {
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
}

void Controller::Unlock() {
    m_Servo.detach();
    m_Attached = false;
}

The detach() function probably stops the data pin from outputting the servo control signal.
Your code disables the control signal a few microseconds after it is enabled.
The cotrol signal is never generated.
Furthermore, a servo requires the signal to be present at all times for it to keep its position.
When your programming includes real-world events, you have to think about the time frame of the events, and about the time frame of the running program.
Think in the terms that the program can loop 100,000 times before the servo has finished moving.


Ring topology by using arduino and Bluetooth I want to connect Bluetooth in a circular ring is it possible to contect 8 arduino with each other via Bluetooth hc05 or hc06  and share data into tha ring..

Its probably possible, but I don't think it would be a good idea.

Each Arduino is going to have to forward information it receives that is not for it.  This is a drain on processing power.  Add to that you are going to need to give the devices an identity, so they know what data is for them, and a inform them of the topology of the network so they know how to connect to the adjacent nodes.

Depending on what problem you are trying to solve you might want to look at direct radio coms implementing a mesh network, or the simplest of all solutions Wifi.  You could use an ESP8266 to form an access point and others to connect to it.  I believe there might be a limit to the number of connections an ESP8266 can have at any one time but this could be mitigated by dropping the connection after the message has been sent.


ESP8266 + Arduino Uno: Can't send AT Commands I'm trying to get the ESP8266 up and running without a FTDI chip, just my Arduino Uno. But it seems really difficult. What I did:

attach the ESPs VCC directly to Arduino Uno 3.3V; RX->TX; TX->RX

Result: surprisingly worked for 2 mins, however the AT commands returned ERROR sometimes. (baud rate: 9600)

attach the ESPs VCC to 3.3V 500mA power supply; RX->TX; TX->RX

Result: AT commands don't work anymore, nothing is displayed in the serial monitor, not even my input; red LED constantly on.

attach the ESPs VCC to 3.3V 500mA power supply; TX->TX; RX->RX

Result: blue LED constantly on, no response, same as before

change back RX/TX connection, experimenting with baud rate (300 - 115200)

Result: blue LED flashes on start, flashes when something is sent (no matter what the baud rate is), however still no output at all.

Suddenly, I was also getting this error while uploading:

  ser_recv(): programmer is not responding

Detaching the TX connection solved the problem. Btw, I am also using a voltage divider between TX of the Arduino and RX of the ESP.

Afterwards, the blue LED was on constantly again, even though I haven't changed the wiring... (really weird)

To me it looks like the Arduino Serial monitor isn't sending anything, because I don't even see my input. However, the Arduino can output stuff, therefore I assume a connection between Arduino and PC is existing. Maybe it has to do with the connection between TX -> RX, but I see no shorts, just an ordinary voltage divider (100 Ohm and 200 Ohm resistors).

As you might see, I spent a lot of time trying to figure this out. I'm kind of stuck now, as I'm not sure what else to try. If you have any ideas, tips or advice please leave an answer.

Sorry for my English, it's not my native language. If you don't understand something, feel free to ask.

Hope you can help me!

Tx and Rx should be crossed; meaning connect Arduino Tx to ESP Rx and vice versa.

Your second (and first) attempts are correct. Use 1uF capacitor between Vcc and Gnd. This will provide a more
robust connection since the ESP can draw too much current which might cause it to reset.

When using external power supply, hook together the Arduino Gnd to the PS Gnd.

If you get "Programmer is not responding" - disconnect and reconnect the Arduino USB. Also, you shouldn't get this at all since you are not trying to program the Arduino, just use its FTDI as proxy to the ESP. Any serial terminal application can do it (you don't have to use the built-in terminal in Arduino IDE).


Upload of sketch with avrdude stuck only outside of IDE When uploading my sketch to my Genuino Micro with the Arduino IDE, everything works perfectly. This is the command issued:

C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
-CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
-v -patmega32u4 -cavr109 -PCOM10 -b57600 -D
-Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

All just working like it should (except that the com-port selected is actually COM6, not COM10).

But, if I try to use that exact same command from the command line, avrdude gets stuck for minutes and the arduino is still executing the sketch I've put on it.

C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/bin/avrdude
-CC:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf
-v -patmega32u4 -cavr109 -PCOM6 -b57600 -D
-Uflash:w:C:\Users\<user>\AppData\Local\Temp\arduino_build_31080/KeyboardBase.ino.hex:i

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino8/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .^C

avrdude needs to be run from cmd because I'm building a sketch with partly modified libraries, so it's built and uploaded manually with make.

I already tried running cmd as administrator, using -v -v to get more info, and changing the baud-rate, plugging the Arduino into a different USB port and restarting my machine (the same problem occurred yesterday but I didn't manage to fix it) none of that helped. What else can I try?

@per1234 was correct:

  Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it

From Arduino.cc

In practise, this means that avrdude first has to be executed like so:

$ avrdude -patmega32u4 -cavr109 -PCOM6 -b1200

Where COM6 is the same serial port the arduino is being displayed on in the Arduino IDE. The exit code of this will not be 0 and display a lot of error messages (even with -q -q), but it does exactly what it should.

After a short delay (in a makefile, use sleep 1), the Arduino will reconnect, ready to be programmed. That's when the actual programming command has to be issued:

$ avrdude -v -patmega32u4 -cavr109 -PCOM10 -b57600 -D -Uflash:w:mysketch.ino.hex:i

Notice that the serial port is now a different one! That's why the Arduino IDE actively searches for a new Arduino instead of using the same serial port set in the "Tools" menu, as I pointed out in my question.


Problem to Setting up i2c OLED wemos D1 mini shiled (64*24) Hi

I used this shield before well. But it didn't work when I wanted to work with him last night!

this is my wireing :

Now I want to know how to test that it is healthy? Is i2c address missing or not?

I tried this code to find i2c address but no answer appeared on Arduino Serial monitor !! nothing ..

and i uploaded any more example code on Uno but OLED not worked .

//     ~~~~~~~~~~~ i2c Address Scanner ~~~~~~~~~~~

#include <Wire.h>

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

while (!Serial) {}

Serial.println ();
Serial.println ("I2C scanner. Scanning ...");
byte count = 0;

Wire.begin();
for (byte i = 8; i < 120; i++){
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0){
  Serial.print ("Found address: ");
  Serial.print (i, DEC);
  Serial.print (" (0x");
  Serial.print (i, HEX);
  Serial.println (")");
  count++;
  delay (1);
   }
  }
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
  }
  void loop() {}

.
   .

What is the problem ?

The main problem is, that the module does not get any supply voltage. You connected the Unos 5V to the OLED boards 5V. But this pin doesn't seem to be connected on the OLED shield. It is marked with 5V there, because this board is a shield to be stacked onto the Wemos D1. When you do this, you have 5V on this pin from the Wemos and can access it on the OLED shield for adding further components. (This is the principle of shields. Making even unused pins available on the shield, so that these pins don't get covered by the shield)

The shield needs to be supplied through the 3.3V pin, as it is a 3.3V device and it does not have an own voltage regulator (see the schematics of the shield).

Thus the shield cannot be found, because it is not turned on. It does not have a supply voltage.

That said, you may also get into trouble because of the communication voltage. The Uno works with 5V on the I2C lines, while the OLED shield works with 3.3V. The shield might get damaged by the higher voltage. The schematics the shield don't mention part names, so I cannot know, if they are 5V tolerant (there are 2 ICs in the schematics).

If the shield is not 5V tolerant on the I2C lines, you need to use a bidirectional level converter for both lines (or you can build your own with 2 MOSFETS for each line).


MH-Z19 with Arduino null output I want to get CO2 value by using MH-Z19. I tried this code with Arduino uno R3 but I always get this result (CRC 0/0). I didn't understand where is the problem.
I linked A0 with TX of sensor and A1 with RX, I powered the card with 3.3V/Vin to visualize the result on PC via USB port.

 #include <SoftwareSerial.h>;

 SoftwareSerial mySerial(A0, A1); // A0 - к TX сенсора, A1 - к RX

 byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  unsigned char response[9];

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

 void loop()
{
mySerial.write(cmd, 9);
 memset(response, 0, 9);
 mySerial.readBytes(response, 9);

  int i;
byte crc = 0;
 for (i = 1; i < 8; i++) crc+=response[i];
 crc = 255 - crc;
 crc++;

  if ( !(response[0] == 0xFF && response[1] == 0x86 && response[8] == crc) )
 {
Serial.println("CRC error: " + String(crc) + " / "+ String(response[8]));
  } else {
unsigned int responseHigh = (unsigned int) response[2];
unsigned int responseLow = (unsigned int) response[3];
unsigned int ppm = (256*responseHigh) + responseLow;
Serial.println(ppm);
}

From the datasheet, working voltage for MH-Z19 is 3.6V to 5.5V, so 3.3V is not enough. (Although the interface runs at 3.3V).

Also, the Uno might not run reliably at 16MHz and 3.3V.

Edited image from datasheet page 303.


Arduino Yún console clear I'm having a problem. I want to clear the screen on the connected console. And after the clear, I want to rerun my code. But I can't seem to figure out how to do it. Below is some part of the code:

#include <motorStyring.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define PORT 6666
motorStyring mt;
int cm;

  YunServer server(PORT);
  const int pingPin = 9;
  int led = 13;
    void setup() {

    Serial.begin(115200);
    Bridge.begin();
    server.noListenOnLocalhost();
    server.begin();
 }
    void loop() {
    long duration, inches, cm;
    pinMode(pingPin,OUTPUT);
    digitalWrite(pingPin,LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin,LOW);
    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin,HIGH);
    cm = microsecondsToCentimeters(duration);
    h();
   }
    void h()
   {
    YunClient client = server.accept();
     if (client.connected()) {
      String question = "What would you like to drink?\nyou have 4    choises:\n1)Juice\n2)Vodca\n3)Soda\n4)Mix\n";
client.write((uint8_t*)&question[0], question.length());
String response;
while (client.connected()) {
  if (client.available()) {
    char cmd = client.read();
    if (cmd == '\n') {
      break;
    } else {
      response += String(cmd);
    }
  }
}
if (response == "juice") {
  juice();

} else if (response == "vodka") {
  vodka();

} else if (response == "soda") {
  soda();

} else if (response == "mix") {
  mix();

} else {

  String error = "you didn't select anything that corrospond to an option. \n try agin";
  client.write((uint8_t*)&error[0], error.length());
 }
   String awnser = "Here is your " + response;
   client.write((uint8_t*)&awnser[0], awnser.length());
 }
 delay(1000);
}

...

Is there a way to clear the screen on the console, so that all of the text from the previous code is not disturbing the user?

Perhaps you could count the number of lines in the console and the print out enough carriage returns ("\n") to fill it with empty whitespace.

For example, with a console with 100 lines:

for(int iter = 0; iter < 100; iter++) {
   client.write('\n');
}


What is the most accurate sensor for detecting ping pong ball? What is the most accurate proximity sensor for a ping pong ball? I will be using this to calculate 3D positioning of a ping pong ball in flight. I only need to detect the ball within 0-5 feet (basically on one side of ping pong table).

I've had some good luck with using the Pixy camera system.

http://www.cmucam.org/projects/cmucam5/wiki

You get a maximum of 50 FPS and can detect and locate different objects based on hue. The library function getBlocks() returns the X and Y center location of each of the objects the camera detects. You teach the camera what hues to recognize as blocks, and adjust the detection thresholds. I use mine in monochrome infrared light by adding a visible filter and lens kit from http://irlock.com/


Estimate soc battery and discharge time using Arduino Uno I am currently learning to do a project for estimating the soc of LiPo batteries with coulomb counting and calculating discharge time using Arduino Uno to display a warning when the battery runs out.
however, I don't even know where to start. Can anyone help provide a reference for the code and its working steps?
Thank you in advance!

Use google and enter: arduino state of charge. I got a few hits About 2,620,000 results (0.55 seconds).


On start servos rotates to 180 degree I'm testing a servo using varspeedservo.h and it rotates to 180 degree on start and then rotates back to programmed position.
Here is the code:

#include <AFMotor.h>
#include <VarSpeedServo.h>
VarSpeedServo myServo;

void setup()
{
  myServo.attach(10);
}
void loop()
{
  myServo.slowmove(0, 30);
  delay(5000);
}

You will need to open up the VarSpeedServo library source code and read through it to understand how the library actually works with your sketch.

Consider that you have not setup an initial position before issuing your first "slow moving" command.  It may be by setting an initial position before assigning a pin to the servo, you may prevent any unexpected movement.

Try something (for your code) like "myServo.wirte(0,0)" where the first argument is the position and second is the speed.


IO with port manipulation while not interfering with i2c I'm using an Attiny84 with the Tiny Core.
I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.

How can I write only to the lower 4 bits to avoid interfering with the i2c?

I don't think you need to worry. A simple piece of code:

void setup()
{
 PORTA |= bit (0);
}

void loop() { }

Generates:

00000044 <setup>:
  44:   d8 9a           sbi 0x1b, 0 ; 27
  46:   08 95           ret

In other words, the compiler generates code to set that bit, ignoring all the other bits.


'dynamic_cast' not permitted with -fno-rtti class A {
    virtual ~A();
}

class B : public A {
    public:
      int foo;
}

void bar(A *foo_){
    B* b = dynamic_cast<B*>(foo_);

    if(b != nullptr){
         cout << (*foo_)->foo << endl;
    }
}

int main(){
    B b{};
    bar(b);
}

Compiling error:

error: 'dynamic_cast' not permitted with -fno-rtti

I thank sincerely for the help.

It seems avr-gcc version 4.9.2 that is used by the Arduino IDE has been compiled without RTTI support. It defaults to -fno-rtti, and if you try turning it on with -frtti you just get other horrible linker error messages instead.

So it looks like you can't use dynamic_cast on AVR boards.

Googling around it looks like numerous people have tried to enable FTTI on Arduino, but they have either failed and given up, or they have succeeded and never bothered to tell anyone else how they did it (numerous forum posts of "how do you do this?", a bit of discussion, and then they tail off...)

The solution? Either don't use RTTI, or use a more capable microcontroller whose compiler has RTTI enabled.

One way to not use RTTI is to fake it yourself:

#define CLASS_A 1
#define CLASS_B 2

class A {
    public:
        virtual int classType() { return CLASS_A; }
};

class B : public A {
    public:
        virtual int classType() { return CLASS_B; }
        void bar() {
            Serial.println("Baaaah!");
        }
};

void foo(A *foo) {
    if (foo->classType() == CLASS_B) {
        B *foob = (B *)foo;
        foob->bar();
    } else {
        Serial.println("Sorry, I can't bar.");
    }
}

void setup() {
    Serial.begin(115200);
    A a;
    B b;
    foo(&a);
    foo(&b);
}

void loop() {
}

Output:

Sorry, I can't bar.
Baaaah!


Cannot send any UDP packets from ESP8266 Wemos D1 I am attempting to send sensor data from a battery-powered device using UDP. The goal is to send a datagram immediately after the wifi station awakes from sleep then immediately go back to sleep after writing the datagram to a given IP address or hostname.
I can send data to Thingspeak's API using their library so I know the device works, but when attempting to use the WiFiUDP library to send a datagram to an IP address on the same LAN I see nothing happen. My device is getting on the wifi and the udp.endPacket() command is returning successful, but I am not receiving the packets on the server. I know the server works because I can use nc to send UDP packets from other machines on the LAN.
Here is my sketch with the irrelevant bits redacted.
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html
#include <ESP8266WiFi.h>
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-examples.html
#include <WiFiUdp.h>

// Create udp class instance
WiFiUDP udp;

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("SSID:\t");
  Serial.println(WiFi.SSID());

  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());

  Serial.print("Gateway:\t");
  Serial.println(WiFi.gatewayIP());

  uint8_t buffer[50] = "hello world";
  char message[] = "hello world 2";

  IPAddress staticIP(192, 168, 1, 118);
  udp.beginPacket(staticIP, 3381);
  udp.write(buffer, 11);
  //udp.write(message);
  udp.endPacket();

  // Calculate required sleep time and go to sleep
  long sleepTime = measurementInterval - millis(); // in milliseconds
  if (sleepTime < 100) sleepTime = 100; // set minimum sleep of 0.1 second
  Serial.print ("Going to sleep now for ");
  Serial.print((float)sleepTime / 1000, 3);
  Serial.println (" seconds.");
  Serial.print ("Time going to sleep=");
  Serial.print ((float)millis() / 1000, 3);
  ESP.deepSleep(sleepTime * 5000); // convert to microseconds
}

And my node server just to be complete here:
const dgram = require('dgram')
const server = dgram.createSocket('udp4')

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`)
  server.close()
})

server.on('message', (msg, rinfo) => {
  console.log(`got message from ${rinfo.address}:${rinfo.port} - ${msg}`)
})

server.on('listening', () => {
  const address = server.address()
  console.log(`server listening ${address.address}:${address.port}`)
})

server.bind(3381)

I've also tried adding delays between each function to no avail.

Per the esp8266 subreddit, you need to add a sufficient delay() of 50-100 milliseconds (not microseconds) before going to sleep as none of the udp functions are blocking.


Removing CH340g chip from Arduino Nano clone.. any issues? In trying to figure out how to solve another problem with Arduino Nano clone using CH340 chip, I was just now wondering, would there be any issues if I were to simply remove the CH340 chip? As it stands, I have the slight suspicion that the chip itself might be causing some problems with communicating using only the Tx Rx pins, could this be the case? More importantly, can I just remove the chip with no issues (other than the already lacking ability to use it as USB-Serial bridge)? In a working board, would removing the chip cause any other problems?

No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.

Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.

I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.


Is there GUI to flash a sketch with new variables? I'm dabbling in a project and would like to add a feature, but I need some help from the community.

My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.

If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.

Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.

Is this a pie in the sky proposition, or something that could be implemented?

Thanks for your input.

The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.

Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.

The configuration parameters are written to EEPROM so that they will be preserved.

In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.

Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.


Problem in getting the output (language: Processing and Arduino IDE) I am working on a small project with Processing and Arduino, in which, depending upon the value of a photoresistor, it displays whether it is day/night/evening.

I read the value from the photoresistor and write the value to the serial port. Then in Processing I read the value from the serial port and display depending on the value.

But I get a very flickery output, and there is always a -1 imprinted on the screen as shown in the video.

Please help me out.

link to the video

Code for Arduino:

int ldr1 = A0;
int x,y;

void setup() {
  pinMode(ldr1,INPUT);
  Serial.begin(9600);
}

void loop() {
  x = analogRead(ldr1);
  Serial.write(x);
  delay(100);
}

Code for Processing:

import processing.serial.*;
Serial port;
int x,y;

void setup() {
  size(640, 320);
  port = new Serial(this, "COM3", 9600);
}

void draw() {
  background(0);
  x = port.read();
  text(x,100,100);
  if(x < 400 && x > 200) {
    textSize(32);
    fill(0,0,255);
    text("it is evening",200,200);
  }
  if(x < 200 && x > 20) {
    textSize(32);
    fill(0,255,0);
    text("it is night",200,200);
  }
  if(x > 400 && x < 900) {
    textSize(32);
    fill(255,0,0);
    text("it is morning",200,200);
  }
}

If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial_read_.html

it says:
"Returns a number between 0 and 255 for the next byte that's waiting in the buffer. Returns -1 if there is no byte, although this should be avoided by first cheacking available() to see if data is available."

Either before calling "Draw" function, or inside "Draw", you should first check:

if(port.available()){
  //do your checking for X value and set text as you are doing before

}

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.

You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.

  int val = analogRead(ldr1);
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val); //now you will not lose information

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.


Problem with using pure C code to program default UART (UART0) in Arduino Mega Can I code default serial port in Arduino Mega (USART0, I assume) in pure C? I mean to set up it and configure directly by ATmega's registers?

I'm asking because I'm trying to do it and I have a problem. Below is code which I use and Arduino doesn't transfer anything...

#include <avr/io.h>

#define F_CPU 16000000
#define BAUD_RATE 9600
#define MY_UBRR (F_CPU+BAUD_RATE*8UL)/(16UL*BAUD_RATE)-1

void setup() {

    UART_Init(MY_UBRR);
}

void loop() {
    UART_Transmit('a');

 }

void UART_Init(unsigned char ubrr)
{
   UBRR0H = (unsigned char)(ubrr >> 8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (1<<USBS0) | (1<<UCSZ00);
}

 void UART_Transmit(unsigned char data)
 {
    while(!(UCSR0A & (1<<UDRE0)))
    UDR0 = data;
 }

That code I created following the datasheet for ATmega 2560. It has been compiled and programmed but doesn't work at all...

Please give me any advice. It's important for me use just C code in that case.

I suggest to use existing code and copy that or use that.

This is the Arduino HardwareSerial : HardwareSerial.cpp
You can find more code at avrfreaks.net. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.

The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?


Random(0,2) gives bad results All I need to do is generate a random integer between 0 and 3 for example.
I am using this function:

void Crossover(int parents[2][3])
{
  int ranDpart;
  int ranDparent;
  for(int i=0; i<10; i++)
  {
    for(int j=0; i<3; j++)
    {
      ranDpart = random(0,3);
      ranDparent = random(0,2);
      newGen[i][j] = parents[ranDparent][ranDpart];
    }
  }
}

where as you see parents is input with size of 2x3 and newGen is 10x3 2D array. As seen here in the code, this function is supposed to randomly take one of parent and a part of this parent to make a new "child". Am I doing something wrong? I think that random gives me bad results. I tried some online compiler and random gives me numbers like "1804289383" even if I tried to make it long. Can you guys help me with random int?

stdlib.h defines a few psuedo-random number functions. I am not familiar with a random function taking two arguments, presumably the low and high end of the desired range, that you've specified in your code.

For what it's worth, in plain old C use the modulo operator to achieve the range you want using stdlib's srand and rand functions:

/* seed psuedo-random number generator during setup with something */
srand(0xdeadbeef);

and in your function simply use modulus to get your range:

int ranDpart = rand() % 3; /* range: 0,1,2 */
int ranDparent = rand() % 2; /* range: 0,1 */

If your ranges should be inclusive e.g. [0,3] and [0,2] then

int ranDpart = rand() % 4; /* 0,1,2,3 */
int ranDparent = rand() % 3; /* 0,1,2 */


16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter I'm using Adafruit 16-Channel 12-bit PWM/Servo Shield with Arduino Uno controller

In setup() I have a number of default positions with PWM commands for motors with plug of USB to PC and turning on

I'm trying to figure out, how to avoid setup() commands, or any other signals during process to servos, in case if shield is not powered from power adapter, which is 6V 8Amp in my case, to not send signal to servo while it is not powered by power supply

I would propose a circuit like the following:

simulate this circuit – Schematic created using CircuitLab

The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a digitalRead() on the corresponding digital input pin of your Arduino, to check, if the power was applied.

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.


How big of a difference is there between an Arduino Uno and the rest? Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it built for the Teensy 2.0. On the page for the Teensy 2.0 there is a link for an Arduino Library for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be

#if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
 #define __AVR_AT90USBX2__
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
 #define __AVR_AT90USBX6__
#else
 #error "Unsupported device"
#endif

Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys.

What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.

That program will make the arduino board act like a keyboard to the PC it's plugged in. This can't be done on the Uno, since it doesn't have USB support.


Delay() is not working outside of interrupt Delay() doesn't work inside ISR routines, but here I have used it in loop and outside interrupt section still Delay is not working, however there isn't any error coming. What is wrong?

int L = 2;
volatile int done0=0;                                //ISR variables
void recordL();                                              //ISR 1

void setup() {
Serial.begin(9600);
Serial.println("Start");

pinMode(L,INPUT);
}

void loop() {

interrupts();
attachInterrupt(0,recordL,RISING);
done0=0;

while(!done0)
{
    Serial.println(millis());
}
noInterrupts();

Serial.println("Detected");
delay(5000);
Serial.println("After Delay");
}

void recordL()
{
  Serial.println("in Interrupt0");
  done0=1;
}

Do I need interrupts() noInterrupts() in the loop section?

Yes, you do. Always.

The optimal workflow is

In the ISR itself, just raise a flag or directly change some global
variable.
In the loop you first copy that flag/variable to a local variable, using interrupts/noInterrupts to prevent the ISR changing the value while you are using/copying it.

Assignment are not atomic in Arduino World. That means that the value you are copying can change while you are doing it, and you end with garbage in your variables. Or, worse, it can change between one statement and the next. Try to debug that.

This is how you do it. In this example, I'm using an interrupt to manage a button (with debouncing). I need to detect state (pressed/not pressed) and timing (how long you pressed it). I can't directly use lastFallingEdge in loop; I copy it first so it won't change while I'm using it.

volatile unsigned long lastFallingEdge = 0; // For debouncing.
volatile boolean bPressed = false;

void buttonInterrupt(void)
{
    lastFallingEdge = millis();
    bPressed = true;
}

void loop()
{

    if(bPressed) {
        noInterrupts();
        bPressed = false;
        unsigned long falling = lastFallingEdge;
        interrupts();
        unsigned long len = millis() - falling;

        // Do something.
    }
}


Arduino FM transmitter I am wondering if it's possible to transmit on all frequencies at once using this module.

I know it's illegal to take over regular stations when others are trying to listen but I'm only planning to use it for short range (less than the length of my house).

No, this is a receiver only, not a transmitter.


invalid conversion from 'const char*' to 'char*' [-fpermissive] With WebSocket various messages arrive.
Task:

Find message "setBrightness: 15"
Extract the value "15" from the message (the value can be any)
Convert this value to uint8_t

My code:
#include <string.h>

String payload_str = "setBrightness: 15"; // WebSocket message
const char* payload = payload_str.c_str(); // Convert string to char

const char* value; // Message value
uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   value = strtok(payload, " ");
   value = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t)atoi(value); // Convert to uint8_t
  }
}

void loop() {}

Compilling error:

error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
error:   initializing argument 1 of 'char* strtok(char*, const char*)' [-fpermissive]

Maybe I'm doing it completely wrong and not safe. How can this be fixed?

strtok modifies the char buffer entered as first parameter. It replaces the delimiters with terminating zeros. To parse a constant string with strtok, you must first copy it into a working char buffer.

For your test you can initialize a char array as in following example.

char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   strtok(payload, " ");
   const char* tok = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t) atoi(tok); // Convert to uint8_t
  }
}

void loop() {}

if you know the 'name' part of the name:value string, you can skip it for atoi this way:

brightness = (uint8_t) atoi(payload + strlen("setBrightness: "));

(strlen("setBrightness: " will be evaluated at compile time to a constant number)

const char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
     brightness = (uint8_t) atoi(payload + strlen("setBrightness: ")); // Convert to uint8_t
  }
}

void loop() {}


How to find out whether an arduino can control a servo motor I have a servo motor with following specs
Torque - 1.08Nm
Max rpm - 3000
Current rating - 7.8 amp
Max voltage - 56V DC

Please tell me how to calculate whether an arduino board - uno rev 3 can control the servo motor? If not, how to find out how many such boards are required?

An Uno most definitely cannot directly control that motor. According to the specs here,

  They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA

So your motor has needs about ten times the voltage and 200 times the amps that the Uno can supply. Of course, you can always get a driver of some sort for the servo.


Multithreading Leds and Joystick I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that?

One way to do this is to use the millis() function.

millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).

This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.

A function ToggleLED(n) is assumed which toggles the specified LED n from 1->0 or 0->1  as required.

LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...

The two loops are essentially independent.

unsigned long delay1; delay2;

void setup(){

int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

delay1 = millis() + FlashTime1;  / Init LED timers
delay2 = millis() + Flashtime2;
}

void loop()
{
  if (millis() == delay1){ / Not until delay expired.

    ToggleLED(1);
    delay1= millis() + FlashTime1; / Reinit flash timer}

  if (millis() == delay2){

       ToggleLED(2);
       delay2= millis() + FlashTime2;}

}


Wrong Mouse.move() output in Arduino Leonardo I'm using my Arduino Leonardo as a Mouse but I'm experimenting a strange behaviour.
I put my mouse at (-1, -1) (absolute) coordinates and then I execute this code:

Move.move(com[curr_cmd_id].x, com[curr_cmd_id].y, 0);

where that point is (334, 180) (relative coords) (and I checked it through Serial console)

Now, the pointer is actually moving to the right but then it stops. Let's say it reaches the point (334, 0).

Then I tried:

Mouse.move(com[curr_cmd_id].x, 0, 0);
delay(500);
Mouse.move(0, com[curr_cmd_id].y, 0);

but still the same behaviour.

Then finally I tried this one (which it actually solves my problem but it's a dirty solution):

int i;
for(i=0; i<com[curr_cmd_id].x; i++){
  Mouse.move(1,0,0);
  delay(1);
}
for(i=0; i<com[curr_cmd_id].y; i++){
  Mouse.move(0,1,0);
  delay(1);
}

Could anybody help me in understanding what's going on here? How can I achieve a simple and direct relative movement for my pointer?
Thanks you in advance!!

I struggled with this too until I realized this

  Parameters

  xVal: amount to move along the x-axis - signed char

  yVal: amount to move along the y-axis - signed char

  wheel: amount to move scroll wheel - signed char

Note it says signed char.

That means the value you pass to the Mouse.move is a signed 8-bit. (-128 to 127)

My work around is this below:

void moveMouse(int x, int y, int w){
  x = (int)x / 1.59; //Adjust these two values accordingly. I found out that 100, 100 does
  y = (int)y / 1.58; //not move 100, 100. It moves 159, 158 for me.

  while(x!=0 || y!=0 || w!=0){
    int moveX, moveY, moveW;
    if(x > 0){
      if(x >= 100){
        moveX = 100;
      }else{
        moveX = x;
      }
    }else if (x < 0){
      if(x <= -100){
        moveX = -100;
      }else{
        moveX = x;
      }
    }else{
      moveX = 0;
    }

    if(y > 0){
      if(y >= 100){
        moveY = 100;
      }else{
        moveY = y;
      }
    }else if (y < 0){
      if(y <= -100){
        moveY = -100;
      }else{
        moveY = y;
      }
    }else{
      moveY = 0;
    }

    if(w > 0){
      if(w >= 127){
        moveW = 127;
      }else{
        moveW = w;
      }
    }else if (w < 0){
      if(w <= -128){
        moveW = -128;
      }else{
        moveW = w;
      }
    }else{
      moveW = 0;
    }

    x = x - moveX;
    y = y - moveY;
    w = w - moveW;

    Mouse.move(moveX, moveY, moveW);
  }


GPS detecting stationary? can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,

uint8_t speedZero() {
uint8_t spd = gps.speed.mph();
  if (spd < 5) {
    return 0;
  } else {
    return spd;
  }
}

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

I found this to get me started.

http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/


MCU fuses used by Pro Mini and ATMega 2560 and power down In context of Pro Mini and ATMega2560

Fuses, as documented in chip factory doc are complex topics (I have not really used it before), appreciate pointers and advises, to narrow down those that are needed for contexted task and left un-needed in their default modes.

Which fuses are used within context of the IDE in general, and in specific of software loading via bootloader and ISP?

Which fuses related to sleep and power down modes, in context that individual chip modules can be set to various power-saving modes via registers. Does fuses play a part in getting the power-saving effect?

Many thanks in advance

The data sheets are the ultimate source. However, that may be a bit overwhelming. I find the below great resources very helpful.

1) Online Fuse Calculator There are many others.

2) avrdude-GUI
there are many others out there.

3) the .\arduino-1.5.7\hardware\arduino\avr\boards.txt

uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05

4) I also read the fuses from any device before I stomp over them. And check into what each mean.

As for narrowing down the features the Online Calculator very helpful to start with and then read into the data sheet for ones of interest.

For the most part there have several questions and answers for low power modes, using interrupts to re-awake. Where there appears to no direct fuses to save power, outside of clock source and speed. Arguably Brown Out detect is a fuse, but that is not directly related to saving power.


Servo issue, won't go into negative range I'm trying to create a small laser "turret" with x-axis control. The arduino receives input through IR sensor. I'm having a problem where my servo will preform my up and reset function(moves and prints as intended), but When i preform the down function the servo does not move. I believe the function is executing (it outputs angle to LCD and text to serial monitor) but there is no movement.
Any help would be greatly appreciated!

#include <IRremote.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

int IRPIN = 3;
int angle = 0;
int test = 0;
IRrecv irrecv(IRPIN);
decode_results results;
Servo spinnything;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup()
{
    irrecv.enableIRIn();
    lcd.begin(16, 2);
    lcd.backlight();
    spinnything.attach(5);
    spinnything.write(angle);
    lcd.setCursor(0, 0);
    lcd.print("WARNING");
    lcd.setCursor(2, 1);
    lcd.print("!!!LASER!!!");
    delay(1500);
    lcd.clear();
}

void loop()
{
    if (irrecv.decode(&results)) {
        irrecv.resume();
    }
    if (results.value == 0xE172C837) {
        up();
        results.value = 0x00000000;
    }
    if (results.value == 0xE17228D7) {
        down();
        results.value = 0x00000000;
    }if (results.value == 0xE1724CB3) {
        reset();
        results.value = 0x00000000;
    }
    lcd.setCursor(0,0);
    delay(10);
}

void up() {
    if (angle < 180) {
        angle = angle + 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("up");
    }
}
void down() {
    if (angle > -180) {
        angle = angle - 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("down");
    }
}
int reset() {
    angle = 0;
    spinnything.write(angle);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Current Angle");
    lcd.setCursor(3, 1);
    lcd.print("=");
    lcd.setCursor(5, 1);
    lcd.print(angle);
    Serial.print("reset");

}

First of all Servo.write(int) takes a value ranging from 0 to 180 degrees.
Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing Servo.write(0) the servo would rotate all the way to one side, doing Servo.write(180) it should go to the other side, doing Servo.write(90) it should stay in the middle.

Also, lcd.setCursor(5, 1); is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do lcd.print("= "); if you want an additional space between the equals symbol and the number


Can I use this replacement motor without modifying the circuit? I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:

This is the old (broken) motor: https://www.sparkfun.com/products/11696. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA).

The new motor that I'd like to use is part of this kit: https://www.sparkfun.com/products/12866. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA).

I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.

Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?

Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".

However, be careful that there is another important value in motor datasheets: the stall current.

Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.

The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).

Your replacement motor has 1A according to the link you provided.

These 200mA can make a big difference for the transistor used in your circuit, a P2N2222A.

Indeed, that transistor is specified to switch a maximum of 600mA current at the collector.

So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.

Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)

So my answer is:

you can do it for a simple experiment with no load on the motor
if you really want to do something with the motor, take another transistor with a higher Ic current


NRF24L01+ how much supply ripple is acceptable? I'm trying to get a simple TX/RX pair to work. I've got identical Nanos and I'm using the example from:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

I followed the advice about adding a cap across the Vcc GND on the nrf board, and added a 10uF electrolytic to both.

I still haven't received a packet yet, and I wondering how to eliminate the power supply as a cause. I scoped the power pins, and even without a cap I got about 250mV of ripple. With the cap it goes down to about 100mV. Is this within tolerance? What kind of caps does anyone else use, and has anyone scoped the result to see where the threshold lies?

Aside form that, are there any other clever ways to debug this issue?

Update 20160122. I finally tested using those cheap piggyback 3.3v regulator boards that plug straight into the nrf board. Works perfectly, not one lost packet over 5000 packets sent. Interestingly, the RX side appears to be the fussy one. Thanks to everyones' suggestions. For a total combined cost of about 4$ per node, I have a great wireless TX/RX solution.

I would suggest using a different power supply, that appears to be your problem.  250mV is 1/4 of a volt, that is a lot of noise/ripple.  I am assuming it is ripple from the AC mains.  The series resister is way to large, try something about 0.1 ohm.  Also put a filter cap on the load side of the resister.  If you have high frequency noise add a 0.01 cap that will help.  Be sure the grounds between the units are solid.

Gil

I have a feeling it is narrow fast rising spikes.  If so the odds are very high it is the power supply.  Can you try an analog one and see if the problem goes away?  Try adding more bulk capacitance, at the rate of at least 1000uF per amp.


I2C communication between Attiny85 as master and arduino UNO as slave I want to make my Attiny85 and my Arduino UNO communicate together with I2C protocol. Since Attiny do not support Wire library, I use TinyWire by lucullusTheOnly and Wire on the Uno.

The Attiny is sending data as the master to the Uno, the slave.

Here is my code:

Master

#include <TinyWire.h>

byte slave_address = 10;

void setup() {
    // config TinyWire library for I2C master functionality
    TinyWire.begin();
}

void loop() {
    TinyWire.beginTransmission(slave_address);
    TinyWire.send('c');
    // endTransmission sends the bytes in the buffer to the slave and returns 0 if there was no error
    TinyWire.endTransmission();
    delay(500);
}

Slave

#include <Wire.h>

void setup() {
  Wire.begin(10);                // join i2c bus with address #10
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

I connect the pin like this :

Arduino --> Attiny
SCL ---- PIN 7
SDA ---- PIN 5

I try to pull-up the clock and data line with 2.2k resistors but nothing happened, I receive nothing on the Uno from the Attiny.
Any idea ? Thanks !

The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the endTransmission() function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)

I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.

Chrisl aka lucullusTheOnly

EDIT: I had to think about this and looked into the library. The problem was found easily. In twi.cpp there is a NOISE_TESTING define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.

I have deactivated the NOISE_TESTING in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of NOISE_TESTING.


Arduino digital pin input used to power device? I am attempting to debug a W65C02 and I am using an Arduino Mega to look at the inputs and outputs of the device, which is behaving weird.

I have Pin 22 to 52 connected as INPUT on the MEGA and they are all connected to A0-A15 and D0-D7 on the 6502. However when I unplug my Arduino and keep the 6502 powered on it seems to stay on in that the power light is on. Is something fried or is this normal behavior?

Nothing else is plugged in to the Arduino except GND and the digital inputs.

Arduino get the power from the port of 6502 via the protecting diod in the Arduino port. This the normal behavior.
// Mikael


Lowest voltage applicable on AREF pin on Uno and Mega I need to measure an Analog signal in the range of 5-30 mV.

Naturally, using the internal default 5V reference leads to very poor measurement resolution. I would like to use the capability to use an external reference voltage of 50mV on the AREF pin (using an Agilent precision power supply)

However, when I tried this in the lab, I noticed something strange. The ADC readout on the channel remained stuck at 1023. If I used anything above 0.5V on the AREF pin, the readout on the ADC is correct, and the counts reliably go up and down when I ramp up and down the Analog input accordingly.

Any idea how to resolve my issue?

According to the datasheet (page 375) the minimum voltage you are allowed to have as a reference voltage for the ADC is 1V.


How to import my own library or file? I have some small functions to format numbers. I move them to a new file and I would like to import it to my proyect.

I can't find how to do it without defining a class (maybe it's the only way). I would like to import like JavaScript, PHP or other languages: just using the import word or something similar.

I know how to import libraries. Example:

#include <OneWire.h>
#include <DallasTemperature.h>

If the file is in your sketch folder then you use this syntax:

#include "foo.h"

All source files in the root of the sketch folder are shown as tabs in the Arduino IDE. In some cases that might not be desirable. If so, you can put the file in the src subfolder of your sketch folder and use this syntax:

#include "src/foo.h"

Or you might want to group files together into separate subfolders:

#include "src/foo/foo.h"

If you want to access the file from multiple sketches then you should turn it into a library and use this syntax:

#include <foo.h>


Using a analog multiplexer to use 9 serial input sensors? I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.

EDIT: It's a Temperature and Relative Humidity Sensor

No. Not unless you can change your communication protocol to be a "call-and-response" protocol.

Basically, the problem is this: when do you switch to which serial device? Unless all the devices have their timing synchronised there is no way of knowing - so how do you control your analogue multiplexer in that situation...?  You can't.

You would need to have some method of the master switching the multiplexer to a specific peripheral, then send a message to that peripheral saying "Send me your data now".

You would be better off investigating other boards with more UART ports, such as the Mega2560, and having multiple boards.

The Mega2560 has 4 UART ports. You can have 4 sensors per board (5, if you want to use SoftwareSerial or, better, AltSoftSerial), so you could get away with two boards.

One board acts as normal, communicating on the UART ports to 4 sensors, and also acts as an I2C or SPI master (the choice is yours). The second board communicates to 4 more sensors on UARTs and one further on using AltSoftSerial etc. It also acts as an I2C or SPI slave device.

The "slave" board just runs autonomously gathering data from the sensors it is directly connected to and storing those values.  The "master" then periodically asks the "slave" board for the latest data.