Attiny13 project with leds and electret microphone I want to make a project similar to this Turn Signal Biking Jacket

.

But, instead of using Arduino Lilypad I want to use an 8 pin attiny13A-SH and want to use one electret microphone instead of the buttons.

I want to use led's only for the left, right and a stop indicator(on the back, i don't want the leds on the sides like the instructable project).

According to me, the leds require 1 pin each and will share a common gnd(that's 4 pins).

The microphone will require 1 additional pin, with 1 going to the gnd (5 pins).

And I might require 2 pins for the power outlet (6 pins out of 8).

Now, i am a newbie in all this stuff so i don't want to go about experimenting with the chips. I am ready to disable the reset pin cause i wont require the chip again. I have got a couple of instructable's to help me in the programming and set-up plan(though they have used Arduino Uno or Lilypad), so I only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.

Also, as an alternative, i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc(i just want 6 leds on each side). I'm extremely sorry for my horrible drawing(First time and no correct tools. used paint!)
ANY HELP IS APPRECIATED.

want to use 1 electret microphone instead of the buttons.

In what way do you want to use the microphone? You do realise, don't you, that an Arduino can't understand speech (or much of anything really) without powerful extra hardware? A microphone by itself is pretty much useless, especially without any form of preamp and signal conditioning.

  i only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.

No, it's not possible. You will require lots more parts. You can't just take an arbitrary chip and connect it to a battery and expect it to work properly. You need to consider correct supply voltages (voltage regulation or boosting depending on your power source), decoupling capacitors, drive circuitry, amplification, signal processing, etc...

  i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc

Again, no.  Those are 12V LED strips. You need both a 12V supply (and the associated regulation down to 5V to power the ATTiny etc) and MOSFETs (or something similar) to allow the ATTiny to switch that 12V to the LED strips as needed.


GSM SIM900A SMS content not displaying I am trying to read messages sent from my mobile to a GSM SIM900A module on my Arduino Serial monitor. Neither does the AT+CMGR command nor does the AT+CMGL command display SMS content. I also tried increasing the receiver buffer size in the SoftwareSerial Library but to no avail. I am simply trying to read 'check123'. I want to further store the SMS received as a string for further processing. But I am stuck with no display of SMS content on the serial monitor.

My code is:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
String content = "";
char character;
int i;

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

void loop() {
  ReceiveSMS();
  delay(2000);
}

void ReceiveSMS() {
  mySerial.println("AT+CMGF=1");
  delay(2000);
  toSerial();
  mySerial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
  delay(2000);
  toSerial();
  mySerial.println("AT+CMGL=\"ALL\"\r");
  delay(5000);
  toSerial();
  mySerial.println("AT+CMGD=1,4");
  delay(2000);
  toSerial();
}

void toSerial() {
  while (mySerial.available() != 0) {
    Serial.write(mySerial.read());
  }
}

Output is:

Edit:

SoftwareSerial.cpp file. I have marked the area where I have changed the value from 64 to 256 according to some previous help post.

Your code is absolutely correct. As I tested it with my Mega with Serial3 connected to GSM SIM900. I think there is something fishy about SoftwareSerial. Double-check the location of SoftwareSerial.

  C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial\src

Maybe you can see if RAM usage is exceeding the safe limit. Here is my output:


Convert string plus hexadecimals to array of hex: I have a string which I send to the arduino using serial monitor. Something like that:

my specific string 0x0F 0x2C 0x98 0xBC

How can I parse this string in the arduino to get an array of hex values:

0x0F 0x2C 0x98 0xBD

? There are two prerequisites:

All hexadecimal starts with #
The size of hexadecimal is 2. No 0x111 or '0xbbb'

How can I parse this string in the arduino to get an array of hex values:

There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:

char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];

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

  char* bp = buf;
  int i = 0;
  do {
    char* ep;
    val[i] = strtol(bp, &ep, 16);
    Serial.println(val[i], HEX);
    bp = ep;
    i += 1;
  } while (*bp != 0);
}

void loop()
{
}

Cheers!


Do I need a lot of Arduinos? I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01.

Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?

One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.

Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.


How to modify values inside a file I am writing a wav file to an SD card on a ESP32 and that requires that every time I append data to the the end of the file I modify the header to set the right size in some fields.

I cannot find how to replace a value inside a file, I tried to write the new values with the seek function but unless I'm missing something looks like this deletes everything after the new value added.

I do not want to create a new file and to delete the old one as I will storing potentially large wav files and looks like wasting resources.

Is there a way to overwrite one value inside a file. I'm using SDlib but I'm open to others too.

Here the code I use to create the file and to update it:

#include "WavFileWriter.h"

void WavFileWriter::createFile(char const* filename, WavFileHeader* wavFileHeader)
{
  byte headerBuffer[44];
  wavFileHeader->getHeaderData(headerBuffer);
  File file = SD.open(filename, FILE_WRITE);
  file.write(headerBuffer, 44);
  file.close();
}

void WavFileWriter::appendData(char const* filename, WavFileHeader* wavFileHeader, byte* data, int dataLength)
{
  File file = SD.open(filename, FILE_WRITE);
  file.write(data, dataLength);

  byte headerBuffer[44];
  wavFileHeader->setFileSize(file.size());
  wavFileHeader->getHeaderData(headerBuffer);

  file.seek(0);
  file.write(headerBuffer, 44);
  file.close();
}

After calling appendData I end up with a file with just the header size (with the right header for a file with data but the data is gone).

The FILE_WRITE in SD library is 'append' (for historical reasons)

#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

so use

 File file = SD.open(filename, O_WRITE);


REST API on Industrial 101 (Yún family) lags, then crashes I have tried to set up a very simple REST API on an Arduino Industrial 101 (which is, as far as I understand, equivalent to a Yún). The Arduino is hooked up to a temperature sensor, which value is returned over the REST interface. Everything works fine at first, but over the course of a day it starts taking longer and longer for the device to respond until it completely crashes and becomes unresponsive. (At that point it also doesn't respond to ping and ssh anymore.)

On the Arduino forum there are several threads reporting similar problems (e.g. this one) but they all seem to be at least a few years old and have been solved in the mean time. (The solution reported here, for instance, has already been incorporated in my Linino version.)

If I reset the ATMega the problem persists, but if I reboot the OS it is solved for a day, so I have reason to suspect something on the Linino side is not working properly. Any help would be much appreciated, although I realize this is quite an old board.

My sketch is basically a dumbed-down version of the Bridge example:

#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  BridgeClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

void process(BridgeClient client) {
  // no matter what the command is, return value on A1 sampled 4096 times

  int pin = 1;
  float val = 0;
  for (int i = 0; i < 4096; i++){
    val += float(analogRead(pin))/4096.0;
  }
  client.println(val*5.0/1024.0, 5); //multiply by 5/1024 to get volts

}

First of all you should try changing the delay(50);. Try using millis(); instead and see if the problem still persists.

int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

If that doesn't help, try adding the yield(); method after the delay(50); / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.

My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.


Set computer time on arduino uno How to set computer time on Arduino Uno, and then control it (Arduino) with Serial monitor. For example show time on LCD.

I have no idea, how to make it using Arduino IDE. So, maybe I can write code in IDE, then load on Arduino. And with some script run Serial monitor also sending current time?

P.S. I have no additional boards like RTC or Ethernet.

A good place to start would be the "TimeSerial" sketch that comes with the Arduino Time library: https://playground.arduino.cc/Code/Time.


Arduino MEGA2560 wake up using DS3231 RTC I am trying to set the Arduino MEGA 2560 R3 into sleep mode and wake it up with an RTC DS3231 via interrupt. I was following this tutorial:
Tutorial

One of the libraries included is the "LowPower" library, you can find it here on GitHub. It produces the following error while compiling:

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp: In member function 'void LowPowerClass::idle(period_t, adc_t, timer5_t, timer4_t, timer3_t, timer2_t, timer1_t, timer0_t, spi_t, usart3_t, usart2_t, usart1_t, usart0_t, twi_t)':

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:562:49: error: 'power_usart3_disable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_disable();

                                                 ^

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:597:48: error: 'power_usart3_enable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_enable();

                                                ^

exit status 1
Error while compiling for Arduino/Genuino Mega or Mega 2560.

I dont understand why there should be any functions in the library, which are not declared...This would mean noone could use it?! I am not an expert in C++ so maybe one of you could tell me what the issue could be. I am glad for any help.

after further web research, it looks like this is a bug which hasnt been fixed yet.
it was discussed previously here and here.

My solution was to go into the "LowPower.cpp" scroll down to the lines, where the functions are not declared and I just out-commented them. Compiling works now.


Using chipKIT WiFi Shield with an Arduino I'm beginning with Arduino and I have to make two of them communicate via WiFi. I'm going to implement the examples for a WiFi Client and WiFi Server in their tutorials page.

The problem is I only have one Arduino WiFi Shield which is working fine. But I also have a chipKIT WiFi Shield.

My question is: Can I use this other shield to do what I want with one of my Arduinos (I have Uno, Mega and Due) and how? Because I've plugged the shield and I've uploaded the code but it didn't seem to work.

No, you can't. The only libraries available for the chipKIT WiFi Shield are written specifically for the chipKIT boards.

Also, how have you plugged the board into an Arduino? The chipKIT WiFi Shield has Digilent's own header layout with a double row of headers where the Arduino only has a single row. Half the pins won't be plugged into anything.


Fool Proofing My Arduino IC Checker I am creating an IC checker for some high school juniors since a faulty IC can be a nuisance of a bug to find when bread-boarding. These ICs are all simple TTL gating from the 74LS series; the set I am using are all 14-pin and have VCC and GND at pin 14 and 7 respectively.

Thus far my prototype's hardware looks like this:

14 digital pins to connect to the IC inputs/outputs
1 analog pin reading a joystick to navigate through the IC options
1 analog pin set to digital read as a button, which starts the checking process
1 analog pin writing to an LED to indicate whether the IC is valid
2 analog pins (SDA and SCL) as a serial bus to control my display

I actually have the prototype working for a few ICs, but I am concerned that these high school students may test an IC under the wrong selection. Since the digital pins have to dynamically change input/output depending which IC its checking, this allows for inputs and outputs to be mismatched, which could prove fatal to both the IC and the Arduino board.

I want to know if there is a way to check that inputs and outputs are misaligned without having serious electrical failure. Possible some advanced pin control I am unaware of?

Also, if you could answer my question with an example with the 74LS00, whose pinout is diagrammed below and datasheet can be found here.

I would connect each of the IC's IO pins to both a digital output and
a digital (or analog) input of the Arduino, like this:

simulate this circuit – Schematic created using CircuitLab

Drive each pin with the digital output, alternatively LOW and HIGH.
While doing this, read the pin voltage through your input:

If the IC pin is an input, you will have no significant voltage drop
through the protection resistor. Your reading should be LOW when
driving the pin LOW and HIGH when driving it HIGH.
If the IC pin is an output, you will have 5 V through the
resistor whenever the IC's output value doesn't match your Arduino
output. The reading on your input will be independent of the level of
your output.

Obviously, an Uno doesn't have enough I/O pins to implement this idea.
You could use a Mega instead. Notice also that with this setup you don't
need the joystick input: you could just test for every known IC type
until you find one that matches the observed behavior, then display the
part number on your LCD.


Using two references in the same ADMUX I'm making a project and I neee to use 2 different references on the same ADMUX. One reference is 0-5V and the other is 0-2.5V. I'm aware that I can use the reference of the Arduino to the 5V sensor. But how I put a 2.5V reference while using the 5V at the same time?

First of all a reference is just a voltage, not a range.

If you use a reference of say 5V than your analogRead(...) calls will return a 10 bit number where 0 stands for 0V and 1023 stands for 5V.

Second, the AREF pin is there for that purpose: feed your 2.5V reference to that pin and use:

analogReference(EXTERNAL);
analogRead(...);

when you want to read using the 2.5V reference (0 stands for 0V and 1023 stands for 2.5V in this case), or

analogReference(DEFAULT);
analogRead(...);

when you want to read using the 5V reference (supposing your Arduino is powered by 5V).

UPDATE

Nothing can be done at the exact same time on an Arduino/ATmega328 because it has one single processing unit. In case of analog to digital conversion you can not even perform two conversions on two pins too fast because you have only one ADC which is multiplexed (shared) among all the analog pins.

You have no choice to perform one reading, wait, then perform the other reading. You can change the voltage reference between the two conversions though, but you need to ensure the internal ADC capacitor is properly discharged: if you read a 5V line and then read a 2.5V line without discharging the internal ADC you are more than probably going to always read the maximum value.

How long you will have to wait depends on the impedance of the line you are sampling: higher the impedance, longer the time you have to wait for the ADMUX capacitor to discharge/charge up (Arduino/ATmega328 ADC is a store and sample comparator).


Looking for an accurate and fast updating range sensor I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).
I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.
I'm happy to explain more about the implementation if needed, but until then ...
Many thanks for taking the time to help! John

Inside an inkjet printer, I've found a clear plastic strip with photo-engraved (loose approximation) lines perpendicular to the length of the strip. This strip passes through an optical pair, one side illuminates, the other reads. The strip stretches the entire width of the printer and if I recall correctly, the reading module is on the print head carriage. Consider that many printers are described as 600 dots per inch, which would create a resolution on the strip of 1/600" / 0.04 mm.
Additionally, I've discovered circular plastic encoders on which the rings of black/clear alternated the segment counts with each expanding ring. That is to say, the first ring was half black, half clear. The next ring out was 1/4 black/white alternating, the one following was 8 segments, then 16, etc.
This required a reader for each ring, but provided an absolute reference rather than a relative reference as is the case with the linear strip. One could create a linear strip which would work in a similar manner. One level would be half black, half clear, the next layer would be 1/4 black/clear, etc.

The requirement for 500 mm fits into a binary 512 value, which would require 9 stripes and provide for the accuracy noted in the post.
The aspect I can't answer is the speed of the encoding, although I suspect that any design based on an optical reader could be optimized to work.
I found an article at rp-photonics.com

When light is diffracted at the traveling refractive index grating in
an acousto-optic modulator, the diffracted light experiences a shift
of optical frequency which is plus or minus the acoustic (or drive)
frequency. That effect (which can be interpreted as a Doppler shift)
is exploited in acousto-optic frequency shifters.
Drive frequencies are typically between some tens and hundreds of
megahertz, rarely more than 1 GHz. The resulting change of optical
wavelength is quite small. For larger frequency shifts, or for
realizing very small frequency shifts (e.g. only a few MHz), one may
cascade two or more devices. It is also possible to use a double pass
through a single device in order to obtain twice the frequency shift.

I think from reading that excerpt that the long strip in the inkjet printer is the traveling refractive index grating. I had not considered that a low-power laser could be substituted for a simple optical pair. Doing so would provided even better resolution.
If your project allows for a strip of sufficient length to be attached to the piston, with assurance that it won't buckle under acceleration and jam in the sensor, you'd probably make it work.
But wait, there's more. I can picture the rod on the piston alternately obscuring and uncovering a digital design, which is constantly scanned by a laser. This reduces the number of parts in close contact and possibly the moving mass.


Arduino JSON foreach loop I'm trying to extract values using ArduinoJson. The values aren't fixed, therefore I need to use the foreach loop.

I'm trying this, but I can't seem to use the values like I could with.

root["0"]["value"].as<const char*>();

Here is my code.

void loop(){
  int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
      payload = http.getString();
    }
    if(payload.length() > 0) {
      Serial.println(payload);
      JsonObject& root = jsonBuffer.parseObject(payload);
      if (!root.success()) {
        Serial.println("parseObject() failed");
        jsonBuffer.clear();
      } else {
        Serial.println("Data Fetched");
        for(JsonPair& node : root) {
          Serial.print("0 State: ");
          Serial.println(*node);
        }
        http.end();
      }
    } else {
      Serial.println("Payload Empty");
    }
  }
}

Please avoid any missing brackets. Thanks in advance.

[{"state": true, "value": 10}, {"state": false, "value": 8}, {"state": false, "value": 5}, {"state": false, "value": 13}]

I found another way around the solution.

Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.

void loop(){
int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
      }
      if(payload.length() > 0){
          JsonArray& nodes = jsonBuffer.parseArray(payload);
          if (!nodes.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          }else{
            int node_length = nodes.size();
            for(int i=0; i<node_length;i++){
              Serial.printf("node-%i\nValue : ",i );
              String value = nodes[i]["value"].as<const char*>();
              String state = nodes[i]["state"].as<const char*>();
              Serial.println(value);
              Serial.print("State : ");
              Serial.println(state);
            }
            http.end();
        }
    }else{
      Serial.println("Payload Empty");
    }
  }

  jsonBuffer.clear();
  delay(8000);
}


Run Code Based on Time From GSM Module (SIM900) I am trying to check the time from the GSM module to let my code run or do nothing.

If I send the command, AT+CCLK? to the SIM900. This is the response:

AT+CCLK?

+CCLK: "17/02/14,16:58:25-20"

OK

How do I parse the time information from the SIM900 and setup a loop for my code to run if it is past 6pm but before 6am?

My code currently:

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7,8); //RX,TX

void setup() {
  PowerOn(); //power on GSM Module
  delay(10000); //delay 10 seconds
  SIM900.begin(19200); //software serial for GSM Shield
  delay(500);
}

void loop() {

// if time is past 6pm and before 6am send text message else do nothing

SendTextMessage();

}

///GetTime
void GetTime()
{
    SIM900.print("AT+CCLK?");
}

///SendTextMessage
void SendTextMessage()
{
    SIM900.print("AT+CMGF=1\r");//Because we want to send the SMS in text mode
    delay(100);
    SIM900.println("AT + CMGS = \"+12137777777\"");//send sms message, be careful need to add a country code before the cellphone number
    delay(100);
    SIM900.println("Motion Detected!");//the content of the message
    delay(100);
    SIM900.println((char)26);//the ASCII code of the ctrl+z is 26
    delay(100);
    SIM900.println();
}

///PowerOn
void PowerOn()
{
  ///software equivalent of pressing the GSM shield "power" button
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

I'm imagining SIM900 is a serial stream that supports input methods available() and read().  The hour portion of the response string is a two-digit integer delimited by a comma and a colon.  The following snippets of code assume you trigger a response and then start a listen() to connect to the software serial input.  Since listen() discards old data, presumably a message like +CCLK: "17/02/14,16:58:25-20" will be the next data to arrive.

This code converts any string of digits that it sees into a number.  Whenever it sees a non-digit character, it treats it as a delimiter.

When the previous and current delimiters are ',' and ':', it checks if the current number value is in the desired time range, and if so, it sets a flag, else clears a flag.

When the previous and current delimiters are '-' and '"', it assumes it is done with the parse.  Or one could, possibly, end the parse as soon as the hour field has been processed.

void loop() {
  // ...
  // somewhere within loop()
  byte num, dell;       // Currrent number and left delimiter
  byte timeFlag, readMore, foundTime;
  //...

  // Send string to elicit +CCLK and tell parser to handle response
  SIM900.listen();      // Discard old input
  SIM900.write("AT+CCLK?"); // Elicit new input
  readMore = true;
  timeFlag = foundTime = false;
  num = 0;
  dell = 0;
  // Read and parse +CCLK input; set or clear timeFlag
  while (readMore) {
    while (!SIM900.available()) {}; // Wait for a character
    char c = SIM900.read();
    if (c >= '0' && c <= '9') { // Is c a digit?
      num = 10*num + c-'0'; // Yes, add it to num
    } else {   // Not a digit, so check for Hour field or End of parse
      if (dell=='-' && c == '"') {
        readMore = false;
      } else
        if (dell==',' && c == ':') {
          timeFlag = (num < 6) || (num >= 18);
          foundTime = true;
        }
      dell = c;            // Record left delimiter of next number
      num = 0;             // Get ready to evaluate next number
    }
  }
  // If foundTime, then timeFlag is true for time in 6 PM to 6 AM, else false
  // ...
  // etc
}


Use Female USB Type A as Power Supply for external device I bought a female USB Type A Breakout, like this (https://www.sparkfun.com/products/12700). I thought I could use this one to simply power a USB 5v water pump. Therefore I use an external USB power supply that is regulated by a relay, that I regulate with my Arduino. But I'm wondering if it is possible to get that USB Breakout to "give out" power to my water pump.

Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.

If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.


Sense distance with Bare Conductive's Touch Board How can I sense distance with Bare Conductive's Touch Board, like they suggest in their product video?

I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.

As a member of the Bare Conductive team, I can tell you that looking at the grapher will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the Datastream code. Datastream will give you the sort of raw electrode data that you're looking for.


GPS timestamping of digitized voltages from geophones I wonder if anyone has written a code for GPS time stamping of voltages from seismic geophone (or any other sensors) digitized by internal or better external ADC connected to Arduino? Since the accuracy of at least 1 millisecond is required I believe using 1 PPS signal of the GPS is the only solution.

To tackle the time resolution and accuracy issue you could:

Attach the 1PPS signal to an interrupt pin
In the interrupt routine record the millis() value at the time the 1PPS signal is activated
In the main loop do a non-blocking read of the GPS data to find and build up the time string as it is sent from the GPS (shortly after the 1PPS is triggered).

You now know what the millis() count was the last time a 1PPS pulse arrived, and you know the current time to within a second. The 1PPS pulse will be at HH:MM:SS.000 (or as near as damnit) so if you subtract the current millis() from your recorded 1PPS millis() value it gives you the number of milliseconds since the 1PPS pulse. Add that to the current time, and you have 1ms accuracy in the time: HH:MM:SS.iii.


Performance tuning PORTB manipulation - mask I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.

Can I speed this up somehow? x  is a byte with the 3 lowest bits set.

#define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x

4 cycles:

IN Rd,PORTB
CBR Rd,7
ORI Rd,x
OUT PORTB,Rd

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.


FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel So I've got a FlySky TH9X and I'm trying to read some pulses using an Arduino Uno.

I'm just starting out so I want to get the hang of using the pulseIn function before moving onto interrupts. My problem is that, when I wire everything up, I don't get sensible values. Furthermore, they don't change even though I move around the sticks on the actual remote.

I tried to start off simple by wiring just the channel 1 of the receiver to pin 3 of the Uno. Then I used this code:

int ch1;

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

void loop() {
  ch1 = pulseIn(3, HIGH, 25000);
  Serial.print("Channel 1: ");
  Serial.println(ch1);
  delay(100);
}

The serial monitor then spits out numbers ranging from 0 up to 10000+ in a very erratic and apparently not periodic nature. I'll copy a few lines here:

Channel 1: 9989
Channel 1: 10063
Channel 1: 10068
Channel 1: 274
Channel 1: 0
Channel 1: 10085
Channel 1: 10039
Channel 1: 10336
Channel 1: 9629
Channel 1: 9959
Channel 1: 10064
Channel 1: 10088
Channel 1: 378
Channel 1: 0
Channel 1: 10044
Channel 1: 10059
Channel 1: 10424
Channel 1: 9632
Channel 1: 9867
Channel 1: 10069
Channel 1: 10067
Channel 1: 10473
Channel 1: 10037
Channel 1: 10063
Channel 1: 10063
Channel 1: 10253
Channel 1: 9677
Channel 1: 10013
Channel 1: 10064
Channel 1: 10062
Channel 1: 13

As you can see: not only are the higher-end values a whole order of magnitude too big (i thought pulses are normally between 1000 - 2000us?), but the actual range that these numbers span is far, far too wide for me to do anything with. Also, the sticks on my remote seem to have no influence on the numbers.

Can someone please help me? thank you :)

Hassan

I would not recommend using pulseIn for reading values from the receiver.  pulseIn blocks the program until a signal is received, which is almost always undesirable.

An alternative approach would be to use CHANGE interrupts.  You get an interrupt when the signal goes high and low.  You take note of the time that each change occurs with millis and compare the times to get the duration of the signal.

Here's an example - you can add more channels if you'd like.  Note, this is using the EnableInterrupt library.

#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  2

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1

uint32_t last_update_time = 0;
uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  // read the values out of the shared, volatile array (which can change at any time)
  // and into an array that we only will only change when we call this function

  noInterrupts();
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
  interrupts();
}

void calc_input(uint8_t channel, uint8_t input_pin) {
  // This is the interrupt.  If the pin is high, we record the start
  // time of the pulse.  If the pin is low, we compare the start time
  // to the current time in order to get the length of the pulse.

  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;
  }
}

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);

  // set up CHANGE interrupts, so that we get notified when
  // each signal goes high or low.
  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
}

void loop() {
  rc_read_values();

  Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
  Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

  delay(200);  // just so serial log doesn't flood
}

For a more detailed explanation, take a look here:  http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html


Arduino HTTP Command - ESPEasy I am new to Arduino and although I am starting with and creating some basic projects my end goal right now is to be able to turn my Sonoff on and off via a momentary switch attached to my Wifi enabled Arduino board (Particle Photon). I'm not looking for the code I would just like to pointed in the right direction.

I flashed my Sonoff so that it now runs ESPEasy and set it up so that I can control it from my browser using http://10.0.1.35/control?cmd=event,TurnOn to turn it on and http://10.0.1.35/control?cmd=event,TurnOff to turn it off. I have been reading about using POST or GET requests but none of the examples I find seem to send a similar command to how I currently have my Sonoff set up.

My question is what should I be looking at and reading about to be able to send these types of commands via the Arduino?

Any recommendations are greatly appreciated. I'm thoroughly enjoying getting into coding but finding this step quite challenging to say the least!

Thanks!

Thanks for the heads up that the GET request was indeed the right way to go. I managed to work through this a bit today got the GET request to work. I also hooked up the button and got that to send the two requests on both press and release. I know this code is for the Photon but I hope it'll help someone else out

// TCPClient
#define LIB_DOMAIN "10.0.1.252"
TCPClient client;

// This constant won't change:
const int  buttonPin = D1;    // the pin that the pushbutton is attached to
const int ledPin = D7;       // internal LED pin

// Variables will change:
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT); // Initialize D7 pin as output
  pinMode(buttonPin, INPUT_PULLUP);
  // Initialize D1 pin as input with an internal pull-up resistor
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, turn on or off
    if (buttonState == HIGH) {
        digitalWrite(ledPin, LOW);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOff HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    } else {
        digitalWrite(ledPin, HIGH);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOn HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

}


Powering an Arduino Pro Mini directly from a LiPo I've recently purchased an Arduino Pro Mini, 3.3V version. I've planned to use it in a diy remote: I've empty a ps2 remote, just left the buttons, and the board will be inside. The remote will be wireless: I use an xbee, which also fit inside the ps2 controller. To power it, I use a one cell Lipo, which will empower the Arduino and the XBee, here comes my issue: As you've seen, there will be many things an a single ps2 controller, so I try to minimize connections and external components. But, the XBee will take more than the maximum 150mA provided by internal regulator of the Arduino. So, either I use an external regulator, or I directly plug the lipo in the VCC pin if the Arduino. Can the board survive? If the voltage is greater than 3.3V, will it damage the board?

The only thing about the 3.3V Pro Mini that is actually 3.3V is the 3.3V regulator.  The main chip (pretty much the only other component) is good for anything from 1.8V up to 5.5V.

Running direct from a 3.7V LiPo or Li-Ion will be perfectly fine.  You might want to disconnect or otherwise disable the regulator though to reduce current consumption - the latest Minis have a solder jumper SJ1 for doing just that, but older versions you may want to actually cut the 3.3V OUT pin of the regulator or de-solder it entirely.


How to run 5 wires hibrid stepper motor with arduino uno? I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver.
Here is the driver, stepper and Arduino when stepper has 4 wires.
http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1_Resize.png

I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.

Questions are:

Wires identification?
How to connect it to ArduinoEasyDriver?
Code example desired.

UPDATE

  I am now thinking of making it bipolar (4 wires), because now in 5
  wires configuration motor is unipolar. I did some research and this
  motor is HIBRID. It can be driven as unipolar or bipolar. I will try
  to troubleshoot the wiring and find the common wire. Ill keep you
  informed.

1) it is probably something like A1, A2, Common, B1, B2.  You could confirm this with an ohmmeter. Common to any of the others would be a certain resistance X, while between any of the others (A1-A2, B1-B2, A1-B1, A1-B2, B1 A2) would be 2X.

2) You can't.  It is a unipolar stepper.

The EasyDriver faq number 5.1 at http://www.schmalzhaus.com/EasyDriver/ says:  "... The only kind you can't use is 5-wire stepper motors. (They need uni-polar drivers.)"

The difficulty with the 5-wire steppers is that they short the middle of the two coils together, which makes it hard to drive the coils independently.

Since you have the motor open, you might be able to do some surgery and disconnect the centers of the coils from each other, but you'll probably be better off getting a 4, 6 or 8 wire stepper instead.


Make 3 servos move like a wave I am having some trouble programming 3 servos to move like a wave.  So, for instance, all my servos start at 90 degrees. I want my first servo to move and when it reaches 135 degrees I want my second servo to move, with the first, then when it reaches 135 degrees I want my third servo to move, with the first and the second. Then go backwards. Does that make sense?

Here is what I have so far.

#include <Servo.h>

//Create servo object to control a servo
Servo left;
Servo middle;
Servo right;

//Variables to store the servo position
int post = 180;
int post2 = 90;
int back = 90;
int forward = 135;

int firstTriggerAngle = 135;
int secondTriggerAngle = 180;

//Delay
int mid = 4;

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

  //Attaches the servos on the pins of the arduino to the servo object
  left.attach(4);
  middle.attach(3);
  right.attach(2);

  //Starting position
  left.write(back);
  middle.write(back);
  right.write(back);
}

void loop()
{
  for (int i=back; i>=forward; i+=1)
  {
    left.write(i);
    if( i > firstTriggerAngle)
    {
      post = map(i, 90, 135, 135, 90);
      middle.write(post);
    }
    if(post > secondTriggerAngle)
    {
      post2 = map(post, 90, 135, 135, 90);  // depends on the angles you use
      right.write(post2);
    }
    delay(mid);
 }
}

The easiest way is to define how many degrees you want to move totally .

In your case it is 180 steps (from 90 to 180, which is 90 steps, and 180 to 90, which is another 90 steps).

Than use a for loop with a 180 step-counter and make 3 simple formulas to map the 180 possible degrees to the wanted servo position.

So the first formula will look like (step 0..90 -> move from 90 to 180, step 90..180-> move 180 to 0).

int calcServo1(int step)
{
    if (step < 90)
    {
        return 90 + step;
    }
    else
    {
        return 270 - step; // 180 - (step - 90);
    }
}

For the second it should be:

step is 0..45: first iteration: 90, otherwise 135..90
step is 45..135: 90..180
step is 135..180: 180..135

The code will be something like:

int calcServoPos2(int iteration, int step)
{
    if (step < 45)
    {
        if (iteration == 0)
        {
            return 90;
        }
        else
        {
            return 135 - step;
        }
   else if (step < 135)
   {
         return step + 45;
   }
   else
   {
       return step - 45; //  step - 180 + 135
   }
}

Servo 3 I will leave up to you.

From your main loop you call the positions:

 int iteration = 0;

 while (loop)
 {
      for (int step = 0; step < 180; step++)
      {
         int servo1pos = CalcServo1(iteration, step);
         servo1.write(servo1pos);

         int servo2pos = CalcServo2(iteration, step);
         servo2.write(servo2pos);

         int servo3pos = CalcServo2(iteration, step);
         servo3.write(servo3pos);

         delay(mid);
     }
     iteration++;
  }


Why does this Arduino Pro Mini use a capacitor on the DTR reset line? I'm kind of curious as to why there is a 0.1uF capacitor on this Arduino Pro Mini (https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf). It seems like it would work just fine without it.

Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.

This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.

The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.

So it will convert a LOW transition to a LOW pulse.


Can Android phone can be used instead of( or with) Arduino as controller? I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

phone as controller (without arduino) - this option would be the
best
if phone cannot give commands maybe with arduino, while
using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.

So for normal RC car you would need to have:

AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC


Speeding up Arduino DC Motors I am using the Adafruit Motor Shield v2.3 for Arduino Uno. I am using the analogWrite() command to power my DC motor and have set the speed to 255. Is there any way to speed up the Arduino motor even further? Thanks!

The speed of a motor is a function of the motor itself and the voltage applied to it. There is no programmatic way of increasing the speed of a motor. You would either need to increase the voltage being applied to the motor (as long as it is within the limits of your motor and speed controller) or find a different motor to use that is faster.

It appears the Adafruit motor shield accepts between 5-12 volts, if you are not already at the maximum of 12 volts, and your motor is rated to allow it, you can increase the voltage you are applying to the shield. All that 255 means in this case is give the motor all the power that is available, so if you are only giving the controller 5 volts, it is only going to give the motor 5 volts.

Also I might recommend instead of using analogWrite() that you use the official Adafruit library to control your shield as it uses its own PWM library which is more performant for motor control than the built-in Arduino one.

EDIT

Actually, with v2 of the shield, it has its own PWM driver controlled over I2C. In which case analogWrite() shouldn't work at all, or at least it doesn't do what you think it does. Instead use the official Adafruit library and I also recommend following the official tutorial as well.


Creating variable inside if statement (conditional signed vs unsigned int) I have an SPI chip that I would like to read out with an Arduino. Some of the registers are signed int others are unsigned int. I am writing a function to read any register.

A simplified version:

readRegister(byte thisRegister, char type) {

  if(type == 's'){
    signed int result;
  }else{
    unsigned int result;
  }

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

readRegister(0x4B87,'s')  //read signed int register
readRegister(0xB357,'u')  //read unsigned int register

However this doesn't work since the variable result is created inside the if statement so the scope is wrong. I get error: 'result' was not declared in this scope on the SPI.transfer() line.

How to solve this?

You could try something like this:

int16_t readRegister(byte thisRegister) {
  int16_t result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

uint16_t readUnsignedRegister(byte theRegister) {
  return (uint16_t) readRegister(theRegister);
}

Another alternative is to define a "universal" data type, i.e. a union and necessary cast operators.

union univ16_t {
  uint16_t as_uint16;
  int16_t as_int16;

  univ16_t(int value)
  {
    as_int16 = value;
  }

  operator uint16_t()
  {
    return (as_uint16);
  }

  operator int16_t()
  {
    return (as_int16);
  }
};

This allows the function to have the following form:

univ16_t readRegister(byte thisRegister) {
  int result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

With the two possible assignments.

uint16_t reg1 = readRegister(...);
int16_t reg2 = readRegister(...);

Cheers!


Why does a 4 digit 7 segment cathode display wired to an Arduino not need to be connected to ground? As a circuit neophyte I thought for a circuit to conduct current it had to be grounded.

The Uno is grounded. Current flows into the A-G and DP pins (that is: D2, D3, D4, D5, D6, D6, D8, and D9 on the Uno) when one of those pins is LOW and one of the display's digit pins is also low.

There is one "Common" pin for each of the 4 digits, labeled D1, D2, D3, and D4 on the display. Those common pins are connected to the Anodes (positive pin) of all segments in the specified digit. When 5V is applied to the base of the transistor, the NPN transistor is off. When 0V is applied to the base of the NPN transistor, current flows from the 5V source, through the transistor, and into the Anode of the digit.

When a segment pin (A-G, DP) is HIGH, it is at 5V. The Anode is also at 5V, so no current flows. When a segment pin in LOW, it s at 0V, and current flows from the Anode to Ground through the segment pin into the Uno.

This kind of display is meant to be multiplexed by digit. To light the first digit, The D1 transistor is turned on, and the segments to light up are set to LOW. All other transistors are off. Then, the first digit transistor is turned off and the 2nd digit transistor is turned on, and the segment pins are re-adjusted so that the desired output on the 2nd digit is displayed. Each digit is only on for a fraction of a second, but they are rotated through all 4 so quickly, that it gives the appearance of all 4 digits being on at the same time, without requiring 8x4=32 IO pins. Multiplexing means you only need 8+4=12 IO pins.

Search "multiplexed common anode 7-segment display" for more info.


Powering Arduino with 12V AC-DC Adapter Jack I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?

Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.

Is this correct?

Thanks,
Jyoti Raj

You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.


Arduino Wifi Shield with monitor mode ( promiscuous mode ) Is there a WiFi Shield or driver that supports monitor mode and receiving raw packets ?

Does it have to be a shield?

I would consider buying a cheap Wi-Fi router instead with good open-source support and a way to interface it to the Arduino. Their price is near to the price of Wi-Fi shields.

They consume little power, can be powered by 5V and have built in Wi-Fi.
Some have a built-in USB port, most have a serial port, which can be used to talk to the Arduino.
You would have to put custom firmware on it, plus the program which receives the raw packets for you.

Specifically, I would get a TP-Link TL-WR703ND for this task.

It can be fed 5 Volts, or 3.3 Volts with a little hacking
It has USB
It also has serial, and you can even hack an I2C port onto it
It can run OpenWRT

More info on this particular router


My Arduino IDE stuck on uploading So for a while I get some Arduino IDE problem which I can't solve. When I try to upload any kind of code to my Arduino, Arduino IDE just stay at "Uploading". I tried to use another Arduino but I get the same problem. I used Pro Mini, Nano and Uno but it's the same. Then I decided to upload my code from another PC but I get the same problem and so I can't find where the problem is.

Is the problem in all my Arduinos or in my computers?

Note:
The code which I was uploading, was from Arduino examples.

I am using Windows 10 Pro x64 and in my console I get this error:

 avrdude: stk500_recv(): programmer is not responding
 avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x57

To solve this problem, you should google the error message "avrdude: stk500_recv()".  The web shows countless records where this error comes up.  The message indicates that the serial communication has malfunctioned, but incorrect driver or serial port is not the only way this can happen.

During upload, (1) Have you tried to reset the arduino, (2) ensure that the RX/TX pins are not in use?


How to rewrite code in millis? I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns.
However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?

Here is my code:

#include <AccelStepper.h>

AccelStepper stepper(1, 42, 38);

int i;
int microStep = 46;

int currentAnimation = 0;
int count = 0;
int button = 13;

int state = LOW;
int lastState = LOW;

//bytes for patterns
byte a = B11110000;
byte b = B00010000;
byte c = B01000000;
byte e = B10100000;

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

void setup()
{
  DDRH = B1111000; // set PORT 6-9 of arduino mega high
  DDRB = B11110000; // set PORT 10-13 high

  stepper.setMaxSpeed(900.0);
  stepper.setAcceleration(400.0);

  pinMode(button, INPUT);
  state = digitalRead(button);

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

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

void loop()
{
  //This should happen constantly
  stepper.runToNewPosition(2000);
  delay(500);
  stepper.runToNewPosition(0);

  // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
  }

  if (currentAnimation % 3 == 0)
  {
    same();

  }
  if (currentAnimation % 3 == 1)
  {
    left();
  }
  if (currentAnimation % 3 == 2) {
    faster();
  }

  lastState = state;
  state = digitalRead(button);
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void same() {
  for (int k = 0; k < 10; k++) //plays 10 times
  {
    PORTH = a;
    PORTB = a;
    delay(100);
    PORTH = 0;
    PORTB = 0;
    delay(100);
  }
}

void left() {
  for (int z = 0; z < 10; z++)
  {
    PORTH = e;
    PORTB = e;
    delay(100);
    PORTH = ~e;
    PORTB = ~e;
    delay(100);
  }

}

void faster() {
  for (int z = 0; z < 256; z++)
  {
    PORTH = z;
    PORTB = z;
    delay(100);
  }
  PORTH = 0;
  PORTB = 0;
}

The basic pattern goes like this:
when you start the timer, you essentially store the current millisecond.
After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.
Make sure you use unsigned long variables to store times and check if time has passed with the condition used below (if(millis() - mark >= interval ){...}) so you will not have problem even after millis() rolls over.
If you need more help, do not hesitate to ask.
unsigned long interval=2000; //2000ms
unsigned long mark;
boolean enabled=true;

void setup() {
    Serial.begin(9600);
    Serial.println("starting timer");
    startTimer();

}

void loop() {
    check();
}

void startTimer(){
    mark=millis();
}

void check(){
    if(enabled){
        if(millis() - mark >= interval ){

            enabled=false;
            Serial.println("time elapsed");
        }

    }
}


Store String using F() Macro I'm new to the Arduino and do not quite understand the F() macro yet.

In my code, I have a String, and as I want to transfer it via WebServer, I need to write it to the answer.

Somehow I need to convert the String, to fit it into the fastrprintln() function.

String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

Do you have any idea for me?

The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:

Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:

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

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:

// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.


Adding Date and Time to existing sketch I am currently trying to add a clock functionality to my current sketch for a peristaltic pump [run by NEMA 23].

The current sketch waits for a button on my breadboard to be pressed, it then runs the motor for a specified amount of steps and then stops and waits for the next press of the button. It also displays the amount of steps to the Serial Monitor. I have a working sketch for a clock using an RTC DS3231 module and have unsuccessfuly attempted to fit it into my motor sketch. The problem is, the clock seems to be taking precedent over the rest of my sketch, so pressing the button no longer works and the time is simply consistently output onto the Serial Monitor.

The ideal functionality would be the time and date displayed on LCD constantly (or at least blinking so rapidly that one could not tell the difference) with the number of button presses displayed under it, changing in value only when a button is pressed.

Attatched find my code, it is really quite simple, and thank you so much for the time and help.

#include <Bounce2.h>
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <Wire.h>       //I2C Library
#include <OneWire.h>
#define DS3231_I2C_ADDRESS 0x68

AccelStepper stepper(1, 9, 8); // initiate stepper motor

LiquidCrystal lcd(6, 7, 5, 4, 3, 2);

int pos = 0; // variable to store position
int buttonPresses = 0;

const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

unsigned long ledOnTimer = 0;

const unsigned int ledPeriod = 3000;

Bounce button;

void setup() {
  Wire.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setMaxSpeed(4000);
  stepper.setSpeed(2000);
  stepper.setCurrentPosition(0);
}

byte bcdToDec(byte val)  {
  // Convert binary coded decimal to normal decimal numbers
  return ( (val / 16 * 10) + (val % 16) );
}

void loop() {
  motor();
  printDate();
}

void motor() { // functioning motor sketch by itself

  //if led is on
  if (digitalRead(LedPin)) {
    stepper.runToNewPosition(21000); //about 420 steps per 10 mL
    digitalWrite(LedPin, LOW);
    // }
  }

  //if led is off
  else {
    button.update();
    if (button.fell()) { // if the button "fell" from a value from HIGH to LOW (so now it is off)
      stepper.setCurrentPosition(0);
      digitalWrite(LedPin, HIGH);
      buttonPresses++; // count presses of button and print to monitor
      lcd.clear();
      Serial.print("Number of Button ");
      lcd.setCursor(0, 1);
      Serial.print("Presses = ");
      Serial.println(buttonPresses);
    }
  }
}

void printDate() { //functioning time sketch by itself

  // Reset the register pointer
  Wire.beginTransmission(DS3231_I2C_ADDRESS);

  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();

  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);

  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());

  //  print the date EG   3/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

Last note: Everything compiles, and I will change "Serial" to "lcd" after I finish debugging the sketch, so that is why everything is currently beign sent to the Serial Monitor.

I think you need to look at using interrupts.

The printDate function is quite processor intensive with all the Wire and Serial.print calls, it will be taking the majority of the time in each loop().
Whilst in printDate it won't be looking at the state of the button, so you have to press at just the right time.

If you place an interrupt on the button's pin I think you will get a more responsive system.  Another thing that you could look at it only reading the clock once a second, this could be done with a timer interrupt.


Sending multiple channels with bluetooth I have ordered my HC-05 BT modules.
My question is this:
Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.

If it is possible, could you please provide some more information on how its done?
Thanks!

The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).

There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.

For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:

Communication Protocol Best Practices and Patters


Upload sketch remotely through a serial-IP-serial connection I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.

I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:

PC1-SERVER
Arduino Uno is connected to this PC with classic USB cable.
This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.

PC2-CLIENT
This is the PC where I create and compile the sketch.
I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)

SOLUTION:
server-side commands:

Code:

sudo apt-get install ssh-server ser2net

sudo passwd root    (to set the root password)

sudo reboot

client-side commands (assuming 192.168.0.7 as IP address of SERVER):

Code:

ssh -L 8086:localhost:8086 root@192.168.0.7 \
'/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

you can then upload sketches to arduino doing this:

Code:

avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

NOTE:
In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.

This solution was also posted on arduino forum.


Battery life calculation using Nano, NRF24L01+ and window magnetic reed switch I'm trying to make my own home wireless security system.  I will be using probably 3 AA batteries to power these devices.  My problem is that I need to know if the batteries will be enough to power the devices for at least 6 months.
Below are the details of all the devices I will be using:

Mini Nano V3.0 ATmega328P Microcontroller Board w/USB Cable For Arduino
Makerfire Arduino NRF24L01+ 2.4GHz Wireless RF Transceiver Module
uxcell MC 38 Mount Wired Door Window Sensor Magnetic Reed Switch Recessed

Below are some project requirements that might be useful:

For the Nano, I want to put it to sleep using delay(2000) in the loop() function.  The Nano will be the one checking the window sensor.
I will be using a project enclosure of about 4X4 inches.

If this will not be possible maybe someone knows of other devices that use less power that will be more suitable for this project? I would prefer something easy to use like Arduino Nano with USB so I can easily program it.

EDIT: sorry but I just like to add that from the main HUB component, I would like to check the status of the window sensor if it is open/closed.  This will be useful if there is an open window/door around the house when going to sleep. Probably the Nano will broadcast its current window sensor status to the main HUB program. Thanks.

You should use interrupts for the reed switch and then put the microcontrolller into sleep for a keep alive interval. Your master device should check that the sensor is still active and set off the alarm if its not. You would also want to allow for a battery low condition that might disable the alarm for convince. This still should keep the power consumption low.

The nano is roughly 1mA @ 3.3v while the CPU is running and 72uA when its in sleep. Discounting power consumption in the alarm condition triggered by the interrupt using an interval of 9 seconds using delay or interrupt timers then average consumption then about a second to wake up and send a keep alive over the RF. (0.000072 * 9 + 0.001 * 1) / 10 = 0.0001648 amps. (average over 10 second duty cycle)

My guesstimate of your RF power consumption without knowing what kind of protocol would be somewhere around 128 bytes per transmission taking about 90ms. (0.0001 * 9910 + 0.015 * 90) / 10,000 = 0.0002341 amps.

Total of their averages is: 0.0003989 or 398.9uA.

Alkaline AA cells vary widely. So instead based on some Ni-MH with 2400mAh per cell and 1.2v

3 cells would be 3.6v so you'll "get" most of the mAhs out of the batteries.

2400mAh = 2400000uAh

2400000uAh / 398.9uA ~= 6016.54 hours or 250 days or 8 months.

Power consumption were intentional overestimates. You should be able to make it last a lot longer.

https://www.avrprogrammers.com/howto/atmega328-power
http://harizanov.com/2013/05/nrf24l01-power-consumption-footprint/


NodeMCU what is my esp3286 core version How do I find out what my esp3286 core version using Arduino IDE?

Tools Menu -> Board -> Boards Manager - scroll down to the core and see what version it is.


How can I make an H-bridge using NPN transistor? I am new to arduino and I wanted to make an h-bridge because it is not easily available in india. I want to control the h-bridge using arduino uno r3 board and 2n2222A transistors and 1n4001 Diodes if necessary. I want this h-bridge to control two motors in a single direction. If possible pls include the friting diagram. I had created the circuit using NPN transistor and flyback diode and a resistor for both motors individually, I am posting the diagram , This is the link to the tutorialtutorial link

I am posting this as an answer so I can show the diagram.
But, my answer proper is in my comments above - your diagram is badly wrong. If what you have built is the same as the diagram then it is not what you are trying to build.  And, if the diagram is wrong, you should fix it.

Fritzing can do an OK job of showing layouts when used well. But your diagram is unable to be interpreted with certainty. It is not a matter of  you "not being good with Fritzing" as you say - it is a matter of putting in enough effort to show what you are trying to show. If it is wrong you MUST fix it - it is pointless to show people absolute rubbish which cannot be correct.

You say " ...I did exactly the same, [as the example]..." BUT your diagram and his are different and half your diagram cannot work in any way.

You MUST compare the two and not just keep pretending that yours and his diagrams are identical.

Look at the diagram below - copied from your diagram.
Inside the orange ellipse - how do the blue wire, green wire, diode and transistor really connect.
Why do your wires not end on "holes" in the breadboard - if a wire end is between two holes, which is it really meant to connect to?
Follow the red and blue lines that I have added to show current flow through one motor. The current MUST go THROUGH the diode in your example. In his example the motor current does NOT go through the diode.
FWIW - your diodes can not pass current in the direction shown - but that's not your main problem. FIRST fix the wiring so it is the same as his and the same as what you have built/ THEN your main question may be able to be answered - or may answer itself.

LOOK at his diagram and yours.
Compare them.
Follow the current pars.
Realise that your one is wrong.

If you refuse to take advice and continue to insist that what you have shown on your diagram is the same as the example then you will be unhelpable. Or, take advice and learn as you go and you will find it a rewarding hobby.


What is the best way to attach TMP36 sensor to the copper coil? I am very new to this site and this question may not be strictly related to Arduino, but I do small Arduino project which needs to measure the temperature of the copper coil using TMP36GZ sensor.

What is the best way to glue it to the coil for best measurements?
Shoul I use silikone or epoxy?
Should I take extra steps to ensure proper readings from the coil surface (f.ex.: using thermal paste)?

If you don't have to worry about conductivity from the electrical standpoint, you could use a thermal epoxy such as Arctic Silver which uses "microfine" particles of silver to conduct heat. It's a two part (redundant when using the term epoxy, I think) adhesive that is engineered to transfer heat, but may also short conductors. I've used the stuff and unless subject to intentional separating force, it holds well.


Which Protocol to use to control WiFi (esp 32) enabled Led Light I am developing a Wifi based Led light (for learning purpose). I have little knowledge about web server, clients, Web protocols. I will be using ESP32 as Controller cum WiFi module.

There are two ways to control Led light over WiFi.

Locally
Remotely // as of now am focusing on locally

Android/iOS app will be handling all the control part (Flutter app)

Which protocols can I use to control Led light, locally?
will set up multiple esp32 at that time its hard to control the device both devices will have different ip

Kindly help!
if anyone give good example it would be helpful

You can use your ESP as a server by the following code and then put your DigitalWrite(1, HIGH) line in the code like the following:
 String line = client.readStringUntil('\r');
 Serial.print(line);
if(line=="ledon")
{
DigitalWrite(1, HIGH);
}

and at this point you just can call the following link to turn the led on
http://192.168.*.**/ledon

or whatever the starting of your ipv4 is.


Arduino + TMP36 + DC Motor I made this circuit:

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)

As you can see, I also have a TMP36 sensor attached. What I would like to do is this:
When the temperature is 25 degrees or more, the motor should turn on.

I have this code:

//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                        //the resolution is 10 mV / degree centigrade with a
                        //500 mV offset to allow for negative temperatures

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor
}

void loop()                     // run over and over again
{
 //getting the voltage reading from the temperature sensor
 int reading = analogRead(sensorPin);

 // converting that reading to voltage, for 3.3v arduino use 3.3
 float voltage = reading * 5.0;
 voltage /= 1024.0;

 // print out the voltage
 Serial.print(voltage); Serial.println(" volts");

 // now print out the temperature
 float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((voltage - 500mV) times 100)
 Serial.print(temperatureC); Serial.println(" degrees C");

 if(temperatureC >= 25){
  analogWrite(9, 250);
 }

 delay(1000);                                     //waiting a second
}

But I get this result:

0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.75 volts
25.20 degrees C <------
0.87 volts
36.91 degrees C
0.66 volts
16.41 degrees C
0.78 volts
27.64 degrees C
0.77 volts
26.66 degrees C
0.84 volts
34.47 degrees C

The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.

How do I solve this?
Thanks in advance!

I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png

Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.


Bad Communication with Multiple I2C Devices I have an Arduino Micro connected to two I2C devices. An MPU-6050 that is powered by 5V (though it has its own voltage regulator on it) and a Altimeter that is powered by 3.3V. They are both connected to the SDA and SCL.

I noticed that when I have the MPU powered on but don't power the 3.3V altimeter, the MPU does not communicate with the Arduino. I need to have the 3.3V power on to just communicate with the MPU through I2C. Why does this happen?

Then unfortunately, I believe I may have shorted the 3.3V rail and broke the altimeter. When I remove the MPU from the equation and try to just communicate with the Altimeter, I get nothing. Does this mean that I did short the device, or is there something else going on with I2C that I don't understand?

I have attached a schematic below of how the devices are connected.

I would like to know why when one device is bad (or not powered) on
  I2C, it screws up the other devices.

The I2C lines need to have a pull up resistor to provide the high. The master device, and the slave devices, ground the line to provide a low, but they release the line, and not drive it at all, in order to provide the high.

Consider switches a and b to be inside the I2C device. When the switch a is open point A will be at 5 volts. When switch a is closed, point A will be at 0 volts.

Now if you had a second set of R resistors on the same line, but powered from their own 5 volt power supply, the same voltages will be seen at A when switch a is open (5 volts) and switch a is closed (0 volts).

But now if we kill the supply feeding the second set of R resistors (sorry that I can't show them in a picture) instead of pulling up to 5 volts (because we killed the 5 volts) the resistors will be pulling down due to whatever other loads there are on the killed 5 volt supply. And just for argument sake, let's say the killed 5 volt supply was at 0 volts.

So if one set of resistors is pulling up to 5 volts (the still powered pair) and one pulling down (the killed pair) then the voltage at points A and B will not be as high as the 5 volts we would see when the switches are open.  If all the resistors R were the same value, and the killed supply was at 0 volts, then the highest voltage at A or B would be 2.5 volts. And that is not a good high.

So the additional device, that is not being powered, has disrupted the communitations, preventing true highs. Lows are not affected as the switch will pull the line low.

I don't know the values of all your pull up resistors, and don't know how low the dead supply goes, so I can't say what the new lower highest voltage is. But it seems that it is low enough to make the communications stop working.

And the resistor are not the only thing that can be disgusting the high. The unpowered chip can be providing unexpected current paths. Most port pins have an internal diode to Vcc. And since the chip has no power on Vcc the current on the I2C lines can follow that path to ground.

Also, I think you have drawn the resistors wrong. If they were in series with the SDA and the SCL pins there would be no communications because the 1k resistors doesn't allow the SDA line to be pulled low enough. I think those resistors are pull up resistors. Maybe you can take another look and confirm the connection.


What are the fundemental differences of different Bluetooth modules for beginners? I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.

Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).

Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.

My question here is:

What are the fundemental differences of different Bluetooth modules for beginners, such as:

HC-05
HC-06
HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?

As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search).
As for the differences:

The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.
The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.
As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.


Where is the definition of system_adc_read() in the esp8266 Arduino code? Where is the definition of uint16 system_adc_read(void) in the esp8266 Arduino code?

I can see it being declared in Arduino/tools/sdk/include/user_interface.h, however there seems to be no definition of this. system_adc_read() gets called in analogRead() in Arduino/cores/esp8266/core_esp8266_wiring_analog.c

I suspect system_adc_read() calls system_adc_read_fast() to read the ADC, but can't actually find it in the code! Could somebody please point me to this? I've been struggling for quite some time.

Purpose: To manipulate the system_adc_read() in ESP8266 to get higher ADC sampling rates. Right now ADC sampling rate is 10ksps. I want it to be more than 30-40ksps.

The "definition" of uint16 system_adc_read(void) is inside the compiled archive/object file libmain.a inside one of the NONOSDK folders which is located in /tools/sdk/lib/ . The version is selected in platform.txt. For example in my platform.txt:

# default SDK for all boards
# (generic board overrides this variable)
build.sdk=NONOSDK22x_190703
#build.sdk=NONOSDK22x_191024
#build.sdk=NONOSDK22x_191105

Running the xtensa-lx106-elf-objdump.exe -d on this file I can find this section inside:

00000258 <system_adc_read>:
     258:   020c                    movi.n  a2, 0
     25a:   f0c112                  addi    a1, a1, -16
     25d:   0109                    s32i.n  a0, a1, 0
     25f:   fffc01                  l32r    a0, 250 <system_pp_recycle_rx_pkt+0x18>
     262:   0000c0                  callx0  a0
     265:   fff901                  l32r    a0, 24c <system_pp_recycle_rx_pkt+0x14>
     268:   f42020                  extui   a2, a2, 0, 16
     26b:   1b1207                  beq a2, a0, 28a <system_adc_read+0x32>
     26e:   b30c                    movi.n  a3, 11
     270:   902220                  addx2   a2, a2, a2
     273:   1122e0                  slli    a2, a2, 2
     276:   fff701                  l32r    a0, 254 <system_pp_recycle_rx_pkt+0x1c>
     279:   0000c0                  callx0  a0
     27c:   f42020                  extui   a2, a2, 0, 16
     27f:   00a402                  movi    a0, 0x400
     282:   013027                  bltu    a0, a2, 287 <system_adc_read+0x2f>
     285:   020d                    mov.n   a0, a2
     287:   f42000                  extui   a2, a0, 0, 16
     28a:   0108                    l32i.n  a0, a1, 0
     28c:   10c112                  addi    a1, a1, 16
     28f:   f00d                    ret.n
     291:   00                          .byte 00
     292:   00                          .byte 00
     293:   00                          .byte 00
     294:   ff ff 00 00
    ...

000002a0 <system_adc_read_fast>:
     2a0:   e0c112                  addi    a1, a1, -32
     2a3:   11c9                    s32i.n  a12, a1, 4
     2a5:   21d9                    s32i.n  a13, a1, 8
     2a7:   31e9                    s32i.n  a14, a1, 12
     2a9:   5129                    s32i.n  a2, a1, 20
     2ab:   41f9                    s32i.n  a15, a1, 16
     2ad:   0109                    s32i.n  a0, a1, 0
     2af:   03fd                    mov.n   a15, a3
     2b1:   fff901                  l32r    a0, 298 <system_adc_read+0x40>
     2b4:   0000c0                  callx0  a0
     2b7:   4fbc                    beqz.n  a15, 2ef <system_adc_read_fast+0x4f>
     2b9:   fff6e1                  l32r    a14, 294 <system_adc_read+0x3c>
     2bc:   0c0c                    movi.n  a12, 0
     2be:   51d8                    l32i.n  a13, a1, 20
     2c0:   90dcd0                  addx2   a13, a12, a13
     2c3:   001d32                  l16ui   a3, a13, 0
     2c6:   1a13e7                  beq a3, a14, 2e4 <system_adc_read_fast+0x44>
     2c9:   902330                  addx2   a2, a3, a3
     2cc:   1122e0                  slli    a2, a2, 2
     2cf:   b30c                    movi.n  a3, 11
     2d1:   fff201                  l32r    a0, 29c <system_adc_read+0x44>
     2d4:   0000c0                  callx0  a0
     2d7:   f44020                  extui   a4, a2, 0, 16
     2da:   00a402                  movi    a0, 0x400
     2dd:   003d                    mov.n   a3, a0
     2df:   013047                  bltu    a0, a4, 2e4 <system_adc_read_fast+0x44>
     2e2:   043d                    mov.n   a3, a4
     2e4:   005d32                  s16i    a3, a13, 0
     2e7:   cc1b                    addi.n  a12, a12, 1
     2e9:   f4c0c0                  extui   a12, a12, 0, 16
     2ec:   ce9fc7                  bne a15, a12, 2be <system_adc_read_fast+0x1e>
     2ef:   11c8                    l32i.n  a12, a1, 4
     2f1:   21d8                    l32i.n  a13, a1, 8
     2f3:   31e8                    l32i.n  a14, a1, 12
     2f5:   41f8                    l32i.n  a15, a1, 16
     2f7:   0108                    l32i.n  a0, a1, 0
     2f9:   20c112                  addi    a1, a1, 32
     2fc:   f00d                    ret.n
     2fe:   00                          .byte 00
     2ff:   00                          .byte 00
     300:   ff ff 00 00
    ...


What is the relationship between the gain on the receiver and the delay time I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.

Part 2:

Hey Everyone,

I also had a question regarding what purpose each of the following delay serves in wireless communication.

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);// line in question ---------------------
  b >>= 1;
}

and the delay used in the regular blink program.

The regular delay used in the blink programs was what set the 2 microsecond delays.

Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?

I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.

In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").

In the graphic, "E" is the start bit for the next byte.

  I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). That is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.


Expanding analog inputs to the Arduino I need the Arduino to read about 100 analog inputs. Is this even doable? If not what is the maximum analog inputs I can read into the Arduino (The maximum non trivially would be to use the analog pins that the board already provides).

But can I expand those out? Thanks!!

There are two methods of doing what you want:

Add more ADC channels
Multiplex the existing ADC channels

SPI or I2C ADC chips are readily available in a range of resolutions, sampling speeds and number of channels.  They are fairly simple to add to any Arduino.

For instance the MCP3208 will give 8 channels of 12-bit resolution on SPI, which means 3 pins (MOSI/MISO/SCK) + 1 per chip (SS). So 1 chip would be 4 pins, 2 chips 5 pins, 3 chips 6 pins, etc.

Adding lots of chips to the SPI bus though can itself be troublesome with the increased capacitance of all those inputs meaning you have to reduce your communication speed somewhat or add extra buffering to drive the bus with more current.

I2C chips can be harder to have lots of them since there are only a limited number of addresses on an I2C bus - plus on many Arduinos the I2C is also two of the analog pins, which you may not want to sacrifice.

The second option involves using analog multiplexers (eg the 4051) to switch different sources in to the existing analog inputs.

A third option which you probably haven't considered is to have multiple arduinos (or other low-cost microcontrollers) each doing some of the sampling and then implementing some kind of communication method between them (or to a single master). This has the added advantage that it's then possible to sample multiple channels at once (one per microcontroller) speeding up your operation somewhat.


How do i run multiple functions simultaneously on a LCD screen? I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.

My code:

#include <LiquidCrystal.h>

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

int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     144
#define btnDOWN   329
#define btnLEFT   504
#define btnSELECT 741
#define btnNONE   5

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

 if (adc_key_in > 1000) return btnNONE;
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;
 return btnNONE;

}
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

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

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

void Second(){
  int First_Digit = 0;
  int Second_Digit = 0;

  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      }

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      Second_Digit = Second_Digit - 10;
      }

  }
}
void Minute(){
  int First_Digit = 0;
  int Second_Digit = 0;
  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      }

    lcd.setCursor(3, 0);
    lcd.print(First_Digit);
    lcd.setCursor(4, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;
      lcd.print(First_Digit);

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      Second_Digit = Second_Digit - 10;
      }

  }
}

Use the state machine model shown in BlinkWithoutDelay

unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

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

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

With this example, Second() is called only when the difference between "now" and the last time it was called is greater than secInterval. Likewise for Minute().

[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]

EDIT BASED ON UPDATED CODE SAMPLE

Issue 1:

In both your Minute() and Second() functions you have a sequence like:

lcd.setCursor(0, 0);
lcd.print(First_Digit);
lcd.setCursor(1, 0);
lcd.print(Second_Digit);
lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.

Issue 2:

At the start of the Minute() function, you have the following:

int First_Digit = 0;
  int Second_Digit = 0;

This means the variables First_Digit and Second_Digit are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as static so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:

static int First_Digit;
static int Second_Digit;

and similarly in the Second() function.

You're correct that digitalWrite() is not needed in your function as it is described. digitalWrite() is for changing a physical pin on the Arduino to a LOW or HIGH value (that is, a 0V or 5V voltage.) In the Blink without Delay example, ledPin and ledState are just variables to hold the pin identifier for the blinking LED, and the current state (LOW or HIGH) of that pin. Again, not necessary for your code, as you have described it.

SECOND UPDATE

Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the for loop in the Minute() and Second() functions, but it's unnecessary.

You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:

void Second() {
  static int second;

  second++;
  if (second>59) {
    second = 0;
  }
  lcd.setCursor(0, 0);
  lcd.print(second/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(second % 10); // Prints the remainder after dividing by 10
}

void Minute() {
  static int minute;

  minute++;
  if (minute>59) {
    minute = 0;
    // Probably want to increment an Hour counter here?
  }
  lcd.setCursor(3, 0);
  lcd.print(minute/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(minute % 10); // Prints the remainder after dividing by 10
}


Arduino HID keyboard does not work I'm using a ItsyBitsy 32u4, Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the Keyboard docs say are supported.

I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.

Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?

EDIT: the keyboard works on a different computer.

#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}

Keyboard.press() expects a character, but you are passing a character array. Also Keyboard.press() only presses but does not release the key. Keyboard.releaseAll() can be used to release all keys.

I would try:

Keyboard.press('A') ;  //note the ' instead of "
Keyboard.releaseAll();

or preferably:

Keyboard.write('A');   //handles press and release of basic keys


Why impedance between I/O pin and ground drops when Arduino is not powered I have a 4KHz 5V pulsed signal connected to Arduino UNO pin2 (ISR).

When the board is powered, the pulse is attached to ISR rising edge, and is working as intended.

I don't know the output impedance of the pulsed signal, but when the board is not powered, the pulse drops to 2V.

The resistance between pin2 and ground is about 500K when not powered. The resistance is infinite when powered.

The pulsed signal does NOT drop when connected to a 500K resistor.

Question:

What is the cause of the signal drop?
How to prevent it ? (It's not practical to disconnected the signal from Arduino, but I can make sure Arduino is always powered. How to deal with transient situations like reset ?)

Thanks in advance !

The Atmega328p (which is used in the Un[ (and actually all other AVR microcontrollers) has clamping diodes in the input hardware to protect it from overvoltage (above Vcc). When not powered, Vcc is at the same level as ground, so any positive voltage on an input pin is above Vcc. The protection diodes get conductive to protect the input hardware. Note, that the diodes can be fried easily, if a too high current flows through them. You should prevent that.
How to prevent it? By not doing it. You should never provide a voltage on an input of an unpowered chip (like any chip). If you really need to unpower the Arduino, you can prevent the voltage from reaching the input pin with a MOSFET.