Triggering Sound - Arduino + Contact Mic I previously created a sound installation using contact mics and computer (ableton+max msp) where sound would be triggered when people touched/tapped on the object/surface. Now I want to do something similar but want to get rid of the computer as it will be at a night club space where people will be walking around so I don't want to leave the computer there.
What I exactly want to do is to be able to load some sounds into arduino and again use contact mic on the object and when people touch it, the sound will be triggered. I know it won't be as creative as doing it with ableton where there is live-editing possibility but I'm happy with one type of sound in this one. I can probably find some codes here and there but I'm not sure what I exactly need to use to be able to do this.
I have few uno boards and lots of other bits that I've collected but haven't used before, so I would be very happy if you could help me as a novice.

Thank you

I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much.
It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier,  but if you're using little ones like 8ohm 0.25W with the music shield will be enough

some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground


NodeMCU and relay with VIN power Have read a lot of different things online, and I just ain't sure yet.
I'm trying to hook up a NodeMCU to control some relays. And want to power the NodeMCU by the VIN pin.
Anyone know if this setup is possible?
Or should I do it in another way?

Looks fine to me, I don't see any issues, assuming the PSU has sufficient 'grunt' to power both, and most will have.


Flash String Helper object as variable So I have a Bunch of commonly used char arrays to build commands in my library.
So to preserve memory, I have them put into flash, via PROGMEM ext,

typedef const char PROGMEM ProgChar;
ProgChar AT[] = "AT";
ProgChar AT_RST[] = "RST";

Then in my program I have it all go out to A port via:

*hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

This is handled by overloading the << operator;

static Print &operator <<(Print &obj, ProgChar* arg) {
  char pbuffbuffer[12]; //create a buffer,
  obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
  return obj;
}

But this also overloads the << operator for all const char* Which makes me have to do a workaround:

hws->print(1); //HACK

At first, I thought I would overload the operator to handle both a char* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.

So after snooping I find the __FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.

But the problem is, I cant find a good way to Create these:

const __FlashStringHelper MYVAR = F("Some text to be progchared");

Does not compile =/

Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use << for all types,

*hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...

Is this legal?

typedef const char ProgChar;
ProgChar AT[] = "AT";

I would think that the PROGMEM can't be in the typedef, i.e.:

typedef const char ProgChar;
ProgChar AT[] PROGMEM = "AT";


Arduino UNO And SD Card Custom csPin I've connected SD card module to Arduino UNO. I want to use PIN 10 for PWM DC motor control and because of that, I've connected CS pin directly to another pin (A3).

SD card is working properly, but after calling SD.begin(A3), it set PIN 10 to HIGH!
Immediately after SD.begin(A3) and set that pin to LOW, but meanwhile the motor took a small rotation.

I've digged into SD.cpp and Sd2Card.cpp, but couldn't find where this problem occured!

Any help appreciated....

The Solution:
Simply call SD.begin(-1) and it doesn't touch PIN10. Hope helps somebody else!

Pin 10 is special. It's the hardware chip select pin for SPI.  It is integral to the SPI peripheral in the chip.

That pin must be an OUTPUT for SPI to operate as master, or INPUT for it to operate as a slave.

It's a stupid design decision by Atmel if you ask me, but there you go.  So basically trying to use SPI at the same time as PWM on pin 10 is "undefined" and to be avoided.

Use a different pin for PWM or if you need more than there are PWM pins available then consider an external PWM control chip.

Just probing around to get more detail on exactly how it all works, this is what I have found:

digitalWrite() explicitly disables PWM on a pin.
The direction of pin 10 defines the SPI operation as master or slave.
analogWrite() sets pinMode(OUTPUT).
The SD library calls pinMode(OUTPUT) and digitalWrite(HIGH) on pin 10.

This means that:

SD.begin() will terminate any existing PWM on pin 10.
Using PWM on pin 10 will force the pin to output rendering SPI slave mode impossible

You should be able to use PWM on pin 10 if, and only if:

You use analogWrite() after using SD.begin(), and
You never want to use SPI slave mode.


Running many devices on 5V pin. How to provide external power I'm using my Arduino DUE 5V pin to power a lot of sensors and I'm worried about the drop in current.

I'm powering the board using the USB port. Is this the correct way or is there a different way of powering the board to make sure the current drop is limited as much as possible?

Thanks in advance.

There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.

You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.

Note there is a maximum current for USB too.


computer doesn´t recognize mkr1010 I´m learning how to use arduino mkr1010, when I wrote the program for control leds and to read BMP280 sensor with a web aplication and I uploaded the program to the board,  suddenly the computer cannot recognice the board. The power led of the board works, but I can't access to the board with mi computer, and I can't see in the COM ports neither in the "unrecognice device" to reinstall the drivers. I have tried with a few others USB cables and with another computer, and I have the same problem. I have also tried to press the button reset board and I still have the same result. What can I do to make my board work?

The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.
A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.
This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.


Serialprint and analogRead time How much time takes to print each sample using Serial.print and analogRead in each iteration?

#include <SoftwareSerial.h>
#define Sensor A0
void setup() {
  Serial.begin(250000);
  pinMode(Sensor,INPUT);
    }
void loop() {
  Serial.println(analogRead(Sensor));// RUN TIME??
}

It is quite complex to work out how "long" it will take to print.  Why?

If there is room in the serial buffer then the text just gets placed in that buffer. Takes almost no time at all to print.
You are printing a variable length string. The longer the string the longer it will take to print if the buffer is full.

However:

Each character consists of 10 symbols (8 data bits plus 1 start and 1 stop bit).
Characters are transmitted at 250000 symbols per second
Thus each character takes 1/(250000 / 10), or 40 microseconds to transfer through the actual wire.

So printing the number 100, which also has \r\n appended to it (characters 13 and 10) would need 5 characters. If the buffer is full it will take about 5*0.00004s = 200µs. If the buffer isn't full, it will take a fraction of that to just copy the data into the serial buffer.


ESP8266 Wemos D1 Retrieving Wrong AP Mac Address Using WiFi.BSSID and WiFi.BSSIDstr gives me some weird mac address.

the code is:

#include "ESP8266WiFi.h"
#include "ESP8266WiFiScan.h"

void setup() {
Serial.begin(115200);
//WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
Serial.println(WiFi.macAddress());
}

void loop() {
   int n=WiFi.scanNetworks();
   Serial.println(n);
   for (int network = 0; network < n; network++){
      Serial.println(WiFi.SSID(network));
      Serial.println(WiFi.RSSI(network));
      uint8_t* mac=WiFi.BSSID(n);
      char APmac[13];
      APmac[0]=0;
      for (int i=0; i<6;i++) {
        char buffer[3];
        sprintf(buffer, "%02x", mac[i]);
        strncpy((char *)(APmac+(i*2)), buffer, 3);
        Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
      }
      Serial.println(APmac);
      Serial.println(WiFi.BSSIDstr(n));

  }
  Serial.println();
  Serial.println();
  delay(10000);
}

The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference WiFi.SSID(); and WiFi.RSSI(); both spits out correctly.

edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong

This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:

String digit = String(*mac, HEX);

Try changing your example to:

uint8_t* mac=WiFi.BSSID();              // Gather the byte array
String APmac;
for (int i=0; i<6;i++) {
   String digit = String(mac[i], HEX);  // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
   if (digit.length() <2)
     APmac += String("0")+digit;        // Corrected capitalization error
   else
     APmac +=digit;                     // Corrected capitalization error
   //mac++;                             // Not necessary
   Serial.print("["); Serial.print(i); Serial.print("]");
   Serial.println(mac[i], HEX);
}
Serial.println(APmac);                  // Print the constructed String
Serial.println(WiFi.BSSIDstr());        // Print the pre-formatted string

Consider not using the String object, which may help condense the code a bit:

uint8_t* mac=WiFi.BSSID();
char APmac[13];
APmac[0]=0;
for (int i=0; i<6;i++) {
   char buffer[3];
   sprintf(buffer, "%02x", mac[i]);
   strncpy((char *)(APmac+(i*2)), buffer, 3);
   Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
}
Serial.println(APmac);
Serial.println(WiFi.BSSIDstr());


ESP8266 01 wifi module I have a weird problem  , as I.m trying to connect to esp8266 01 with Arduino Uno when i try sending commands from the serial it doesn't work but if i send it in a function in the setup phase it works

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup()
{
Serial.begin(9600);
esp8266.begin(9600);
delay(1000);
//sendData("AT", 1000);
//sendData("AT+CWMODE=1", 1000);
}

void loop() {
// put your main code here, to run repeatedly:
if(esp8266.available()) // check if the esp is sending a message
  {
      while(esp8266.available())
      {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
      }
  }
  if(Serial.available())
  {
    delay(1000);
    String command="";
    while(Serial.available()) // read the command character by character
    {
        command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

void sendData(String command, const int timeout) {
 String response = "";
 esp8266.println(command);
 long int time = millis();
 while ((time + timeout) > millis())
   while (esp8266.available()) {
     char c  = esp8266.read();
     response += c;
    }
 Serial.println(response);
}

I take your code as a test sketch and will not comment on the terrible way you read Serial input.

The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use print to send the command to esp8266.

Or set in Serial Monitor "No line ending" and let in sketch the println to send the command. println adds \r\n to printed string.

If you had only "New line" set in Serial Monitor and used println the resulting command was for AT firmware disturbing "AT\n\r\n".


arithmetic operation outcome differs from the expected outcome I am writing a function

void Sound_Play(int frequency,int millisec)

A part of this function is:

  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:

millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21

Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it?
Thanks!
Bhuvnesh

Once again an example to Why should I learn C/C++ first before learning Arduino.
The main point here is: know your data types.

Your calculation millisec*frequency/1000 would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.

Unless stated otherwise I assume your variables millisec, frequency and counting are of type int. int has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)

It is also signed, that is why it can hold values between -32768 and 32767.
You calculation millisec*frequency evaluates to 500 * 220 = 110000 which is many times larger than the value that can be represented.

You can do two things:

Use long which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer uint32_t.
If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).


Host a webserver on esp32d that has a hyperlink that triggers an ardiuno song through a buzzer I would like to use my ESP32D to create a wireless access point and host an html page that has a hyperlink and a few other things on it that triggers an arduino song (rickroll), and plays it through a buzzer.
I just need to know how to host the webserver and make the trigger hyperlink work, right now the html is set to send "trigger" whenever the link is pressed.
html file https://pastebin.com/sGmPPVYG
(Arduino-song)https://github.com/robsoncouto/arduino-songs/blob/master/nevergonnagiveyouup/nevergonnagiveyouup.ino

This is a partial answer. I assume you already know how to build a Web
server on you ESP32, and how to react to client requests. If not, there
are tutorials available on the Internet. Here I will specifically
discuss the issue of the hyperlink.
You wrote:
Click Here To Trigger The Rick Roll!/a>

Not only the closing tag is incorrect (it should be ), but such a
link is likely not what you want. The semantics of an hyperlink is “go
fetch that resource and display it here, replacing the current page”.
Unless you do have a displayable resource (Web page, image...) on your
server actually named “trigger”, you do not want an hyperlink. You want
a clickable item that may look like an hyperlink and, when clicked,
triggers a request to the server, but without replacing the current
page.
So I would start by replacing the link by a generic container:

Click Here To Trigger The Rick Roll!

Then, style it like a link. I don't quite like the underlining, but you
can add it if you wish:
#trigger {
  color: blue;
  cursor: pointer;
}

Then, within a


How do I output tone() and audioFX board output through a single speaker? I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.

I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.

How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?

Note that only one or the other will be playing at one time.

Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.

I will draw a circuit in the morning.


How can I discover attached motor shields in code? I'm using the Motor Shield v2 and I'm looking for a way to automatically discover the addresses of attached motor shields.

If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.

This sketch is derived from the I2C Scanner sketch found here: I2cScanner

// This sketch tests the standard 7-bit addresses.
// Devices with higher bit address might not be seen properly.
#include <Wire.h>
byte shieldOneAddress = 0x27;
byte shieldTwoAddress = 0x32;
byte error, address;

void setup(){

  Wire.begin();
  Serial.begin(9600);
  Serial.println("Scanning for shields...");

  for(address = 1; address < 127; address++){

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if(error == 0){
      if(address == shieldOneAddress){
        Serial.println("Shield One is connected.");
      }
      if(address == shieldTwoAddress){
        Serial.println("Shield Two is connected.");
      }
    }

  }
  Serial.println("Scan complete.\n");
}

void loop(){}


Please explain this OneWire communication with Arduino Uno and DS2502-E48 The goal is to read the MAC address from a DS2502-E48 chip.

I think I accomplished this goal too with the following code, but I can't get behind at how this works.
I had a similar program with a PIC chip as reference.

I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses.
Where'd I normally attain the information so that I know I have to write: cc ,f0 , 0, 10 , read a random byte, and then I'm at the right position for MAC.

#include <OneWire.h>

OneWire ds(2);
void setup()
{
  Serial.begin(9600);

  byte i;
  byte dataLength;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
    Serial.print("No more addresses.\n");
    ds.reset_search();
    delay(250);
    return;
  }

  ds.reset();
  ds.select(addr);

  delay(1000);     // maybe 750ms is enough, maybe not

  present = ds.reset();
  if (present != 1 )
  {
    Serial.println("No device present, exiting...");
    return;
  }

    ds.write(0xCC);//SKIP_ROM
    ds.write(0xF0);//READ_MEMORY
    ds.write(0);  // ?
    ds.write(10); // ?
    ds.read();    // ?
    dataLength = ds.read();

    for ( i = 0; i < dataLength; i++) {
    data[i] = ds.read();
    if ( i>3){
      Serial.print(data[i], HEX);
      Serial.print(" ");
    }
  }
}

void loop()
{

}

I found a nice writeup on this on a blog.  To quote his experimental findings:

  Comparing to the OneWire spec, we can tell it’s writing 0xCC, which
  should be SKIP_ROM. Following that is 0xF0 (ReadMem), and two bytes
  starting address: 0x08, 0x00.

Based on this, the zero and 10 that you are writing are apparently an address value.


When should you worry about interference affecting the analog input? I made something that uploads the measured current to Thingspeak. Everything works, but i did not place the DC to DC converter on the board because i was worried that it would interfere with the analog input. Also the ESP8266 is very close to the Arduino Pro Mini. Could it affect the reading?
Could i have put the DC to DC converter on the board without any problem?

230VAC to 12VDC adapter(not on the picture) --> 12VDC to 3,3VDC(on the picture)-->the prototype board

Sensor: SCT-013-030 30A = 1V

Noise reduction involving Analog to Digital Conversions can be done in many ways.  Common software solutions involve averaging multiple conversions.  Exponential smoothing is one such method.  One advantage of exponential smoothing is that it can be applied to an endless stream of conversions.


Can FastLED be made faster? I am using FastLED to drive 16 pixels on an addressable  WS2812B RGB LED strip. My application has extremely tight timing constraints. Specifically, I need to turn the LEDs on and off within less than 1 ms. I tried FastLED but it requires a minimum of 2.5 ms to execute the Show command, regardless of the number of LEDs attached. I analyzed another library and that one has the exact same limitation. In fact, I found a snippet of code that said roughly: "if this operation performs in less than 2500 us, then wait idly until the 2500 us have passed. Apparently this wait is necessary due to timing requirements of WS2812x strips. Does anyone have any advise about other addressable RGB LED strips or libraries that can be turned on and off within 1 ms?

By default the fastLed is limiting the refresh rate to 400 fps (i.e. 2.5ms).
You can disable that with FastLED.setMaxRefreshRate(0);


What does serial data look like on an oscilloscope? How I can find the data field on oscilloscope at 300 baud or at 9600 baud?
Could someone show me picture on oscilloscope plase.

This is the picture

at 9600 Baud

I had these images lying around so here is an example of "Fab" being sent at 9600 baud:

And now a single byte (the letter "F"):

A - no data (Tx is high)
B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
E - The start bit for the next character.

The time for one bit is shown on the logic analyzer as 0.1041667 ms (that is, 0.0001041667 seconds). This agrees with the inverse of the baud rate:

1 / 9600 bits per second = 0.0001041667 seconds per bit

Looking at your photo, my guess is you have inverted logic here. That is, RS232 levels (where 5V is a 0-bit and 0V is a 1-bit). Thus (and this is a guess because all the bytes are close together):

I marked the start and stop bits, and put a dot for each bit inbetween.

Also see What is Serial.begin(9600)?


Can anyone explain how this code can be converted to work on a Arduino Uno I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.

#!/usr/bin/python3
import RPi.GPIO as GPIO
import time

# this many mm per bucket tip
CALIBRATION = 0.200
# which GPIO pin the gauge is connected to
PIN = 17
# file to log rainfall data in
LOGFILE = "log.csv"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# variable to keep track of how much rain
rain = 0

# the call back function for each bucket tip
def cb(channel):
    global rain
    rain = rain + CALIBRATION

# register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

# open the log file
file = open(LOGFILE, "a")

# display and log results
while True:
    line = "%i, %f" % (time.time(), rain)
    print(line)
    file.write(line + "\n")
    file.flush()
    rain = 0
    time.sleep(5)

# close the log file and exit nicely
file.close()
GPIO.cleanup()

This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes.  if there is a specific programming problem it should be addressed separately instead of handing out working code.

const int CALIBRATION = 0.200;   //Calibration Constant
int pin = 2;                     //Pin it's on, this is int0 for uno.
volatile int rain = 0;           //Used in interrupt routine

void setup() {
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
}

void loop() {

     /* Output OR LOG DATA HERE
        Also You need a Time Library and RTC (Real Time CLock) the above
        code is for a raspberry pi that has all that. */

}

void cb() {
    rain = rain + CALIBRATION;
}


Why is Serial.Write that slower when writing x+1 characters than when it is writing x characters? Using Serial.Write() in a time sensitive application. I realize that the number of characters being written not only had an impact on the time spent writing in the buffer, but actually had a bigger impact than expected.

Consider the following sketch, which measures the time it takes to write NB_CHARS characters, using Serial.Write(). I sampled 1000 times in order to get a more reliable measure.

#define NB_CHARS 100

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

  uint8_t chars[NB_CHARS];
  for (int i=0; i<NB_CHARS; i++)
  {
    chars[i] = 66;
  }

  unsigned long time1, time2;
  unsigned long totalTime = 0;

  delay(100);

  for (int i=0; i<1000; i++)
  {
    time1 = micros();
    Serial.write(chars, NB_CHARS);
    time2 = micros();
    totalTime += time2 - time1;

    delay(10);
    Serial.println("");
    delay(10);
  }

  float meanTime = (float)totalTime / 1000.0f;
  Serial.print("meanTime = ");
  Serial.println(meanTime);
}

void loop()
{

}

Here are some results for different NB_CHARS values:

NB_CHARS: Time (microseconds)
1: 12
2: 18
3: 24
[...]
99: 2912
100: 2997
101: 3082
[...]
199: 11412
200: 11497
201: 11582

It seems that at first, each new character adds around 6 microseconds of delay, but afterward it becomes 85 microseconds. I tested every values from 1 to 100 to find where it changes and it seems to be right after 70:

It seems weird to me.

A quick Google search gets me to this 2013 post by Tom Carpenter. I am not sure how true this is or if it is still relevant.

  Part of the trouble is that the Hardware Serial library is so
  incredibly inefficient (I don't think they could have made it less
  efficient if they tried!). After each byte is sent, there is an
  interrupt called which spends a lifetime loading the next byte into
  the buffer to send. The write function also wastes lots of time doing
  calculations as to where to put a character in a ring buffer.

  [...]

Why is there such a "long" delay for each character and is there a way to make it faster?

What happens after 70 characters that slows it down even further?

The Arduino core has a 64 byte transmission buffer.  Characters are sent out of that buffer by the hardware.

When you blast lots of characters out of serial the first 64 just get put into that buffer - almost instantly.

Once that buffer is full your sketch blocks until the hardware has sent a character to make room.

Since it's sending right from the moment you place the first character into the buffer you get a little more than 64 bytes worth of buffering time (64 + the number that have been sent by the time the buffer fills).

From that point on you are entirely at the mercy of the baud rate you have chosen.

To get more predictable throughput (and maximise the speed) you should bypass the Ardiuno core and manipulate the UART registers directly.


How to control Arduino using mBlock and Bluetooth? Is it possible to control an Arduino using mBlock and Bluetooth?

Assuming yes, I tried various things, but was not able to come to a conclusion.

I am trying to get this combination working using a HC-05 Bluetooth module. I am not sure if my Bluetooh setup is the problem or is mBlock is not able to recognize the COM port provided by Bluetooth.

I can see the COM device (in fact two?) when I pair HC-05 with PC. I have the following questions based on whatever I have tried so far:

When I connect HC-05, should I connect TX to TX OR reverse them?
There are varying articles describing both ways of connection.
How much baud rate do I need to set on the Bluetooth device?
Do I need to use the voltage divider for RX? Again there are varying tutorials.
Is mBlock default Arduino firmware sufficient for such setup?

When I connect HC-05, should I connect Tx to Tx OR reverse them?

  There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

  How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

  Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

  Is mblock default arduino firmware sufficient for such a setup?

What is mblock?


Is there a manometer available to use with Arduino? I used an analog manometer in a plumb system. I would like to actually track information about water pressure across an entire building on different points and record all this information to analyze changes on pressure. I was wondering if there is a manometer that can be used with arduino. Or if there is some other homemade solution?

If there is any electronic sensor with an analog output that would be enough.

Bruno, there are a number of sensors available, try an Ebay search, to do what you want.  However, you need to determine what pressure range you are looking at.  As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems.  An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs.  you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry.  As you are aware to measure pressure all sensors will need to be invasive into the pipework.


HD44780 Extended non-display DDRAM? According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.

The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.

But it is workable for sure.


Arduino Yun can no longer send to Dropbox A long time ago I had set up an Arduino Yun to send files to Dropbox... I tried now and it ends in "killed" when trying to install the latest Dropbox Python module.

pip install (six, urllib3, etc etc) does work individually without running out of memory. Unfortunately when I install all but Dropbox, and then put the Dropbox module code folder in the current directory, it does start to import Dropbox with import dropbox but ends up with the KILLED message.

Is there a way I can connect to my current Dropbox without it using all of the 60mb of RAM and quitting... I keep getting the error with version 2.1:

  Error.Cannot connect to Dropbox
  [400] u'v1_retired'

I'd eventually figured out how to do it running the latest Dropbox module installed into the sd card where there was room.


Keyboard/mouse libraries with UNO I have an Arduino Uno Rev. 3 and I'm trying to make it so that the Arduino can send a key press / mouse action to the computer. However, these libraries are restricted to a few other versions of the board. Is there another alternative method to doing this without actually pressing any buttons/interacting with the arduino other than USB? Thanks!
Link

It is actually possible, but not easy.

The main MCU on the Uno, the ATmega328, is not capable of using the USB connection at a low enough level to make this possible. The other MCU on the Uno R3, the ATmega16U2, is. You can reprogram it to act as almost any arbitrary USB device.

Since the '16U2 has no connection to digital pins 2 and up or to any of the analog pins, you would have to program it to communicate with the '328 (or an external chip) via UART, and then have another program running on the '328 that would communicate with the other pins.

Note that you will need an external programmer for this, since once the '16U2 is reprogrammed you will lose the ability to program the '328 until you restore the original programming. Using another board running ArduinoISP will work for this.


Can you connect BH1790GLC and TMP117 sensors to an Arduino board? I would like to use those two components for an upcoming project :

BH1790GLC heart rate sensor
TMP117 temperature sensor

I especially like the fact that they’re so tiny.

Could I connect them directly to an Arduino board or some other well-known microcontroller ?

Yes, the sensors will work with microcontroller(s). What you look for is the interface they use. In this case it is I2C interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

Choose 3V powered microcontroller
Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


Arduino Wall Wart and Relay Board Power Supply I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ - sorry it's not very descriptive).

The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.

Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

Here is the circuit without the external power, using a small LED:

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

Is there a way to use the wall wart as the power supply? Do I even need the relay board?

You will need the relay board.  The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.

If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work.  If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.

If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.

"How do you split the power?" I hear you say, "do I need any extra hardware?"

That depends, how attached are you to your wall wart's cable?  The way I have done it is to UNPLUG the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board.  Then use jumper wires to take an additional feed off to the 12V circuit.

CAUTION Ensure you get the polarity of the wires the right way around.  You can test this with a volt metre.  I suggest red electrical tape to mark the +ve wire.

IF YOU ARE NOT CONFIDENT DON'T DO IT!


Controlling a 240v AC high current relay Should I use 2 relays, one for the hot wire and one for the neutral ?
I'm talking about 16A.

Use 1 relay, more precisely a DPST (Double pole, single throw) type. You'll only need 1 signal to drive both, and be sure that both lines are switched off. Electrical installation regulations require double throw relays/switches for certain applications, e.g. in wet rooms like bathrooms.

Note that relays are more delicate devices than they appear to be. A 16A relay may not always be suitable for switching 16A. They have to be derated according to their type of load. And that is almost everything. Not only for capacitive or inductive loads you'll have to limit the current to a fraction of the rated 16A, but even for incandescent lighting (due to the high current peak when switching on). See the manufacturer's datasheet or application documents for the amount of derating.


My computer dose not recognise my Arduino Uno I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.

Why isn't the board interfaced successfully? How should I troubleshoot that problem?

Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.


Splitting SCL and SDA pins For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.

I am using an Arduino UNO and a playstation 2 controller with the following guide:
http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.

But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function ps2x.config_gamepad().  In it's parameters you can set the pins that the library will use.


How do I connect velostat to an arduino? I have some velostat that I'd like to hook up to an Uno. At the risk of sounding dense...how do I do that?

Ultimately wanting to get readings of pressure from the velostat, just not sure how or what wires to connect where.

Usually a variable resistance sensor is used in a voltage divider circuit:

In the above example a thermistor is connected to the positive supply and a pull down R1 is connected to ground.  The voltage where they meet is measured using one of the Arduino's analog inputs pins.

Choosing R1 is tricky.  If it is too large compared to the variable resistance sensor the voltage fluctuation at Vout will be too small to measure.  The same problem exists if R1 is too small compared to the variable resistance sensor.  Also, you need to mind the current through the sensor.  If the combined resistance of R1 and the sensor is too small the current may damage the sensor, over heat R1 and / or put a heavy drain on your power source.


ADS1115 : measuring 5v voltages and powering with 3.3v I have a project where I need to measure 0 - 5 V. I’m using a ADS1115 to have a better precision, connected to a ESP12. Since the ESP is only 3.3 V tolerant and the ADS powered by 5 V (because it needs to be powered a the same voltage as the measured voltage), I put the two pull-up resistor of the I2C bus on 3.3 V.

Is it safe to operate like this?

Is your arrangement bsafsm Yes, perfectly.

Is your arrangement a good idea? No, it is not.

When the ADS1115 is run at 5V it needs at least 3.5V on the I2C bus to properly register a HIGH.

However you can pull up to 5v instead and you won't have a problem.  Not only is the esp8255 tolerant of 5v, but that 5v is severely limited in current by the pull-up resistors, so even non tolerant inputs would have a hard time complaining. Worst case scenario, the ESP8266 pulls the bus down to maybe 3.8v (3.3v plus an ESD diode drop) which is fine for a logic high on the ADS1115.

However, if you want to do things properly, you really should use a proper I2C level translator.


Having trouble using RTC if I set an ISR for a 1 second timer I built a sketch using some timer ISR code to get a trigger every second.  (for the Atmega328 chip I use the following code I got form the internets.  It works)

It runs fine and I get a trigger/callback every second.

void setupAtmega328()
{
#ifdef __AVR_ATmega328P__

//      traceDebug("setupAtmega328() entry");

    cli();  // stop interrupts

//    traceDebug("setupAtmega328() 1");

            //set timer1 interrupt at 1Hz
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1 = 0;//initialize counter value to 0
              // set compare match register for 1hz increments
    OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
                  // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS12 and CS10 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
//  traceDebug("setupAtmega328() 2");
    sei();//allow interrupts
//  traceDebug("setupAtmega328() 3");

#endif
}

I also wanted to add the capability of a real time clock (RTC) so I got a DS3231.

I downloaded and ran the sample app from this RTCLib on github

The sample code works fine when running under the Arduino IDE

However, when I add the RTC code to my sketch I don't get the results I want/expect.

Specifically, the program seems to hang/halt at the call to:

cli();

I am new to the Arduino platform and not sure what I am missing.
What do I need to do to get the RTC to work in conjunction with an ISR?

I wired the RTC according to the directions from Adafruit's site

I have other arduino boards that use different ISRs, but I have not tried them yet with the rtc since the 328 seems to be the standard arduino boars that is used to do initial work/testing.

How can I use the 3231 RTC AND a 1 second ISR/callback?

EDIT:
I removed the trace/serial output - I had originally added those to track the code to see where I got but i think I exacerbated or added problems in doing that.

for those interested the code is at https://github.com/tjurik/Intervalometer

In the Arduino you don't have control how are some essential parts implemented.

For example delay function requires interrupts to be enabled or it'll be deadlocked (for sure).

Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your traceDebug is little bit longer.

In general ISR should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.

volatile bool flag = false;

ISR(...) {
  flag = true;
}

int main() {
  init();

  while (1) {
    if (flag) {
      do_something();
      flag = false;
    }
  }
}


Schematic: 1 Button and 1 Potentiometer Sketch Schematic: 1 Button and 1 Potentiometer
Sketch: Each time the button is pressed, acquire the value of the potentiometer in a vector of 10 positions and print it on the serial monitor or LCD display.
At the end print the average (sum of values / 10)
#define BUTTON 5
#define ARRAY_SIZE 10
int counter = 0;
int valori[ARRAY_SIZE];
int pinPotenziometro = A0;
int statoPresenteBottone = LOW; //why so LOW?
float media = 0.0;
void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
  for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
}
void loop() {
  if (counter > ARRAY_SIZE) {
    counter = 00;
    media = 0.0; // when we fill array fully - we start again
    for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
  }
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
    valori[counter] = analogRead(A0);
    media = media + valori[counter];
   Serial.print("Average: ");
   Serial.println(media / counter);
   Serial.print("Button pressed times: ");
   Serial.println(counter);
    statoPresenteBottone = LOW;
    counter++;
  }
}

That's what I did but it doesn't work like I want. I need to get the average of the 10 numbers I acquired at the end but it does it each time.

I will not write the code for you (as explained in my comment to your duplicate question), though I will point out some problems in your code and give hints how to solve them.
Mainly your program structure isn't correct. The first hint is to not look at real C/C++ code in the first step. Write down step by step, what the program should do. Here I'm doing this for you, as I understand your description:
Initialize everything (setup)
loop
  if button was pressed
    loop 10 times
      take analog reading and add it to the sum
      delay 10ms (for example) to keep the reading regularly spaced
    calculate average by dividing the sum of values through 10
    print average over serial

And from this pseudo code you would start to write the corresponding C/C++ code for the Arduino. For the "Initialize everything" you can reuse your current setup() function (assuming you already have a pulldown resistor on your button pin). What I wrote as "loop" would just be the loop() function. The "if button was pressed" will be a if(digitalRead(button_pin)). The 10 analog readings could be written with a for loop, adding the analog values to a local variable and delaying a bit to make the readings regularly spaced in a specific distance (you can change that to your liking. You could also delay way shorter with delayMicroseconds()).
And now some notes for your original code, that you should keep in mind for writing the new one:

You have the lines (I omitted some lines, that are irrelevant to my point here):
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
      statoPresenteBottone = LOW;
  }

Follow the logic here: We read the button state and save it in a variable. Then we loop while this variable is HIGH. But already in the first iteration of that loop we are setting the variable to LOW. That means the while loop will not loop. It will only run once. Also: If you want to check if the button is still HIGH, you actually need to read it. The variable statoPresenteBottone will not change automatically, when you press or release the button. You need to actually read the button pin with digitalRead(BUTTON). The variable is just a small space in memory, where you store data (like the last read state of the button). It is not connected to any hardware. That has to be done by the software.

You use an array for the analog values, though in this case you don't need that. For calculating the average it is enough to just add up the values and then divide by the number of measurements. The array is just not needed. And when removing the array, the variable counter and the complete array reset code becomes unnecessary and can be removed.

We cannot see your circuit, so please note, that you need a pulldown resistor on the pin, that you connected to the button. Otherwise you would have a floating pin, resulting in a randomly and often rapidly changing pin state. Often the people instead use the internal pullup resistor of the Arduino, by using pinMode(pin, INPUT_PULLUP) and connecting the button to ground instead of Vcc. Though that reverses the logic (LOW then means the button is pressed, HIGH means it is not pressed). It's up to you, want you want to use.

In the comments others pointed out button debouncing. That is an important issue, though for the above pseudocode structure that is not that important I think (this depends on how exactly you want the button to behave). So you should keep debouncing in mind. There are many tutorials about that online. I often suggest using the Bounce2 library, since it already handles the button debouncing for you and is fairly easy to use. Though - as said - I don't think that you really need it in this case.


AccelStepper help - it just won't move! I should begin by saying I am not a programmer, do not really know much about programming, and am programming an Arduino Uno for the first time. I am using a Nema 23 motor (23HS22-2804S) with a microstep driver (ST-M5045). Within the following code is the description of what I need the program to do:
#include <AccelStepper.h>

/* Using a stepper motor,
 rotate a vibrational model using gears interconnected by springs
 in such a way as to induce torsional vibration, which should be visible by comparing
 movement of juxtaposed rotating gears with markers painted on. */

AccelStepper stepper(AccelStepper::FULL4WIRE, 2, 6, 4, 8);

int Microstepping = 8; /* Microstepping factor, as set on the ST-M5045 control board.
                          Multiplies the number of steps per revolution on the stepper motor.
                          Reference controller manual for adjustments to this number. */
int Steps = 200; /* Number of steps on your stepper motor.*/
int SPS;
int Amp;
int Freq;
// int SC;
int n = 2;
int i;
int totalSteps = Microstepping * Steps;

/* It should be noted that the Microstepping and Steps factors are not necessary, and adjusting the microstepping factor
 *  on the fly will not break the code. However, be aware that changing the microstepping factor by more than one interval
 *  at a time can cause the motor to not keep up with the sudden changes, i.e. losing torque or vibrating/stuttering. */

void setup() {               // THIS RUNS ONCE //

  // read potentiometers; raw inputs from 0 to 1023 //
  SPS = analogRead(0)*0.733; // MAX RPM ~28, max speed ~750 steps per sec (speeds above 1000 steps per second are unreliable,
                             // according to AccelStepper documentation)//
  Amp = analogRead(1)/20;     // MAX AMP ~51//
  Freq = analogRead(2)/170;   // MAX FREQ ~6 Hz//

  stepper.setMaxSpeed(SPS);
  stepper.setAcceleration(SPS/1.5);

  int nextStop = totalSteps/Freq;

  stepper.moveTo(nextStop);
  stepper.run();
}

void loop() {
  int nextStop = totalSteps/Freq;

// reaches here, doesn't execute if loop.
   if(stepper.distanceToGo()== 0){
     SPS = analogRead(0)*0.733;
     Amp = analogRead(1)/20;
     Freq = analogRead(2)/170;
     i = SPS - Amp;
     if(i <=0)
       i = 1;
     stepper.setSpeed(i);
     stepper.moveTo(nextStop*n);
     stepper.run();
    }
    n++;
}

When I use Serial.println() to check where the program is working and where it isn't, I see that it completes the setup loop without ever moving, and in slightly different versions of the same code, it has entered the if() statement and executed it (also without moving.)
An earlier version of the program runs and executes all statements, but only moves a maximum of about 20 steps per second, without the fluctuations in speed I call for, and doesn't respond in real time to any input from the speed potentiometer that puts the speed above 20.
Ideally, the program would run the demo at full speed, and freq times per second, it would slow down just enough to be noticeable as a torsional vibration.
I have tried running the program with and without the run() lines, and I have tried using runToNewPosition() in attempts to get the program to stop and properly execute the movement.
I made the setup loop as close as possible to the setup loop in bounce.pde, the example program in the AccelStepper documentation which moves the stepper motor between two points repeatedly, accelerating and decelerating before changing directions. The reason I did this is because I know that the setup loop in bounce.pde works, and so I would feel more confident that my setup loop is not the root problem.
Any help you can offer me is appreciated! Thanks for your time.

Please read the documentation for the AccelStepper library.

Poll the motor and step it if a step is due, implementing
accelerations and decelerations to achieve the target position. You
must call this as frequently as possible, but at least once per
minimum step time interval, preferably in your main loop. Note that
each call to run() will make at most one step, and then only when a
step is due, based on the current speed and the time since the last
step.

source
You are only calling run once, after setting a new position.
Move stepper.run(); out of the if statement, the the end of the loop function.
      ...
      stepper.moveTo(nextStop*n);
    }
    stepper.run();
    n++;
}


How to implement multiple LED modes in a sketch with potentiometers? My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...

I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.

How do I implement? Mode selection via a potentiometer?

Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using analogRead(), you just need to decide what to do with it.

Assume potVal has the value of the pot.;

if (potVal < 256) {
    // Pot is one quarter turn or less
} else if (potVal < 512) {
    // Pot is between 256 and 512, so its more than quarter but less than half
} else if (potVal < 768) {
    // Pot is between half and 3/4ths of the way there
} else {
    // Pot is greater than 3/4 of it's full range
}

So I have broken it down into four quadrants for you, but you can do it however you like.


Can a shift register be used to extend the Arduino pins when an ethernet shield is mounted on the Arduino? I am currently working on a wireless home automation system. The system is connected to a wireless network in the home via the ethernet cable connected the ethernet shield and router. Hence, I need more pins on the Arduino to connect the appliances to be controlled in the home.

You can control a shift register with shiftOut or bit-banged SPI.

My page about SPI has a small library that does bit-banged SPI.

It is also possible to control a shift register using the same pins (MOSI/MISO/SCK) that the Ethernet interface uses, as long as you use a different SS (slave select) pin for your shift register. This may not be practical if the Ethernet card is active all the time. It is probably easier to do the bit-banged SPI or use shiftOut.


Light up multiple LEDs with standard Arduino Uno I am trying to find out if it is possible to light up multiple LEDs with a standard Arduino Uno. Say I have 500 LEDs and logically I give each one of them a number from 1 to 500. In my test scenario I'd like to say something like "LED No 275 On" and as a result only have this single LED turning on while all others remain off.

Is there a way to do that at all? Or will I have to use many different Arduino Unos for that?

Probably the simple answer is to use 63 8-bit shift registers, with a LED and resistor attached to each shift register output pin. There are many good examples of using shift registers to add output ports on the internet.

The shift register solution will let you turn on just one LED at a time, or if your power supply can stand it, all 500 at once.

This question shows how to go about the expansion Is there a way to have more than 14 Output pins on arduino?
It also gives some other valid options.


WiFi.setOutputPower(); I'm trying to cut my esp8266 range down to about a meter to save power.  I know that I can adjust output power but I don't know enough to understand what a given setting will actually yield.

I can set zero to kill it or 20.5 to set max range, but what setting is appropriate for a meter or so?  Is there a rule of thumb?

The actual WiFi range is highly dependent on many more factors than just the TX power:

The antenna gain, directionality, and orientation of the receiver
The antenna gain, directionality, and orientation of the transmitter
The proximity of radio-reflective objects nearby (metal)
The proximity of radio absorbing objects nearby (humans)
RF Black Magic

In practice, test your situation by running a series of tests at lower and lower power settings until you get an unreliable connection, then bump it up a couple of notches from there.

Do not rely on transmitter power for security, however. You cannot stop someone from pointing a high-gain antenna at your device and communicating with it from a distance farther than 1 meter. TX power reduction should primarily be for energy conservation.


What terminologies and concepts describe the codes that follow a format of Text1.Text2()? I'm just really curious because some codes really follow a format like this. Examples include serial.begin(), serial.println() and when I used servomotors the left part was the name of the servomotor, which I declared. I want to know what concept does the code with a format of Text1.Text2() refer to? What do you call Text1 and Text2? Are there official or commonly used terminologies for the concepts and parts such as "variable", "statement", "code"?
To add to my understanding, it appears that Text1 refers to an object and that Text2 has the concept of "function" where it performs something related to the object. Though I would think that another terminology would be possessed by Text2 other than function to distinguish it from a function since it is required to be written in the format I mentioned, which next to the object with a period separating them and no spaces at all.

The over-arching concept is Object Oriented Programming (OOP).
The terms I was taught at University - taking Serial.println() as an example:

Serial is an instance of a class (in this case HardwareSerial), sometimes called an object.
println() (a function in a class) is a method of a class.
A "variable" in a class is called a property of a class.

A commented code example:

class Foo { // This is the *class*

    public: // These symbols are accessible from outside the class

        int bar; // This is a public property

        void baz() { // This is a public method
        }

    private: // These symbols are only available from inside the class

       int meep; // This is a private property

       void moop() { // this is a private method
       }
};

Foo bar; // Instantiate an instance of the Foo class and call it bar.


ESP32 USB HID/MIDI library (not the BLE one) I couldn't find any library to use an "old" ESP32 (not the new ESP32-S2) as an HID connected physicaly to the Usb port (not over BLE pairing) to send keystrokes to the PC ...
Is there any solution? Any code example, so far?
Thanks in advance!

The ESP32 doesn't have USB. You can't do USB communication. All it has is (like the UNO) a USB to UART interface chip. Unlike the UNO this is not programmable (more like a cheap Chinese knock-off UNO clone in that respect).
You would need to couple it with a microcontroller that has USB and program hat to be your USB interface and communicate with it over some other communication medium, such as UART or I2C.


How do I configure WEMOS D1 R2 Vin pin to output max voltage? I am in need of 12VDC from my Wemos D1 R2. How do I configure the Vin pin to output the max (I think its 12VDC)?

board: Wemos D1 R2 V2.1.0 - ESP8266 (LOLIN D1 R2)

Pinout here in pictures below

You cannot. You are misunderstanding, what that pin is. Vin means Voltage In. It's a voltage input, connected to a voltage regulator, which will regulate the provided voltage at that pin down to 3.3V for the Wemos to work with. It is not an output. The regulator cannot convert the 3.3V from the Wemos to 12V. That is not, what it is build for.

To get 12V you either need a separate 12V power source, or you need to buy a stepup/boost converter, which brings the 3.3V (or 5V, if you are powering from USB) up to 12V. For the latter, be sure, that the converter and the source, where you get the input voltage of the converter, can provide enough current for your use case.


What is micro C in a circuit diagram? This is probably a simple question but I am a beginner with these things. What does the micro C part of the circuit diagram mean? The diagram is from the datasheet of the tssp77038 IR receiver. Does it want there to be a capacitor on the output?
(http://www.farnell.com/datasheets/1915248.pdf?_ga=1.234529246.1943069395.1480959857)

It means "Micro Controller" - you know it as "Arduino".


How would you send clock impulses to a camera with an Arduino Mega? Hardware newbie here and I need to know how to connect my TSL 1401 line scan camera to an Arduino Mega so that I can send it the needed impulses. The Mega has a hundred different sockets and the Schema just scared me when I looked at it.

I just want to know which socket I can connect to the CLK and SI ports of my camera so that I can get and an analog output of pixels.

It depends on the camera that you're using but you send in impulse just sending digital write signal, waiting a little bit and then turning it off. You do this over and over again until you have all the pixels. Here is an example where I send 128 impulses:

  for(int i = 0; i < 128; i++)
  {
    digitalWrite(CLK, HIGH);
    delay(1);
    digitalWrite(CLK, LOW);
    delay(1);
  }

Depending on the hardware you are using you might have to send a SI (signal impulse) prior to the CLK impulses and the delay in between them will vary. The best thing to do is to read the documentation to find these figures.


Can't read data from registers using I2C I am trying to read data from the registers 6, 7, 8 and 9 of the STC3100 (Data Sheet) using an arduino uno.
I followed this tutorial: https://howtomechatronics.com/tutorials/arduino/how-i2c-communication-works-and-how-to-use-it-with-arduino/ And adjusted the device and register adress accordingly.
This isn't working and instead of returning the data on the register I'm just getting 16 over and over again.
Here is my code:
#include <Wire.h>
int ADXLAddress = 0x70;

#define X_Axis_Register_DATAX0 0x08

#define X_Axis_Register_DATAX1 0x09

#define Power_Register 0x00

int X0,X1,X_out;

void setup() {

  Wire.begin();

  Serial.begin(9600);
  delay(100);
  Wire.beginTransmission(ADXLAddress);
  Wire.write(Power_Register);
  Wire.write(16);
  Wire.endTransmission();
}
void loop() {
  delay(2000);
  Wire.beginTransmission(ADXLAddress);

  Wire.write(X_Axis_Register_DATAX0);
  Wire.write(X_Axis_Register_DATAX1);

  Wire.endTransmission();

  Wire.requestFrom(ADXLAddress,2);

  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
  }

  Serial.print("X0= ");
  Serial.print(X0, BIN);
  Serial.print("   X1= ");
  Serial.println(X1, BIN);
}

The following code shows, how I would read from a STC3100. But I own none of them, so I can not try the code. I would be very surprised if it works directly. Use it as an example. Perhaps we could improve it together. ;-)
#include <Wire.h>

#define STC_ADDRESS 0x70
#define MODE_REGISTER 0x00
#define CURRENT_LOW_REGISTER 0x06
#define VOLTAGE_LOW_REGISTER 0x08

int voltage, current;
int high_value = 0;

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

  Wire.begin();
  delay(100);
  // power on the STC
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(MODE_REGISTER);
  Wire.write(16);
  Wire.endTransmission();
}

void loop()
{
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(VOLTAGE_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    voltage = Wire.read();
    //Serial.print("REG 8 = ");
    //Serial.println(voltage);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 9 = ");
    //Serial.println(high_value);
    voltage += (high_value << 8);
    //Serial.print("voltage = ");
    //Serial.println(voltage);

  }
  Wire.endTransmission();

  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(CURRENT_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    current = Wire.read();
    //Serial.print("REG 6 = ");
    //Serial.println(current);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 7 = ");
    //Serial.println(high_value);
    current += (high_value << 8);
    //Serial.print("current = ");
    //Serial.println(current);
  }
  Wire.endTransmission();

  Serial.print("V= ");
  Serial.print(voltage);
  Serial.print("   C= ");
  Serial.println(current);
}


EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.

When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.

I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.

While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.

I am currently testing my code with a simple serial relay sketch, ESP on Serial3.
I have nothing else connected to ESP besides vcc, ch_pd, gnd, tx and Rx.
I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx

I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.

I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.

I appreciate any and all replies, and will provide any necessary clarification.

Thanks,
Vl4d

A wiring diagram would help.

Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.


What is the fastest and easiest way to transmit arduino's sensor data to a PC wirelessly I have a specific problem :

I'm working on a testing platform. It has to be absolutely isolated, so I cannot wire it back to my PC. I again reiterate it. There is no way to wire it to my PC. IT HAS TO BE ABSOLUTELY ISOLATED
It has about 10 different sensors on it and I need to read sensor's data simultaneously at 100Hz.  It is currently working fine with 16Hz, but I need to improve it further, so I think maybe in future sampling rates higher than 100 is beneficial. 7 Hz is the lowest possible value that doesn't botch the whole things up.
I have a laptop on the platform which reads the sensor data via RS232, then it processes them in a fraction of a second and produce a control signal and send it to the actuators. It has to happen at real-time. Control algorithm is not heavy, it is several PIDs.
It has 6 actuators with the fastest possible reaction time of 0.005 second.
The main sensor currently is Microstrain 3DM-GX1. It is a very good sensors.
I want to add a GY-80 sensor in parallel to 3DM-GX1. I want to test various filtering algorithms on the GY-80's output and compare them to 3DM-GX1.
Platform has 6 degrees of freedom so I think laser transmission is not practical.
Distance between the computer and the platform is at most 3 meters.

For some reasons I am not able to use the laptop anymore. I want to read the sensor's data with an Arduino, preferably Arduino Mega 2560. My problem is that I don't want to load the control algorithm to the Arduino.

IMHO the perfect solution is going to be a Wireless link between the Sensors via Arduino to my PC. This way my PC logs data and also the Control Algorithm can promptly calculate the feedback signal and send it to Arduino which will send them to the actuators. This immensely makes things easier for me.

I think I need a RS232 shield for the 3DM-GX1 & Arduino, + some wireless solution for sending data from both sensors to my computer. Then I need to send back the control signal back to the actuators wirelessly.

Now what is the fast and easy way to transmit the data between PC and Arduino in real-time?

Thank you in advance!

The fastest way would be to use a laser link!! Yeah lasers. You could go with wifi or some other custom wireless but lasers will guarantee the highest energy density and therefor best bandwidth.  This guy claims near 10 MB/s with his setup:

http://www.instructables.com/id/Laser-Transceiver/


SparkFun EL Sequencer does not work I have connected to EL wire, 12v EL Inverter to SparkFun EL Sequencer but it does not work (no battery is connected). The connections are the same like in Hookup Guide (https://cdn.sparkfun.com/assets/learn_tutorials/3/6/9/ELSequencerHookUp_bb.png). Furthermore, there is no light indicating that it works but I hear a noise/whistle from the Inverter.

Do I have to program the EL Sequencer or does it automatically turn the EL wire on?

It looks like Sparkfun probably only put the bootloader on the board. The tutorial is written in a way that suggests the need to flash the board.

Also the board does not imediatly work with the 12V inverter. If you have the battery you should attach it and see the PWR LED turn on.

The inverter only provides voltage to the EL wire and not the Microcontroller, power to the microcontroller is provided by way of a regulator(U2), not the LM317 the last quote from the one comment shows how you can connect to the 12V inverter.

What you should do instead of having to go the route of all the wiring is to connect both the battery to BATT IN and the inverter, but ensuring that the microcontroller is programmed before hand.

  Arduino Code

  Once you have all of your hardware hooked up properly, it’s time to
  program your Sequencer to run the EL Wire display as you want. You
  will need to download the Arduino code in order to follow along with
  the example.

  You can also download the most up-to-date code from the EL Sequencer
  GitHub repository.

  We will be working with the “SparkFun_EL_Example.ino” example. If you
  need a review on how to upload Arduino code to your board or using the
  Arduino IDE, please check our tutorial here. Also, if you are unsure
  about installing the FTDI drivers, please check out this tutorial.

Also from one of the Tech support notes:

  Using 12V to Power Both the EL Inverter & Microcontroller

  If you are using a 12V wall adapter to power the 12V Inverter, you
  would still need to provide power to the microcontroller side. One
  solution with your 12V wall adapter to provide power to the 12V
  inverter and Atmega328P is to get a barrel jack adapter to 2 pin JST
  adapter [ https://www.sparkfun.com/products/8734 ], thus connecting
  the 12V wall adapter to the “BATT IN.” This is assuming that your wall
  adapter is using a center positive barrel jack.

  From there you can connect the 2 pin JST labeled “DC Out” to the 12V
  inverter’s input voltage. To connect, I recommend using the male DC
  barrel jack adapter [ https://www.sparkfun.com/products/10287 ] and a
  2pin JSt jumper wire [ https://www.sparkfun.com/products/8670 or
  https://www.sparkfun.com/products/8671 ]. You will need to wire strip
  the cable to be able to connect it to the screw terminals.

  Lastly, you would need to add a solder jumper to SJ1 so that you
  bypass the voltage regulator between your external power (“BATT IN”)
  to provide power to the inverter’s “DC OUT”. This will provide power
  to your 12V inverter’s input.

Warning: if SJ1 is closed, inverter will see 5V with FTDI plugged in and switch at USB


Hardware Interrupt Triggered Randomly So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so:

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING);
}

void loop() {
  if(flashConvergence) {
    //Do stuff that takes several seconds
    delay(3000);
    flashConvergence = false;
  }
}

void displayConvergence() {
  if (!flashConvergence) {
    flashConvergence = true;
  }
}

The schematic is as follows:

simulate this circuit – Schematic created using CircuitLab

But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second.

Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter.

I modified the circuit by adding a capacitor across the switch:

simulate this circuit

I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch.

Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)?

Thanks for the help!

It has come to my attention I never posted a followup to this but I was actually able to solve this problem by shielding the wire going from the switch to the arduino. The switch's wire was about 2 to 3 inches long and I wrapped aluminum foil around it, which shielded the signal from what I suspected was EMI induced by the switching converters.


How to generate gcode for Arduino Mega 2560 and Ramps 1.4 CNC Router I had a Prusa I3 3D Printer which use Arduino Mega 2560, Ramps 1.4 and Pololu - A4988 Stepper Motor Driver.

I want to convert my 3D printer to CNC Router using my Dremel with Flexible shaft like this.

I found the one project on instructables.com at here
http://www.instructables.com/id/Arduino-Controlled-CNC-3D-Printer

They give config for Mega 2560 as CNC router.
But i don't know how to generate g-code for these cnc router.

Please help me to generate g-code from STL, DXF and Image(PNG or SVG) files to use with this type of cnc router.

For generating g-code from an SVG, you could try to parse the SVG into a set of relative commands, and using the relative commands to generate G-code. Since you were originally using the frame as a 3d printer and now you want to use this as a CNC machine, you could try to invert the data. But, for generating the code I would go read up on how to parse the various file formats, and read the specs on each of the formats. However, most of the file formats you listed are proprietary, and you won't be able to find an open spec for them.

Of the formats that you listed, it would probably be the easiest to parse the SVG, as it's an open spec, and is a lot like XML.

This is going to be really difficult to actually do, because you're essentially reimplementing a full CNC controller.

I would start with getting 2 dimensional stuff down like drawing shapes and setting routing depth.

Some Resources

Here are some resources that might help you with parsing the various file formats. I only listed the ones that have an open standard.

http://www.w3schools.com/svg/default.asp
This link describes the SVG format, and it does a fairly decent job at it.
http://en.wikipedia.org/wiki/G-code
http://en.wikipedia.org/wiki/STL_%28file_format%29


if-else statement not working So I'm facing this problem a lot in my code where the program is not getting into the if else loop properly and just returning the same answer again and again.

void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));
if (temp == 0.00) {
temp2 = 0.00;
} else {
  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

The answer keeps on coming 0 even when temp is non zero.

If anyone knows the reason please help...

I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.

void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));

if (temp == 0.00) {
  temp2 = 0.00;
} else {

/* Bug here.                                                             */
/* this temp2 is local to these {} and is lost as soon as we reach the } */
/* at the end of the else.                                               */
/* Remove the word double and it should work                             */

  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

Personally I'd replace the entire if ... else with:

double temp = abs(tan(theta_rad)); // removed redundant casts to double

double temp2;
if (temp > 1.0) // 1/temp will be smaller if temp > 1
  temp2 = 1.0/temp;
else
  temp2 = temp;

It'll have exactly the same effect but avoids unnecessary floating point calculations


Interfacing Gammon's RS485 with computer I'm using the non-blocking RS485 Gammon's library for Arduino (as shown at http://www.gammon.com.au/forum/?id=11428) to handle the communication between some arduinos.
Now I'm having trouble to add a Raspberry Pi (or otherwise a non-arduino platform) to the network.

How can I integrate the Gammon's protocol in a python or processing software?

Open-source and Web-search is just great. This might be what you are looking for.

Cheers!


serial data gets spoiled I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)
        print(temp)

while 1:
    check_for_command()
    time.sleep(0.1)

the code on the arduino is rather simple:

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

void loop(){
Serial.println(“Hello Pi”);
delay(2000);

the annoying part is. I recieve this:

  b'Hello Pi\r\n'

instead of the clean

  Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.

The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

What does the 'b' character do in front of a string literal?


Run code once after programming I'm using EEPROM to store project settings non-volatile.
After reuploading the sketch to my board (over SPI via ArduinoISP), the EEPROM is reset to full 0xFFs and I have to manually do a "software reset" with a second switch, which initializes the EEPROM with its default values.

Is it possible to run a segment of code once, and only once, after booting up the first time after being programmed?

I'm working around it by checking whether a piece of EEPROM is 1 at startup when it would always be 0 after the initialization and during usage, but surely there's a cleaner alternative than checking for an EEPROM bit each time.

This is a X->Y problem. Here is a solution for X:

Bit 3 of high fuse of the ATmega328p controls if EEPROM memory is preserved through the chip erase. You can change the high fuse setting in boards.txt. Restart the IDE to apply the new setting.

The fuses are written when you select the "burn bootloader" option in the Arduino IDE.


How can I turn this into an (Ableton) controller? I found this lovely decade box in a demolished house recently and want to turn it into an Ableton controller. As you see, there are 18 knobs, each with 12 individual states.

I'd like to have a program which can access the states of all the knobs at any time, and I have an arduino which I can use. Is this possible to do without a shield?

My first thought is that, since many of the leads on the back already have resistors on them, I could use a sort of total-resistance-across-the-connection approach which would suit itself to the analog inputs. But I'm not sure that's the way to go, especially if I want very low latency.

How can I wire up a board that has digital access to all the pins here? How does a multiplexer play into this? How many inputs would I need? I am super new to this kind of stuff, so I imagine this must be a pretty simple answer.

Thanks for your help.

The hard part here is that you essentially have 216 inputs you need to read.

You could multiplex the analog pins using two 74HC4051. Analogread takes around 0.1ms, so around 2ms for all 18 knobs. Debouncing would however be pretty hard.

I'd probably go with input shift registers, and remove all the resistors. You would however need 27 8-bit shift register (3 registers per 2 knobs).

To reduce this you could encode the rotary position into 4-bit using a diode network. That way you can use only 1 shift register per 2 knobs. So 9 in total.


Writing a custom character on an lcd I am using a 16*2 lcd display as a dashboard computer.
I want it to display a logo at the very beginning of the code, but some letters occupy the space of 4 characters, and are using both lines of the display, and creating those letters character by character (some actually require 6 characters) is very difficult.
Is there anyway i can address the lcd as a big matrix ?
there would be 16 lines ( the oringinal 2 lines * 8 lines of each character) and 80 columns (the original 16 columns * 5 columns each character has).
This would make it A LOT easier.

The chip you are using (HD44780) only works with characters; you can't address single pixels. If you read the datasheet, the word "pixel" is absent.

Of course, you can add a wrapper that implement a drawPixel(row,col) function by defining custom characters and then sending it to the display.

The result will be unpleasent to the eye, because there is a gap between chars on screen, and another gap between rows.

A better alternative is an OLED display like this:

You can find the same display with I2C or SPI interfaces. Basic model is B&W, but you also have color and touch sensitive variants.


Question: how to join two different codes I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No
help
this is the code for temperature and relative humidity:

#include <Adafruit_Sensor.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <DHT_U.h>

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup(){

  //Iniciar el sensor de temp
  dht.begin();
  //Iniciar el LCD
  lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
  //Setea el Pin 12 como salida
  pinMode(motor,OUTPUT);

}

void loop(){ //Este es el buclé principal del programa

  //Lee valores físicos
  hume = dht.readHumidity();
  temp = dht.readTemperature();

  //Limpia el LCD
  lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
  lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  //Escribe los valores leídos en el LCD
  lcd.print("TEMPERATURA: ");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  lcd.print("HUMEDAD: ");
  lcd.print(hume);
  lcd.print("%");

  //Activa el motor si la temperatura pasa el valor deseado
  if(temp>=30){ // Compara si la temp ya es 30 grados
    digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
  }
  else{
    digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
  }

  delay(2000);//valor en milisengundos para que repita el ciclo

}

and this is the barometric pressure code:
#include <Wire.h>
#include <Adafruit_BMP085.h>

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");

    Serial.println();
    delay(500);
}

You need to write one program using elements from each block of code. There is no way the Arduino will run both programs concurrently, it will only run one or the other.  You can copy and paste them together but unless done correctly it will not work. This is why it is important to understand the code you are using.


Transistor for DC motor and 9v I have this schematic for a DC motor in my arduino, now I want to add 9v battery.

But I've seen that people use TIP120 transistor, I have BC548B,
can I just put the 9v with that transistor?

There are many circuits using the TIP120 NPN transistor because it is a darlington transistor. This is used because its max voltage is 60V and the max current is 5A, this means you can control a variety of external high current devices with low voltage circuitry because of the darlington arrangement.

You can use the BC548B with your motor(low current) and a 9V battery as it does handle 30V, but it is limited to 100mA, which is fine for tiny low current motors. But these are actually Amplifier transistors, so there main design area is not for inductive loads.

I recommend the TIP120 as this will ensure that you don't trash a transistor with current spikes as you could easily go over the 100mA spec of the BC548.


Leonardo and micro: high pitch noise when powered from Vin I have an issue with several Leonardo and Micro boards.

On all of my boards, there is a sawtooth of about 690mV ptp @ 4kHz on the 5V supply when powered from Vin (external power).
The frequency changes slightly when changing input voltage from 7V to 12V.

C12 is a capacitor on the Leonardo board that is making the acoustic noise, it is "singing" with the frequency of this sawtooth. It follows the voltage regulator NCP1117 for the 5V power supply generation.

According to the schematics of the Leonardo and micro, the voltage regulator used on these boards should be the NCP1117, but on the boards I have, there is no number printed on this component, so I suspect an alternative was used, with these annoying results...

For a project I have for generating audio signals, this noise was unacceptable, so I cut out the regulator and powered everything with an external LM7805. One should not power the module via USB then as long as the external power is connected!!!

Anyone having the same trouble with these boards?
Other solutions?

(The Leonardo is a genuine Arduino board.)

Yes, I've had this problem on a number of boards. It seems there are some faulty units coming out of the factory. I've had them replaced by my supplier, but I end up being sent more faulty boards.

It makes any kind of accurate ADC reading impossible.

A quick way to work out if your board has this problem

Place a jumper between 3.3v and A0
Put an analogRead in a loop and println the result
When powered by 5V you'll see a fairly constant value (around 670), varying by 1 or 2
When powered by 12V, if you have a faulty board, you'll see varying values, deviating by 50 or more.

There's a couple of solutions/workarounds to the problem listed here: http://forum.arduino.cc/index.php?topic=235729.0.


Why delay of more than 64 millisecond stops the servo motor from rotating? I am not using "Servo.h" instead i am just managing the length of pulse The code I used was this
int servo = 5;
int angle;

void setup() {

  pinMode(servo, OUTPUT);

}

void loop() {

  for (angle = 0;angle<180;angle++){

    digitalWrite(servo, HIGH);
    delayMicroseconds((angle*(11))+365);
    digitalWrite(servo,LOW);
    delay(65);
  }

  for (angle = 179;angle>0;angle--){

    digitalWrite(servo, HIGH);
    delayMicroseconds((angle*(11))+650);
    digitalWrite(servo,LOW);
    delay(65);

}
}

as u can see I have set the delay after a particular step to be 65 milliseconds but it won't work, any delay greater than 64 milliseconds do not work and the motor just stops rotating.
what is the reason for this??

A servo motor doesn't just require a single pulse to send it to a specific angle. It requires a constant stream of pulses at the right frequency for it to track what the angle should be.
By sending one pulse you're just hinting where it might like to go to, then stopping. It's never going to get there, unless you keep sending those pulses fast enough.
Also if you don't send pulses then the servo will go into a "low power sleep mode" where it's not actively driving the output and it will go "floppy" where you can move the servo by hand.
Typically you need to send pulses at about 50Hz, which is one pulse every 20ms. Many servos will be more forgiving, but if you send too slowly they just won't know what to do.
If you want to be handling the pulses yourself then you need to do it in the right way.  That is:

Send a pulse of your desired length
Delay for 20ms minus your desired length
Go to 1 until your desired elapsed time has been reached.

For example:
for (angle = 0; angle<180; angle++){
  uint32_t ts = millis();
  while ((millis() - ts) < 100) { // 100ms delay
    digitalWrite(servo, HIGH);
    delayMicroseconds((angle * 11) + 650);
    digitalWrite(servo,LOW);
    delayMicroseconds(20000 - ((angle * 11) + 650));
  }
}

That won't be exact, owing to the latency of the loop instructions, but it will be close enough.


Using Waveshare Raspberry Pi TFT LCD with Arduino Uno I have a 3.5 inch Waveshare Raspberry Pi TFT LCD which uses the XPT2046 Touch Controller. I want to use this LCD screen with my Arduino Uno.

I originally believed something like this was impossible, but then I found out that the XPT2046 Touch Controller is compatible with the Arduino, and a large number of libraries for the same exist. However, I'm not really very sure whether I can use this with my Arduino; the design of the screen I have is slightly different from the ones I've found online, which are supposed to be compatible with an Arduino Uno.

Is it possible for me to use this screen with my Arduino Uno? If so, what would the wiring schematics look like, and would I be able to use libraries like URTouch?

Possibly.

The XPT2046 chip is only for the touch screen, not the LCD.  That will be easy to get going on the Arduino since many many Arduino LCD screens use the same chip.

However, you will need to find out what driver chip the LCD display uses (maybe ILI9488 or HX8357 or something similar), and what pins on the Pi header relate to what function on the display (note: it is probably a 16 bit parallel interface, so uses a lot of pins).

Also note that this only applies to displays that connect only to the big 40 pin header. If it uses the FPC display connector you will have no luck trying to use it with an Arduino.