How to increase voltage of Arduino? Hey I'm very new to Arduino. I don't have very much knowledge in electrical engineering either.

My project: an EL wire working on Arduino. Since the Arduino can only support 5V and the wire needs 120V, how can I make sure that it works? (I assume the voltage provided by the Arduino is not high enough for the EL wire to operate.)

There are two ways of tackling this.  You can either switch the low-voltage DC power to the EL wire inverter (which is safe and easy) or you can switch the high voltage AC power out of the inverter (which is harder, more dangerous, but does allow you to route the power to different EL wires for animation).

The former can be arranged in just the same way as switching any heavy load from an Arduino - with an N-channel MOSFET as a low-sided switch, or a combination of N- and P-channel MOSFETs as a high-side switch. You could add further isolation with a relay should you wish. BJTs could be used instead of MOSFETs but MOSFETs are better at switching higher currents from low current sources.

For switching the high-voltage side you will need a TRIAC circuit. While it is possible to switch a TRIAC direct from the Arduino it is preferred to opt-isolate the system from the Arduino both for safety and ease of switching at higher voltages.

The most common opto-isolator to use is the MOC3041 Opto-Isolated Triac. This is used to switch the gate of a higher voltage / power TRIAC to switch the load.

In that circuit the "220V" comes from the EL inverter, and the LOAD is the EL wire itself. Each EL wire you want to switch would use a copy of that circuit, but can (power permitting) use the same inverter as the source.


Unable to connect ESP8266 to WPA2+Enterprise network I am trying to connect ESP8266 module to WPA2+Enterprise network with my ssid, username and password and the latest version supports such connection. I followed this link, and the code:

#include "ESP8266WiFi.h"
extern "C" {
  #include "user_interface.h"
  #include "wpa2_enterprise.h"
}

static const char* ssid = "ssid";
static const char* username = "username";
static const char* password = "password";
const char* host = "host_ip";

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

  Serial.print("Connecting to ");
  Serial.println(ssid);
   // Setting ESP into STATION mode only (no AP mode or dual mode)
  wifi_set_opmode(0x01);

  struct station_config wifi_config;

  memset(&wifi_config, 0, sizeof(wifi_config));
  strcpy((char*)wifi_config.ssid, ssid);

  wifi_station_set_config(&wifi_config);

  wifi_station_clear_cert_key();
  wifi_station_clear_enterprise_ca_cert();

  wifi_station_set_wpa2_enterprise_auth(1);
  wifi_station_set_enterprise_username((uint8*)username, strlen(username));
  wifi_station_set_enterprise_password((uint8*)password, strlen(password));

  wifi_station_connect();
  Serial.print("Wifi station connect status:");
  Serial.println(wifi_station_get_connect_status());

  // Wait for connection AND IP address from DHCP
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println(WiFi.status());
    delay(2000);
    Serial.println("Not connected");
  }

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

void loop()
{
  delay(2000);
}

OUTPUT:

Connecting to ssid
Wifi station connect status:1
6
Not connected
6
Not connected
.....

Status 6 is  WL_DISCONNECTED,i.e., module is not configured in station mode. I am not able to figure out what is causing the problem.

The clear commands are not useful until after you have connected.
I use these commands just before setting user ID and password:

wifi_station_set_enterprise_identity((uint8*)username1, strlen(username));
wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

It is necessary that the radius server have default_eap_type set to TTLS or PEAP for username/password authentication. Perhaps there is another possibility, but there is a bug in ESP8266 so it does not properly search for supported EAP types.

const char* username1 = "anonymous"; //works for me

u8 ca_cert[] = "-----BEGIN CERTIFICATE-----\n"
"MIIFETCCA/mgAwIBAgIJAO0ntD34r/+QMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD\n"
"VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcMBkR1cmhh\n"
"bTEeMBwGA1UECgwVTWl0Y2hlbGwvVHJhbXBlciBJbmMuMR8wHQYJKoZIhvcNAQkB\n"
"FhBidXJ0bXNAZ21haWwuY29tMSgwJgYDVQQDDB9CdXJ0IFNlbGYgQ2VydGlmaWNh\n"
"dGUgQXV0aG9yaXR5MB4XDTE4MDEyMzE1NTgxOFoXDTE4MDMyNDE1NTgxOFowgaIx\n"
"CzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBwwG\n"
"RHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIEluYy4xHzAdBgkqhkiG\n"
"9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1cnQgU2VsZiBDZXJ0\n"
"aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"
"AQC2O2m4JCmqimeztaZ8JasIuZqksrxvCjyWpkykoGzoR6v1/kDSuLgdp7EmtLKN\n"
"vOJPQ2ea0yVvkFf0dQYcgDhNdAsXcqskMOprS+jefzlLQUbU1jTk+AOSiOcmxWT1\n"
"H8uYhSp/1TkkWDM8dVO9RRIQyigVinsJNhdPyUVsTaQh3s29AL8CboixUNZWngOo\n"
"d1+66lwy4N+3hXACJWlurgvc0q7RfqSqfJY/+lugfID0ANpGQqqu1Dq2IXZbLyx9\n"
"roOPpC+fqX2wn5g9+RuA18OY/GPtkHc6clAoiJDGXsTRpffgsI5spdJ26WknbhO/\n"
"3Q2vQJ2Q5m/QvSp55qOM5nevAgMBAAGjggFGMIIBQjAdBgNVHQ4EFgQUT3hChU84\n"
"EEXHesDdKOtPqfhrg68wgdcGA1UdIwSBzzCBzIAUT3hChU84EEXHesDdKOtPqfhr\n"
"g6+hgaikgaUwgaIxCzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGlu\n"
"YTEPMA0GA1UEBwwGRHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIElu\n"
"Yy4xHzAdBgkqhkiG9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1\n"
"cnQgU2VsZiBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCCQDtJ7Q9+K//kDAPBgNVHRMB\n"
"Af8EBTADAQH/MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly93d3cuZXhhbXBsZS5v\n"
"cmcvZXhhbXBsZV9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBADNmDxddEh1XSo8J\n"
"fanCRuYqngpVFtKCzRNCtQ7aOAPrj6gRMtMAqQhlYmcbxjaVOCboAvJ8evY8x5We\n"
"YU6eIAmg95PlDws8EvcVQhO2ZYcuOHTvdu5Q4Ior0oXaCfqdS35YcPW7pRGprY/x\n"
"w7kbG84FFatpXPuDGQB65haqQ2KXPrILiE/jAKpTu9EBLEEN4uIAuxbB6unARovX\n"
"YoXIQHFc32bZAjihquvs4J7FNkcSr3lJpuv03dryqMB+Qn3G8yM7PFLNL2QyS0Zu\n"
"UbS5kDO7UqbTjtrUDolp5sUNvyrkX5ILYfZeEeaHqAlA20SFqNG7BcTY222NsCft\n"
"yNXqX1c=\n"
"-----END CERTIFICATE-----";

works for me. I have to go back and check whether those \n's are needed.

I think I found the enterprise_identity command important for both TTLS and PEAP, and I found I needed a ca_cert to do PEAP but not necessary for TTLS. I am not certain why.


Trying to connect a 1.3" IIC OLED display to an Arduino M0 board (not Uno) I'm trying to connect an OLED display to the Arduino M0. I got the code example (ssd1306_128x64_i2c) from the Adafruit SSD1306 library I downloaded.

Video showing at 8:14 how it should look

However, when I upload the code to the board most of the display just lights up with no motion. It's only in the bottom that you can see the program is running, showing part of the different shapes.

After I uploaded it the first time I didn't change anything but now the compiler gives an error message saying that one display setting must be specified in SSD1306.h

I've tried setting the display size in the library header file which looks like this:

Displays
-----------------------------------------------------------------------
The driver is used in multiple displays (128x64, 128x32, etc.).
Select the appropriate display below to create an appropriately
sized framebuffer, etc.

    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16

#define SSD1306_128_64
//#define SSD1306_128_32
//#define SSD1306_96_16

But the same error message appears in the compiler.

Does anybody know how I can fix this?

Thank you.

That header part should look like this (notice the comment starts and ends):

    /*=========================================================================
    SSD1306 Displays
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.
    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16
    -----------------------------------------------------------------------*/
#define SSD1306_128_64
//   #define SSD1306_128_32
//   #define SSD1306_96_16
/*=========================================================================*/

If it compiles but doesn't work try to replace the I2C address of Adafruits 128x64 module (0x3D) by the address often used in Chinese modules (0x3C):

display.begin(SSD1306_SWITCHCAPVCC, 0x3D);

to

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

If that doesn't work, use an I2C scanner to find the address of the connected module.


Better way than exit(0)? The following code does what I need it to do (when a start switch is on and door switch is off - a warning light flashes. When the start switch and door switch are both on - a valve opens to allow water in for 2 seconds). I need the light to flash until the door is HIGH too at which point the valve program runs once.  The only way I have to get out of this is to use exit(0). Is there a better way to do this? Ideally, I would like to stay away from anything too Boolean! Thank you.

int start = 2;
int door = 3;
int light = 8;
int valve = 9;
int counter = 0;

void setup() {
  pinMode(start,INPUT);
  pinMode(door,INPUT);
  pinMode(light,OUTPUT);
  pinMode(valve,OUTPUT);
}

void loop() {
  if(digitalRead(start)==HIGH && digitalRead(door)==HIGH) {
    digitalWrite(valve, HIGH);
    delay(2000);
    digitalWrite(valve,LOW);
    exit(0);
    //breaks out of loop. Arduino then needs reset.
  }

  if (digitalRead(start)==HIGH && digitalRead(door)==LOW) {
    digitalWrite(light,HIGH);
    delay(500);
    digitalWrite(light,LOW);
    delay(500);
  }
}

What you need to do is learn what a finite state machine (FSM) is.

An FSM is a way of having the Arduino in one of a finite number of states, such as "light flashing", or "letting water in", etc.

I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


Need help with using pulseInLong to time a sensor I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing'
This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close).
But when I apply pulseInLong I only get a string of zeros on the serial monitor.
What am I doing wrong?
Here is the sketch:

//  Coding by Jeremy 130520
//  further development for ricochet module
//https://www.megunolink.com/documentation/arduino-libraries/exponential-filter/
//https://www.google.com/search?q=how+to+use+arduino+pulsein

#include "MegunoLink.h"
#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.
ExponentialFilter<long> ADCFilter(5, 0);

int coilPin = 8;
int analogIn = A0;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
  pinMode(coilPin, OUTPUT);
  pinMode(analogIn,INPUT);
  Serial.begin(9600);
  }

void loop()
{
 int RawValue = analogRead(analogIn);
  ADCFilter.Filter(RawValue);
 signal_1 =(ADCFilter.Current());
 signal_1 = constrain(signal_1,80, 200);
 signal_1 = map(signal_1, 80, 200,0,400);
 if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
 if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

 Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
 //Serial.println(pulseLength);
 delay(10);
}

You cannot use pulseInLong() because it is a blocking function. It
waits until the input rises, then waits until it falls again, and only
then it returns a value. While it's waiting, the rest of the program
cannot run. This means you will not be able to actually generate the
signal you are trying to time.

The easiest solution is to time things yourself with micros(). You
have to implement an edge detector, i.e. some logic that remembers the
previous state of the signal and notices when it changes:

static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
    time_of_rise = micros();
    is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
    uint32_t pulse_width = micros() - time_of_rise;
    is_high = false;
    Serial.println(pulse_width);
}


D1 mini does not resume operation as expected after deep sleep I'm trying to get the D1 mini to return operation after ESP.deepsleep(). The code below compiles and gives the expected output for the first run. Five seconds after the announcement that that the device is going to sleep, there is a brief flash on the on board LED and I get a string of garbage on the serial monitor. Ideas for things to try would be appreciated.

// Testing d1 mini deep sleep
// D0 and RST are connected

/*  platformio.ini:
  [env:d1_mini]
  platform = espressif8266
  board = d1_mini
  framework = arduino
  monitor_speed = 115200
*/

#include <Arduino.h>

void blink();

void setup() {
  Serial.begin(115200);
  pinMode(D0, WAKEUP_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  blink();
  delay(1000);
  Serial.println("Going for some deep sleep");
  ESP.deepSleep(5e6); // 5e6 is 5 seconds
}

void blink() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
}

As you can guess I'm running this with platformio. The output on the serial monitor is:

stefan@Cameron ~/.../Projects/Deep sleep $ platformio device monitor --baud 115200
--- Miniterm on /dev/ttyUSB0  115200,8,N,1 ---
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Going for some deep sleep
sl␀l��|␀�l�|␂␌␌␄�␄l�␌c|ǃ␃�␛�r�cd�c��gg�doo���␌cpp��$sd{d␛�{��o�c�gbx␀�

There is a blink of the LED on the first run, nothing there either after the apparent reset.

The garbage is because the ESP8266 outputs boot information at 76800. This should include the boot reason and may help you understand why the code's not working as expected.

Try changing your Serial speed to 76800 in your code (just so that your messages don't end up being gibberish), use 76800 on platformio's monitor and you should be able to at least see what the D1 says it's doing.

You should see a line that ends in something like:

  rst cause: x, boot mode:(y, z)

x should be 1 ("Power reboot"), 2 ("External reset or wake-up from Deep-sleep" - obviously what you want), 3 ("Software WDT" - the software watchdog went off) or 4 ("Hardware WDT reset" - the hardware watchdog timer went off)

boot mode indicates where the runtime image came from - y should be 3 ("Flash"); anything else is really unlikely for your setup.

There's more info on this at ESP8266 Reset Causes
and Common Fatal
Exception Causes

If you try this please post how it goes! I'd like to hear more about what's going on here.


MKR GPS Shield Sampling Frequency I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.

I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.

I am using the GPSLocation sample from the Arduino_MKRGPS library (see here):

  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

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

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.

Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?

Thanks!

It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.

I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.

In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.

EDIT:

I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.

I had to make the following two changes to the Arduino_MKRGPS library:

increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);

In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:

  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.


Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino The error message, generated from Sublime, in its entirety...

Compiling KCT_Swimv4l...

Creating C:\Users\ken\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...

'"avr-g++"' is not recognized as an internal or external command,
operable program or batch file.

[Stino - Error 1]

This is initial install of "Arduino-like IDE".

I used the following installation procedure:

Install Sublime Text 3
From Sublime, View --> Show Console
From a web browser, open  https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter.
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
from Arduino --> Preferences --> Select Arduino Application Folder.

Same problem with any sketch.

System Configuration:

-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0

github info on Stino was not helpful.
Has anyone encountered this problem and found a solution for it?
If not, I can open an issue there.

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --> Show Console
From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --> Preferences --> Select Arduino Application Folder

On Compile, error msg is now different:
  Compiling KCT_Swimv4l...
  Creating C:\Users\kct\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
  cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
  cc1plus.exe: error: unrecognized command line option "-flto"
  [Stino - Error 1]

Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.

Update

I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)


What variables to declare for controlling a motor with high power motor controller I was getting started with programming a motor controller with the Arduino Uno, in this case it's a mega motor shield (the motor driver shield I'm using).
The problem I have doing this is that I'm not sure what variables to use for the motor which is connected to two outputs labeled MA and MB.  I used motorValue to set the speed previously and used motorPin for writing the speed with the Arduino and a breadboard, but I'm not sure what to use in place of that for the motor being connected to the driver shield outputs.

Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.

It's the numbers you assign to the variables and, more importantly, what you do with those variables that is important.

Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.


Controlling an RC car using Arduino I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.

I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?

I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.

If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.

The code I'm using to test everything looks like this:

void setup() {
  //Initialize the pins and serial
  pinMode(reversePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
}

void reset() {
  digitalWrite(forwardPin, HIGH);
  digitalWrite(reversePin, HIGH);
  digitalWrite(leftPin, HIGH);
  digitalWrite(rightPin, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  reset();

  digitalWrite(forwardPin, LOW);
  delay(4000);
  reset();
  digitalWrite(reversePin, LOW);
  delay(4000);
  reset();
  digitalWrite(leftPin, LOW);
  delay(4000);
  reset();
  digitalWrite(rightPin, LOW);
  delay(4000);
}

Images: http://imgur.com/a/rgpOY

Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)

If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.

If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.

The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.

Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.

You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.

You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628


Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes I've been working on a DIY keyboard project I have all the hardware designed and now its time for the code. For the microcontroller, I'm sort of locked into an Arduino UNO r3 as I already have it lying around. I know it doesn't have HID capabilities baked in, but I can flash different firmware to it. At first I was going to go with a generic HID firmware. This approach was problematic because it would require me to first write/send my Arduino sketch, then touch I wire to various portions of my UNO (it isn't SMD). After this,
I would flash the HID firmware and hope that there were no bugs in my sketch as fixing bugs would have required flashing Arduino firmware and repeating the aforementioned steps. I then had the idea to use Teensy firmware (https://www.pjrc.com/teensy/). This approach seems better, but I have questions regarding its feasibility.

Can I upload Teensy programs/sketches to the Arduino after I've
updated its firmware (if I had a real Teensy I could do this via the teensyduino plugin)?
Similarly, I'd like to write some software that allows me to remap
    the keyboard. Would the Teensy firmware allow this?
Does the Arduino have enough memory to support #2?
Is it possible to reflash BOTH the 8u2 and the 16u2 on my UNO (for details see #2 in update one below)
If 4 is possible is it possible to write code that would read/write the flash on the 8u2 as a filesystem? (for details see #2 in update one below)

Would the teensy firmware be a good option given these constraints? I know I've focused mainly on the Teensy, but if you have a more straightforward approach I'd love to hear it. Also, I know Arduino has a keyboard library(http://arduino.cc/en/Reference/MouseKeyboard) but, it seems rather basic, seems to block other keyboard signals while in use, and isn't easily remappable(see #2). I haven't completely written this off, so if you think this would be the best option please let me know. Thanks for any and all help.

Update
Thanks to one of the questions linked by @Ignacio Vazquez-Abrams(Can the 2nd MCU on the UNO R3 be used for keyboard emulation?) on the original question(weirdly it didn't show up here)  I have learned the following things(not necessarily from the question itself but by links provided in it):

the Atmel 8u2 of the UNO has 8kb of flash while the 16u2 has 16kb (should've known) I still don't know if either of these sizes are enough to hold my Teensy code AND 1+ map files generated by the mapping software I would make. (see #2 above)
the 8u2 seems like the chip that tinkers are generally advised to reprogram as it wouldn't hold the Arduino sketch. If I'm uploading teensy firmware I shouldn't need Arduino sketch capability (Teensy has that built in) So What I might do is use the 16u2 as a place to hold the firmware my code and use the 8u2 as a filesystem to hold any maps I'd like to store. This leads to more questions see the newly added 4 and 5

No, you can't put the teensy bootloader on the UNO. The teensy has an ATMEGA32U4 and the UNO has an ATmega328.  The 32U4 has USB support in hardware the 328 does not.

The UNO does have a ATMEGA16U2 which does have USB in hardware like the 32U4 but it is programmed as a USB serial converter (to replace the FTDI chip used in earlier arduinos).

It might be possible to install a modified teensy bootloader on the 16U2 but that wouldn't help you because it is not connected to any of the I/O pins on the UNO.

In any case to install new firmware on the 16U2 you would need to buy something that can program the 16U2 via the ICSP and if you are going to buy something you might as well just buy a Leonardo or Teensy since they already support emulating a keyboard.

Now if you really wanted to spend the time it might be possible to write your own bootloader for both the 16U2 and the 328 on the UNO in such a way that they emulate a teensy or Leonardo but it won't be easy, and you would be limited by the smaller memory available in the 16U2.


Trying to understand AccelStepper constant speed I'm starting to learn the AccelStepper library for controlling stepper motors for a project I'm working on. I'm able to get the stepper motors running with the basic examples that use acceleration.
I know for parts or all of project I'll want to use constant speed, so I popped up the constant speed demo: https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library/blob/master/examples/Accel_ConstantSpeed/Accel_ConstantSpeed.ino
#include <Wire.h>
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myStepper1 = AFMS.getStepper(200, 2);

void forwardstep1() {
  myStepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
  myStepper1->onestep(BACKWARD, SINGLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup()
{
   Serial.begin(9600);
   Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  Astepper1.setSpeed(50);
}

void loop()
{
   Astepper1.runSpeed();
}

(I'm using the adafruit stepper motor wing)
I uploaded it to my arduino and it's working, the shaft is rotating, but it's doing it really slow. I figured this made sense because it's set at a speed of 50, so I tried turning up the speed:
Astepper1.setSpeed(200);

But the speed still seems to be the same speed. Considering this is a 200 step motor and setSpeed is steps per second you'd think this would whip the motor around fairly quick.
I'm positive that this is due to my misunderstanding of how the library works, but I'm having a hard time trying to figure out how to properly use the constant speed methods.

So I ended up doing some source code diving for the AccelStepper library to figure out what the problem was and it turns out there was a missing method call in their example code, specifically a call to setMaxSpeed in the setup function:
void setup()
{
    Serial.begin(9600); // set up Serial library at 9600 bps
    Serial.println("Stepper test!");

    AFMS.begin(); // create with the default frequency 1.6KHz

    // ! Note that you need to set the max speed, otherwise the stepper motor will
    // ! only step once per interval regardless of what `setSpeed` value you give
    Astepper1.setMaxSpeed(1000);

    Astepper1.moveTo(targetDistance);
    Astepper1.setSpeed(targetSpeed);
}

If you look at the setSpeed method in the library you'll notice a constraint of the speed value:

The constrain method takes in a speed value and then a low and high, which the accelstepper library sets to the private _maxSpeed variable. If the speed is outside of that range it will set the value to the low or high value passed in.

This means, if you don't call setMaxSpeed the library will use the default _maxSpeed value assigned during construction which issss 1.0:

So, to correctly use the constant speed methods, you need to be sure to include a call to setMaxSpeed in your code before calling setSpeed, likely in the setup function.
I also shot a video explanation to share with my co-workers. You can see it here: https://vimeo.com/438272826


How to set up one second interrupt/ISR for ds3231 RTC I am able to set up one hz interrupts using millis and other timers, but would like to do it instead using the RTC I have attached (DS3231)

I am not sure how I can do that.  Can someone point me to a reference for this?

EDIT/UPDATE

I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.  I followed what I thought was the wiring diagram here and
here and here

I also added a led in the circuit to see if I could figure out something that way, but no dice.

Here is some simple code for a sketch that I think should trigger a 1 second interrupt and call my function:

#include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
#include <Time.h>         //http://www.arduino.cc/playground/Code/Time
#include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

const int rtcTimerIntPin = 2;
bool flag = false;

void setup(void)
{
    Serial.begin(9600);
    setSyncProvider(gRTC.get);   // the function to get the time from the RTC
    if (timeStatus() != timeSet)
        Serial.println("Unable to sync with the RTC");
    else
        Serial.println("RTC has set the system time");

    bool stopped = gRTC.oscStopped();
    if (stopped)
    {
        Serial.println("Detected clock power loss - resetting RTC date");
        time_t newTime = cvt_date(__DATE__, __TIME__);
        adjustTime(newTime);
        setTime(newTime);
    }
    else {
        Serial.println("Clock did not lose power");
    }

    pinMode(13, OUTPUT);    // onboard LED
    pinMode(rtcTimerIntPin, INPUT);
    attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
    gRTC.squareWave(SQWAVE_1_HZ);

    digitalClockDisplay();
}

void rtc_interrupt(void)
{
    flag = true;
}

void loop(void)
{
    //digitalClockDisplay();

    if (flag) {
        digitalWrite(LED_BUILTIN, HIGH);    // flash the led
        digitalClockDisplay();              // this just prints time to serial port
        delay(500);                         // wait a little bit
        digitalWrite(LED_BUILTIN, LOW);     // turn off led
        flag =  false;                      // clear the flag until timer sets it again
    }
}

void digitalClockDisplay()
{
// do something
}

This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

Interrupt vs pin number

First, this is wrong in your code:

attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);

You need an interrupt number, not a pin number. This is correct:

  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

Pull-up resistor

Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT_PULLUP like this:

  pinMode (rtcTimerIntPin, INPUT_PULLUP);

Testing

I used this library from Adafruit.

Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

const byte rtcTimerIntPin = 2;

volatile byte flag = false;

void rtc_interrupt ()
{
  flag = true;
}  // end of rtc_interrupt

void setup () {

  Serial.begin(115200);

  while (!Serial); // for Leonardo/Micro/Zero

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  // enable the 1 Hz output
  rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

  // set up to handle interrupt from 1 Hz pin
  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (rtcTimerIntPin, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
}

void loop () {
  if (flag) {
    digitalWrite(LED_BUILTIN, HIGH);    // flash the led
    delay(100);                         // wait a little bit
    digitalWrite(LED_BUILTIN, LOW);     // turn off led
    flag =  false;                      // clear the flag until timer sets it again
  }
}


Can arduino create a file in its memory? I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).

To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.
However, if it's feasible highly depends on the controller architecture and its peripherals.
Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.
Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)
And others don't allow Flash accesses from application at all.

Anyway:
The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).
Therefore, the SD card approach is surely a very good suggestion.


Using SCL and SDA of ESP8266-01 with GY-30 BH1750FVI for lux measurement I followed this tutorial to get lux measurement from GY-30 BH1750 with Arduino.

It's working fine. But now I want to use it with ESP8266-01.

I read Pin 4 is SDA and 5 is SCL for it. But it's not working. Can someone tell me what do I need to change in the code? I'm a "bit" confused about the addressing.

Following is the code for Arduino:

#include <Wire.h>

int BH1750_address = 0x23; // i2c Addresse
byte buff[2];

void setup() {
  Wire.begin();
  BH1750_Init(BH1750_address);

  delay(200);
  Serial.begin(9600);
  Serial.println("Starte Beleuchtungsstaerkemessung - blog.simtronyx.de");
}

void loop(){
  float valf=0;
  if(BH1750_Read(BH1750_address)==2){
    valf=((buff[0]<<8)|buff[1])/1.2;

    if(valf<0)Serial.print("> 65535");
    else Serial.print((int)valf,DEC);

    Serial.println(" lx");
  }
  delay(1000);
}

void BH1750_Init(int address) {
  Wire.beginTransmission(address);
  Wire.write(0x10); // 1 [lux] aufloesung
  Wire.endTransmission();
}

byte BH1750_Read(int address) {
  byte i=0;
  Wire.beginTransmission(address);
  Wire.requestFrom(address, 2);
  while(Wire.available()){
    buff[i] = Wire.read();
    i++;
  }
  Wire.endTransmission();
  return i;
}

Wire is not setup for the ESP01 by default. There is no GPIO 4 or 5. you can specify the pins as arguments to the begin() method, ex: Wire.begin(sda, scl). Using GPIO of (0,2) is common. Since the ESP01 is picky about pin states during power-up, don't use external pullups (you don't need them anyway).


Measuring solar power with an Arduino I'm pulling together a project for my class where students build a solar panel structure/frame that moves with the sun to capture more power than if the panel was just flat on the roof.  I can handle controlling the motors, but I wanted some help to make sure I safely/accurately measured power.
I have an Arduino (the model isn't especially important), a 12V deep cell battery, and 6 V solar cells.  Obviously I don't want to hook the cells straight to an analog pin, but I came up with the schematic below.  The wire to the battery will go through the CT (the inductor) to get current in order to calculate power.
Would the battery still charge even if the cells are only producing, say, 8V ?  Am I overlooking anything or is there any circuit protection I need to include?  Maybe a computer fan as a load on the battery and to cool everything?  Any help is appreciated.  Thanks!

Just a few points:

You can't measure DC current with a coil; you would need a Hall-effect sensor;
The charging current and the voltage you measure will depend on the state-of-charge of the battery, making it difficult to compare measurements;
You can't fully charge a nominally 12V battery with a 12V solar panel; a 12V lead-acid battery with the panel you mention in the comments should work;
You need at least a diode between solar panels and battery, and possibly a proper charger, depending on the chemistry and capacity of the battery and the maximum charging current; maximum charging current for a 12V 9Ah lead-acid battery is about 1A if you stay on the very safe side, so the panel you mention should be OK; just don't overcharge the battery;
You need to be sure the battery voltage doesn't exceed 12V by too much, or the voltage divider will put more than 5V on the Arduino's input pin and fry it. Nominally 12V lead-acid batteries are usually charged to about 14V, and the solar panel you mention can get there. This would put 5.6V on the Arduino input pin with the resistor values you use in your voltage divider.

Also have a look here: Measure power of solar cell with an esp8266.


Error: Does not name a type I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

class subject {
public:
  char subjectname[];
  char classroom[];

};

Code for the classroom and math

subject math;
math.classroom = "A1";

How can I set the classroom of math to A1?

class subject {
public:
  char subjectname[];
  char classroom[];

};

This creates a class subject which has two char arrays of unspecified size as its members. This will attempt to create an array of size 0 (see here). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then strncpy() your new string inside the buffer.

This would look like

class subject {
public:
  char subjectname[32];  //32 bytes buffer
  char classroom[32];
};

And later

subject math;
strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
Serial.print("Classroom is: ");
Serial.println(math.classroom)

Or, just use the Arduino String class.  For example

#include <Arduino.h>
class subject {
public:
  String subjectname;
  String classroom;
};

Then your first usage code can be used unmodified.

Example

#include <Arduino.h>

class subject {
public:
  String subjectname;
  String classroom;
};

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

    subject math;
    math.classroom = "A1";

    Serial.print("Classroom is: ");
    Serial.println(math.classroom);
}

void loop() { }


Arduino sketch not uploading to Arduino Nano Port is detected and selected but sketch is not uploading to it.
I am getting error:

         avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\ACER\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x2c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

In IDE in the Tools menu, select in submenu Processor the "Atmega 328P (Old Bootloader)" option.

The upload speed 115200 in your console output indicates the you try to upload for new bootloader. The fail to upload could indicate that your Nano has the old bootloader.


Figuring out IR sensor PWM frequency with Arduino I'm trying to verify the pulse width of an IR receiver I "borrowed" from one of those cheap RGB controllers (like thisone) with an arduino nano. But the data I'm getting right now is about 3.4KHz and not the 38KHz I expected.

I'm trying to measure it by connecting the data pin of the IR on INT0 and listening for any change, if the pin goes low I start a measurement, if it goes high I stop the measurement and read out the value.

I'm using Timer1 and no prescaling

My code is as followes

#include <util/delay.h>

#define inpin 1 << PIND2
#define timeron 1 << CS10 //timer no prescale

bool wasTiming = false;
short i = 0;

volatile short timings[20];
volatile bool print = false;

volatile short seconds = 0;

int main()
{
    USART.begin();

    _delay_ms(500);
    USART.writeln("Arduino online");

    DDRD = 0;

    TCCR1A = 0; //no compares, normal counter mode
    TCCR1B = 0; //clock off

    EICRA = 1 << ISC00; // Any change INT0 (PD2)
    EIMSK = 1 << INT0; // INT0 interrupt enable

    sei();

    char buff[20];
    for (;;)
    {
        if (print)
        {
            print = false;

            for (short j = 0; j < 20; j++)
            {
                sprintf(buff, "% 6d ticks", timings[j]);
                USART.writeln(buff);
            }
        }
    }
    USART.end();

    return 0;
}

ISR(INT0_vect)
{
    if (PIND & inpin) //pin high
    {
        if (wasTiming)//
        {
            TCCR1B = 0; //timer clock off
            timings[i] = TCNT1;
            TCNT1 = 0; //empty timer register
            wasTiming = false;

            i++;
            if (i == 20)
            {
                print = true;
                i = 0;
            }
        }
    }
    else // pin low
    {
        if (!wasTiming)
        {
            TCCR1B = timeron; //timer clock on
            wasTiming = true;
        }
    }
}

and the output data is

 13902 ticks
  8865 ticks
  9961 ticks
  8877 ticks
  9968 ticks
  9842 ticks
  8506 ticks
  9896 ticks
  9585 ticks
  9865 ticks
  9541 ticks
  8853 ticks
  9545 ticks
  8888 ticks
  9885 ticks
  9954 ticks
  8515 ticks
  9885 ticks
  8909 ticks
  9874 ticks

on average that looks like about 9500 ticks, which leads me to the following calculation: (16,000,000 / 9,500) * 2 = 3,368.4Hz

Am I doing something wrong here? Or is the data that I'm getting correct, in which case, how would I go about turning that into 1's and 0's?

I'm not really looking for off-the-shelf solutions, half the fun of doing this is figuring it out myself. Eventually I'm gonna build my own RGB controller with this to replace that cheapo thing I already have (it has a few flaws I would like to correct).

You mistakenly believe that the carrier frequency of 38 kHz should be available at the data output pin of the infrared detector chip. These chips provide a logic output indicating the presence of 38 kHz. Most are frequency-selective, being more sensitive at one frequency somewhere between 35 kHz - 60 kHz.
A data sheet pulled at random specifies typical pulse bursts that might be used to encode digital data (pulse burst timing highlighted in red):

In your case, \$f_o\$ might be close to 38 kHz. No fewer than six cycles \$t_{pi}\$ are recommended for the length of one baud. Perhaps your transmitter includes a few more cycles (ten or eleven?) to be safe. The receiver circuitry requires about five cycles before commit, \$t_d\$. Hopefully, a similar delay at end-of-pulse occurs, but the graph at right suggests the end-of-pulse extends a little longer than \$t_d\$. However, pulse width is impressively constant over five magnitudes of infrared intensity.
Note that the presence of a burst of 38 kHz from the transmitter most often sends the output of the receiver to a logic low. No optical signal yields a logic high at receiver output, sometimes with a fast false-detect glitch (which should be rejected if its length is short). A large-value pull-up resistor added between output pin and Vdd may be required to ensure that an idle receiver goes to logic high.
You will still have to determine how these pulse bursts are encoded into logical bits. Many protocols exist, some use pulse position, others use pulse length encoding.


creating object of another class when initializing an object of a class Here's what I want to achieve:
I'm building a class for controlling step motors. In that class I want to have a method called "init". In that method I'd like to create an object of class Tone, which I'll need to control a motor.
BUT I want to have seperate Tone class object for every object of my class that I create. How can I do it?

So, for exmaple, if I have:

myClass newmotor1;
memotor1.init();

After executing these two lines, I'd like to have my object newmotor1 (which I have, because I just created it) AND an object of class Tone, which I'll use.

You don't need to "create" anything. Just have an object in your class:

class Tone {
    public:
        void dosomething() {
            // Whatever is in here
        }
};

class MyMotor {
    public:
        Tone tone;
        void init() {
            // Nothing much else to do in here now.
        }
};

You then:

MyMotor newmotor1;

And you can access:

newmotor1.tone.dosomething();


How to rotate 3 servo motors when 6 led lights are lit using EMG signals I am completely new to arduino and trying to do a school project where i will be able to more 3 fingers with the help of a servo motor using EMG signals.
Right now i am able to read the signals. I just want to modify the code in such a way that when all 6 lights are lit on my emg reading device the servo with rotate by 90 degree. And when all leds are off the servo motor will go back to its initial position, that is will rotate back by 90 degree.
I badly need help over here. Here is the code:

 #define NUM_LED 6  //sets the maximum numbers of LEDs
#define MAX 45     //maximum posible reading. TWEAK THIS VALUE!!
int reading[10];
int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};

void setup(){
  Serial.begin(9600); //begin serial communications
  for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
    pinMode(leds[i], OUTPUT);
  }
}

void loop(){
  for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
    reading[i] = analogRead(A0) * multiplier;
    delay(2);
  }
  for(int i = 0; i < 10; i++){   //average the ten readings
    finalReading += reading[i];
  }
  finalReading /= 10;
  for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
    digitalWrite(leds[j], LOW);
  }
  Serial.print(finalReading);
  Serial.print("\t");
  finalReading = constrain(finalReading, 0, MAX);
  litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
  Serial.println(litLeds);
  for(int k = 0; k < litLeds; k++){
    digitalWrite(leds[k], HIGH);
  }
  //for serial debugging, uncomment the next two lines.
  //Serial.println(finalReading);
  //delay(100);
}

Thanks :)

Apart the problem you have (that the constants are not defined), what you are asking can be easily solved by looking at the servo library.

The servo library tells you that

You have to include the servo library header: #include <Servo.h>
You have to add a variable to hold the object: Servo myservo;
You have to attach the object to a pin: myservo.attach(SERVO_PIN);
Finally you can move the motor to any position (0 <= x <= 180) with the syntax myservo.write(val);

In your code, then, you have the variable litLeds which tells you how many leds are there. Particularly if you have 6 (or more) leds light you will move to 90°, while with 0 (or less - even if this is meaningless) you reset to 0. So the complete code is

#include <Servo.h>

int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
Servo myservo;

void setup(){
    Serial.begin(9600); //begin serial communications
    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
        pinMode(leds[i], OUTPUT);
    }
    myservo.attach(SERVO_PIN);
    myservo.write(0);
}

void loop(){
    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = analogRead(A0) * multiplier;
        delay(2);
    }
    for(int i = 0; i < 10; i++){   //average the ten readings
        finalReading += reading[i];
    }
    finalReading /= 10;
    for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
        digitalWrite(leds[j], LOW);
    }
    Serial.print(finalReading);
    Serial.print("\t");
    finalReading = constrain(finalReading, 0, MAX);
    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
    Serial.println(litLeds);
    for(int k = 0; k < litLeds; k++){
        digitalWrite(leds[k], HIGH);
    }
    if (litLeds >= 6)
        myservo.write(90);
    else if (litLeds <= 0)
        myservo.write(0);

    //for serial debugging, uncomment the next two lines.
    //Serial.println(finalReading);
    //delay(100);
}

Please note that some defines are missing (e.g. the MAX, NUM_LED and SERVO_PIN)


Arduino Mega Timer1 in pure C problem - doesn't work Does somebody know what can be wrong in this, where I try to set Timer1 interrupt in Arduino Mega in C code only. I'm trying CTC Mode and the purpose is LED blinking with 1[s] Period.

I work with documentation program doesn't work completely.

 #include <avr/io.h>
 #include <avr/interrupt.h>

 void setup()
 {
   //LED -> PB7 (Digital pin 13
     DDRB |= (1<<PB7);

  //FCPU = 16MHz, Prescaler :256 | CTC
   TCCR1B |= (1<<CS12) | (1<<WGM12);
   TIMSK1 |= (1<<OCIE1A);  // Compare Match A interrupt allowing
     OCR1A = 62500;

    sei();
    }

  void loop()
  {

   }

   ISR(TIMER1_COMPA_vect)
   {
     PORTB ^= (1<<PB7);
    }

I work with documentation program doesn't work completely.

simple:

1) check out the datasheet;
2) identify those registers needed to get tmr1 to work;
3) set or clear, as appropriate, ALL bits that are needed. Do NOT rely on default values.
4) done.


Arduino RBBB - Device not accepting address I recently purchases and make a Arduino RBBB with a BUB II from Modern Device. I ordered the package found HERE. I built everything according to the instructions, but when I connect it to my laptop (running Ubuntu 14.10), I get the following in dmesg

[63415.213391] usb 3-1: new full-speed USB device number 63 using xhci_hcd
[63415.381403] usb 3-1: device descriptor read/64, error -71
[63415.485225] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 26.
[63415.485240] usb 3-1: hub failed to enable device, error -22
[63415.597236] usb 3-1: new full-speed USB device number 64 using xhci_hcd
[63415.709154] usb 3-1: device descriptor read/64, error -71
[63415.813102] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 27.
[63415.813116] usb 3-1: hub failed to enable device, error -22
[63415.925108] usb 3-1: new full-speed USB device number 65 using xhci_hcd
[63415.925270] usb 3-1: Device not responding to setup address.
[63416.129120] usb 3-1: Device not responding to setup address.
[63416.332902] usb 3-1: device not accepting address 65, error -71
[63416.444973] usb 3-1: new full-speed USB device number 66 using xhci_hcd
[63416.445174] usb 3-1: Device not responding to setup address.
[63416.649008] usb 3-1: Device not responding to setup address.
[63416.852734] usb 3-1: device not accepting address 66, error -71
[63416.852813] usb usb3-port1: unable to enumerate USB device

It is repeatable every time I insert. lsusb does not register it. I have read that I should switch out the cable, but it is brand new (and I don't have another to test with. I was wondering if there is something evidently wrong with my circuitry. I posted pictures

I fixed it. Here is how I did it.

First, I tried connecting just the BUB II to via the USB. Same error, thus I ruled out the Arduino RBBB as the source. I then decided that perhaps it was the voltage jumpers (black things on the pins sticking out in the first picture). After removing them, it works under dmesg, yielding the below.

[  214.044563] ftdi_sio 3-1:1.0: FTDI USB Serial Device converter detected
[  214.044687] usb 3-1: Detected FT232RL
[  214.044696] usb 3-1: Number of endpoints 2
[  214.044704] usb 3-1: Endpoint 1 MaxPacketSize 64
[  214.044712] usb 3-1: Endpoint 2 MaxPacketSize 64
[  214.044718] usb 3-1: Setting MaxPacketSize 64
[  214.045209] usb 3-1: FTDI USB Serial Device converter now attached to ttyUSB0

Thus I wanted to put them back on so I wouldn't lose them. I proceeded to try various combinations till it worked. Ultimately, I ended with 5V for VOUT and VL for LGLV. If that is a bad idea, someone please comment, but it works.

May this help someone else.


Bit Bang signal generation #include <Wire.h>
  #include <LiquidCrystal_I2C.h>
  #include "digitalWriteFast.h"

  #define BUTTONPIN 2
  #define FDCSPIN 6
  #define CIPIN 5
  #define SPEAKERPIN 4

  float RPM=1000.0;
  int PWus=1.5*1000.0;
  int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
  int totalCnt;
  int CIState=B00000000;
  bool Buttonstate=0;
  LiquidCrystal_I2C lcd(0x27, 20, 4);

  void setup()
  {
    Serial.begin(9600);
    lcd.begin();
    lcd.backlight();
    lcd.clear();
    lcd.print("READY TO TEST"); // Waiting for button press
    pinMode(BUTTONPIN, INPUT);// Setting button as Input
    pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
    pinMode(CIPIN, OUTPUT); // Cylinder Identification
    digitalWriteFast(FDCSPIN, LOW);
    digitalWriteFast(CIPIN, LOW);
  }

  void loop()
  {
   Buttonstate=digitalReadFast(BUTTONPIN);
   if(Buttonstate==1)
   {
    delay(5);
    if(Buttonstate==1)
    {
      runInjectorTest();
    }
   }
  }
  void runInjectorTest()
  {
    lcd.print("Test Run");
    playtesttone();

      for(totalCnt=0;totalCnt<8000;totalCnt++)
      {

        PORTD=CIState;
        delayMicroseconds(PWus);
        PORTD=PORTD^B01000000;
        delayMicroseconds(FDCSoffset);
        if(totalCnt%4==0)
        {
          CIState=CIState^B00100000;
        }
      }
    totalCnt=0;
    playfinishtone();
  }
  void playtesttone()
  {
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
  }
  void playfinishtone()
  {

    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);

  }

I am trying to generate 2 signals using the code above and this output is
From the image, the lime green signal is called FDCS and the other is called CI. Note that the scope shows the inverted form of the signal. I want the falling edge of CI to match with the Falling edge of the 5th FDCS signal (right now rising edge is matching with the falling edge of the CI signal). But the Rising edge of the CI signal should match with the Rising edge of the first FDCS signal (which it's already doing). How do I change my code to do this?

If I understand correctly, you signal has a period of 8 FDCS pulses:
4 with CI high and 4 with CI low. Since the rising and falling edges of
CI do not happen at the same place relative to the FDCS pulses, you
should handle these separately.
I suggest something like the following. Note that, as I do not know what
signal(s) your setup inverted, I just try to reproduce what you show on
the scope, with non inversion:
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}


Convert byte* to int in Arduino I am trying to convert byte* value to int here is how I have it.

void mqttCallback(char* topic, byte* payload, unsigned int length) {

  String topicStr = topic;
  int* payload_value;
  int updates_cal;

    payload_value = (int*)payload;
    //updates_cal = *payload_value;

    Serial.print((int)payload_value);

  delay(1);

  Serial.println();
  Serial.println("-----------------------");

}

I am getting MQTT payload as Integer value. Which I want to receive in my NodeMCU (ESP8266).

Is there any way to do this?

Thank you!

Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using mosquitto_pub. The buffer is apparently not zero-terminated.

If these characters represent an integer value, then the way to retrieve it as an integer value would be

char buffer[128];

// Make sure here that `length` is smaller than the above buffer size.
// Otherwise, you'd need a bigger buffer

// Form a C-string from the payload
memcpy(buffer, payload, length);
buffer[length] = '\0';

// Convert it to integer
char *end = nullptr;
long value = strtol(buffer, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be

// Build a `scanf` format string that will read no more than `length`
// characters without relying on zero-termination of the payload
char format[16];
snprintf(format, sizeof format, "%%%ud", length);

// Convert the payload
int payload_value = 0;
if (sscanf((const char *) payload, format, &payload_value) == 1)
  Serial.println(payload_value);
else
  ; // Conversion error occurred

However, this approach is less protected from integer overflow than the previous one.

Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple

// Convert C-string to integer
char *end = nullptr;
long value = strtol((const char *) payload, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

No extra buffers required.


Read CID from SD card with ESP8266 I would like to get the serial numbers of SD cards, with follow code:

#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

cid_t cid;  // *****at the top with the other globals (for get cid)

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;

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

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println();

  // *****list all files in the card with date and size
  //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  //root.openRoot(volume);
  //root.ls(LS_R | LS_DATE | LS_SIZE);

  card.readCID(&cid);
  Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

}

void loop(void) {

}

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".

Also, I would like to get the complete CID like this:

CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

To print the serial number in hex Serial.println accepts a format parameter:

Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:

uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.


Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.
I just cant seem to figure out the mapping or setup for the code for this part.
I remember seeing it done before but my google skils are failing me and i cant seem to find it again.
Thanks

You can use the map function, see Arduino Map Function.
So in your case, assuming a value of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get
int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).
UPDATE
It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).
For this you need two maps depending on the value:
int mappedValue = 0;
if (value < 512) // Backwards
{
    mappedValue = map(value, 0, 511, 180, 0);
}
else // Forward
{
    mappedValue = map(value, 512, 1023, 0, 180);
}


Problem in bootloading my ATmega32U4 chip I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per
https://www.arduino.cc/en/Tutorial/ArduinoISP
 and I followed this instructions:

Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).
Upload the ArduinoISP sketch.
Wire your Arduino boards..
Select the item in the Tools > Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.
Select the Arduino as ISP in the Tools>Programmer menu.
Use the Burn Bootloader command.

But I am getting the error message as

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I am using 16Mhz crytsal oscillator along with 22pf

What might be the problem?

If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.

Possible hardware problems are:

You have bad solder joints / connections.  Even if you think the solder joints are good, try reflowing them again
ISP leads are too long - can lead to data corruption during bootloading
Pins are not correct.  E.g. are MOSI and MISO the correct way around?
Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem.  Post your board layout (or at least schematic) and we can look at it.  If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.


Communication with Arduino and electronic device(for example tv or computer) through rs 232 cable Say some electronic device (TV OR Computer) has an inbuilt program. Depending on received data from Ardiuno, it displays some text based on requirement. For example, if it receives 1 it should display 'error', else if it receives 0 it should display 'ready'.

  I am working on only sending signals/bytes from Arduino Uno to some device which already has an inbuilt program. I just want to send 0 or 1 byte from the Ardiuno to the device using TTL to RS 232 COVERTER.
  this is the code

#include<SoftwareSerial.h>

 #define rxPin 0 //make pin o as rx pin

 #define txPin 1//make pin 1 as tx pin

 SoftwareSerial mySerial(rxPin ,txPin);//i donot undersatnd this line (i got
 the code from net//

 void setup()

 {

     pinMode(rxPin,INPUT);//making rx as input//
     pinMode(txPin,OUTPUT);//making tx as output//
     Serial.begin(9600);
     mySerial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.print(0x00);//i want to send 0 byte data from ardinuo to device //
delay(200);
}

  I am using RealTerm software to check if the signals I have sent from the Arduino Uno are received as they have to be (without any interference).

  I am sending continuously 0 from ardinuo to realterm in this case(for testing purpose). I am receiving in RealTerm in Hexadecimal format. Since I'm sending 0s continuously, I should be getting a continuous output of 0s on RealTerm as well. Instead, I am getting some random values initially (while uploading the sketch) and RealTerm stops displaying output soon after.

  Can someone please help me solve my issue.

  Update 1: i have modified my code as per @chrisl's  suggestion. Now, whn i send 0 i am getting a correct ouput ,but whn i am sending 1 contineosly i am  getting many 0's and random values

#include<SoftwareSerial.h>
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial(rxPin ,txPin);
void setup()
 {
 pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  mySerial.begin(9600);
  }

  void loop() {
     // put your main code here, to run repeatedly:
  Serial.print(0x01);//i want to send 1 byte data from ardinuo to
  device(realterm)
  delay(200);
   }

You have 2 problems:

You use the Serial.print() function, which outputs ASCII encoded characters. When sending "0" this way, actually the value 48 (or 30 in hex) will be send. RealTerm seems to display hexadecimal values, so you would get a long series of "30"'s. This is not really a big problem, you only shouldn't expect zeros to display there with this code. You can use the Serial.write() function to send direct byte values instead of ASCII codes.
You initiate the SoftwareSerial on the same pins, that are reserved for the Hardware Serial. This cannot work properly, because both libraries will try to use the same pins. Choose other pins for Rx and Tx of the SoftwareSerial interface.

EDIT:

Also you are setting pin modes for Rx and Tx of the SoftwareSerial. I don't know, if this can cause a problem, but at least you don't have to do this. The library will handle setting the pins correctly.

EDIT2: Further explanation about binary, hexadecimal and ASCII representation of the Serial byte stream

There are different methods to display a stream of byte data (like the stream from your Serial interface). Let's look at the decimal value (the one you are using when invoking arithmetic operations like +, -) 48. These are the different representation of this number in different numeral system (The first two characters mark the numeral system; 0b for binary, 0x for hexadecimal):

binary: 0b00110000
hexadecimal: 0x30

There are more numeral systems, but these are the most important ones. But the byte stream can also be used to look like a sequence of characters. For this the ASCII standard was born long time ago. In simple ASCII every value from 0 to 127 got assigned to a character or control action. The terminal program reads the byte stream and shows the corresponding characters according to the ASCII table. There are expansions to this model, to display more possible characters, but this is the very basic principle. With it, you are able to actually send human readable text from your Arduino to another device.

The Serial.print() function is made for this human readable text, so it will send an ASCII representation of the input parameter. The ASCII value of the character "0" is 48, which corresponds to a hexadecimal value of 30.

Now I'm not sure, if your terminal program shows hexadecimal or ASCII values. I though of the first, because all characters in your first image are digits or characters from A to F, which is the range of hexadecimal values. It didn't seem likely to not get other characters, when you have ASCII encoded text with random values in it. But I'm currently not sure, if the Serial.print() function would automatically print a hexadecimal representation in form of ASCII text, if given a hexadecimal value (I don't think so, but it might be possible). Please try to use the Serial.write() function and try sending different value while watching the output of RealTerm.

And please search for a settings, that determines, how the received byte stream is interpreted. This would make clear, what RealTerm is doing here. Also make sure you understand the relation between binary value and ASCII character. If this is still not clear enough, you can google for in detail explanations. There are tons of tutorials on that.


SIM800L Arduino Pro Mini I am trying to send an SMS using the Sim800L module and it seems to be unable to connect to the network. When I send the AT+COPS=? command it shows me a list of all the available networks along with the carrier of the sim card inserted but the module is unable to connect to the network. AT+CPIN returns an error as well. I read that changing the antenna will help but I don't think this can be the case as the networks are being detected. What could be going wrong?

Make sure that you are giving it enough power, seaching and registering to a network needs a current peak of 2amps, if the model you are using has a built-in regulator plug it to a stable 5v 2amp source of power and try AT+COPS? again, it should work; you can try with the computer power supply it has a 5v 2amp source.


Programming many Arduinos simultaneously with a wireless broadcast I will have many microcontroller-based devices which will be independent from each other, but all will run the same program.

I would like to upload a program to all of them at the same time with a wireless broadcast. Ideally the user would plug in a USB controller to his computer, and upload a program from the Arduino environment as if s/he were programming a single device.

To get a better idea of what I'm talking about, please take a look at this video. This was achieved with Atmel microcontrollers but a custom-made, non-Arduino bootloader.

From a Google search for "Arduino infrared programming" this interesting project came up. The main drawback is that the reset button still has to be pressed manually. Ideally I would like the devices to be in a low-power state by default, and wake up to receive a program when they sense a signal from the controller. Still, this may be a good starting point for me.

I just wanted to get some perspectives from people who are familiar with Arduinos as to whether they think this is feasible before I jump in.

TL;DR -
You have the options of either BlueTooth or XBee (amongst others: IR, for example?) for wireless uploading. However, I believe that only one board can be uploaded to, at a time, so you will need to cycle through the boards one at a time, see Programming multiple ATMegas/Arduinos at once.

When uploading a sketch or using a programmer (for sketch or bootloader), the software does not just write the code, it actually communicates with the microcontroller.
You can't program them all at once. But you can program them one by one in some automatic way.

Your question is a very interesting one, and asks a question that I am sure that I would never have thought of, but would be extremely useful and labour saving, especially if one has, as I do, many Arduino controlled sensor points located around the house. Here is one rather inelegant solution that may be worth trying.
Wireless upload hardware
If you use BlueTooth to wirelessly upload your sketches, then this solution might be of use, Wireless upload program to Arduino without USB cable. Note that this solution ties up pins D0 and D1:

But be careful that it maybe not compatible with some projects which need to use the D0 and D1 as hardware UART TX, RX. Because the wireless programmer needs to permanently occupy the two pins.

Looking at it, it employs a custom Arduino Wireless Programmer, to which you may have been referring in your question. However, don't be fooled by the name, it is simply a Bluetooth shield. It is basically a BT HC-05 (or similar) device, bolted onto an Arduino, see also Bluetooth Wireless Upload.
Alternatively, en lieu of BlueTooth, you could use XBee devices, see Wireless Programming of Arduino. The advantage of using XBees is that you would not have to go through the pairing new device loop (see below), that would be required when using BT. Instead you would merely have to cycle through the XBee network IDs.
However, in addition to that, you would need to automate the switching of BT devices, selecting the appropriate port and uploading to each Arduino in turn, as you are not able to broadcast sketches. (If am I wrong, then will someone please correct me).
Selecting the port and uploading the sketch
You could use a script along with the command line version of the Arduino IDE, to select the port that the BT device is connected to, before each upload. How you do this will vary for which ever platform you are compiling upon, see Command line Arduino compiling and downloading? This can be done using the environment variable ARDUINO_COMPORT (see the possibly out of date Windows command line build), or the arduino cmd line option --port <portname> ( see the man page). The sketch would then be uploaded using the option --upload <filename>. You could do this in one fell swoop:
arduino --upload --port <portname> FILE.ino

Note that on Windows you should use arduino_debug.exe.
Or you could use Ino, if you are not using a Windows PC... but that might make the next part, which deals with the looping more complex than it needs be.
Selecting each of the Arduinos (i.e. the BT devices)
Next, you would need to add a loop to the script, that pairs the PC to each BT device in turn and thereafter calls the Arduino IDE, for the port selection and uploading. Unfortunately, this would not be platform agnostic at all, and would require a different solution for what ever platform you are using. Take a look at Bluetooth from the Command Line, but for Windows you would probably require the Blue Tooth Command Line tools suite.
On OS X you may be best off resorting to using AppleScript, see Connect to bluetooth device (iPhone) via command line on MacOSX, as the cmd line tools for controlling BT seem a little scant - there is BlueUtil, see How to control Bluetooth wireless radio from the command line? but that only appears to turn the BT on of off. However, bolting AppleScript on to the rest of the Arduino IDE control script quickly makes things more complex, although you could just put the Arduino command within the AppleScript, I guess.


DHT.h Library not being imported I am trying to read the humidity and temperature using a DHT11 temperature sensor for an Arduino UNO using the DHT.h library. I have my code below:

#include <DHT.h>
#define dataPin 4
dht DHT;

void setup() {
  Serial.begin(9600)

}

void loop() {
  int readData = DHT.read11(dataPin);
  float t = DHT.temperature;
  float h = DHT.humidity;
  Serial.println("Temperature: ")
  Serial.print(t)
  Serial.print(" ºC")
  Serial.println("Humidity: ")
  Serial.print(h)
  Serial.print(" % ")
  delay(2000)
}

When compiling the program, it gives me an error:

fatal error: DHT.h: No such file or directory

I have also tried with lower case letters, but it will not work. Is there any reason why? Do I have to install it? I have tried to search for the library in the Arduino app Sketch - Include Library - Manage Libraries, but the library is not there.

Download https://github.com/RobTillaart/Arduino/archive/master.zip
Copy the Arduino-master/libraries/DHTstable subfolder of the downloaded file to the libraries subfolder of your sketchbook folder. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location in the Arduino IDE.
Change the first line of your sketch from:

#include <DHT.h>

to:

#include <dht.h>

Now when you try to compile the sketch you will still encounter many errors. However, these are caused by a paucity of semicolons, not by the DHT library, and thus off-topic for this question.


Non-blocking SoftwareSerial.Write How to use SoftwareSerial.Write without blocking if buffer is full? Serial.write blocks if the buffer is full. So I need to check Serial.availableforwrite before calling write to prevent blocking. But there is no SoftwareSerial.availableforwrite. How can I use SoftwareSerial.Write without blocking?

In short, you don't.
The SoftwareSerial implementation for AVR doesn't have an outbound buffer at all.
It just turns the interrupts off during each character outbound and it sends them all immediately.
This means a call to SoftwareSerial's write simply will block until all of the data you've tried to send has in fact been sent.  If you can't afford to wait for your data to go out on the TX line now, then it's up to you to send it later when you can afford to wait.
SoftwareSerial has no flow control.  When you write(), the data is sent out on the TX pin regardless of whether anything is present on the other side of the connection.  And when present, the data is still transmitted regardless of whether other side considers itself "ready" to receive.  There's simply no feedback from the receiver to tell the sender to stop.  So SoftwareSerial itself will never block owing to these things.


Error conecting raspberry with my arduino in a serial port Hi i am trying to make a comunication between theses device but when i am trying to run in my raspberry i have the follow error:

  Traceback (most recent call last):
    File "serial.py", line 1, in
      import serial
    File "/home/pi/Desktop/serial.py", line 2, in
      ser = serial.Serial('/dev/ttyACM0', 9600)
  AttributeError: 'module' object has no attribute 'Serial'

i have the next code:

import serial

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

while 1:

    if(ser.in_waiting >0):
        line = ser.readline()
        print(line)

If any can help me, i will be thankfull

What's almost certainly happening here is that you've named your file serial.py, so the import is trying to load the library from your file within the current working directory.

To fix this problem, simply rename your serial.py script to something else, for example serial_comms.py or whatever other useful name you want.


rs485 and serial ISP I made a couple of arduino mini pro and esp8266 pcbs with an rs485 transceiver just to find out that I forgot to think about in-system-programming:

Assuming that I don't need to disable the transceiver i tied *RE/DE to gnd/vcc. It turned out that id do need disable the transceiver (at least the receiving part) in order to be able to program the mcu because otherwise the transceiver disrupts the serial data.

But I don't want to lose one pin for this (which in case of an esp8266 are rare) and I don't want to use jumpers because I really like the workflow without.

Is this even possible?

EDIT: The transceiver is an SP3485.
Currently it is connected like:

Mini Pro     SP3485
A-rx ------  RO
GND  --1k-- *RE   A  ---- somwhere else
Vcc  --1k--  DE   B  ----        "
A-tx ------  DI

Which blocks serial programming because of a) the "echo" and b) holding A-rx line high.

If I connect *RE --1k-- Vcc and DE --1k-- GND I can ISP the Arduino, but now I obviously can't use the transceiver anymore.

I can't understand the purpose of connecting *RE/DE to GND/Vcc. With
this setup, the driver inside the transceiver is always enabled, and
it's always driving the A/B pair. Meaning the device at the other end of
the link cannot drive the pair itself without making a collision.
Basically you have a simplex link, where the Pro Mini is always the
sender.

The normal way to connect an RS-485 transceiver is to have DE driven by
a GPIO pin of the MCU. You pull this pin HIGH when you want to talk, and
leave it LOW the rest of the time so you can hear other devices talking.
The *RE pin is connected either to GND (if you want to hear the echo of
what you say) or to DE (if you don't).

That being said, you are correct in that the transceiver may cause
problems when uploading the firmware on the Pro Mini. One possible
solution is to put a resistor between RO and A-RX. The TX of the FTDI
cable should have a low output impedance and be able to overpower that
resistor. Another option is to use ICSP (in-circuit serial programming)
instead of going through the bootloader. It would be easier if you can
put an ICSP header on your board.


How do I combine a variable and characters into a string with Arduino? I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.

My plan is the following:

*If the PLC wants a reading from sensor #1, it will send the string: "1,read"
All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

*What I am trying to do is come up with a line of code similar to the following:

    if (plcCommand == (Matrix.Address + ",read<CR>")) {
  mySerial.print(GenerateEquation());

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.

It seems like a very simple thing to do, but I am having trouble coming up with a solution.

Any help would be appreciated!

You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.

Say you are being sent the string 32,read\r. Instead of making another string 32,read\r and comparing it to what you have received you should instead be splitting the incoming string up.

That way you then have a string containing 32 which can be converted to an integer, and a string containing read. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.


Atmega168 Watchdog timer I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.

Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps > System Reset every 8 sec > goes back to sleep.

While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources.

I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.

Here a basic rundown of what I was thinking about.

ISR(wdt_timer)
{
    how to stop the full system reboot?
    how to make the interrupt start again?
}
ISR(button_press)
{
      gotoSleep=0;
}

void watchdog_init()
{
    /* Reset the wdt. */
  wdt_reset(); //from wdt.h

  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   */
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  /* set new watchdog timeout prescaler value */
  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

  /* Enable the WD interrupt (note both interrupt and reset). */
  WDTCSR |= (1<<WDIE) | (1<<WDE);
}

void main ()
{
    watchdog_init();
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        reset_watchdog();

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        gotoSleep();

        //wake up here

    }

}

Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.

Also, consider using <avr/wdt.h> and <avr/sleep.h> to handle (most of) the watchdog and sleep functionality.

EMPTY_INTERRUPT(WDT_vect);

void main ()
{
    watchdog_init();
    set_sleep_mode(SLEEP_MODE_STANDBY);
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        wdt_reset()

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        {
            sleep_enable();
            sleep_cpu();
            sleep_disable();
            WDTCSR |= _BV(WDIE);
        }
    }
}


ESP8266 ESP-12 Connection I am connected with my ESP-12 through a programmer and all the AT functions work correctly. However I do not get a connection when connecting to the ESP8266 module.

I have done the following:

Set the mode both: AT+CWMODE=3

Connect to an Access Point: AT+CWJAP="<name>","<password>" (Responds with WIFI Connected and WIFI Got IP)

Set the Access Point: AT+CWSAP = "<other_name>","<password>",<channel>,<password_security>

So at this time it should be connected to my local network and I can connect to it through wifi on my laptop. However when I connect to it, it says 'Connected, No Internet' (The network the esp8266 module is connected to, has internet).

When I troubleshoot problems it says DNS is not responding.

Does anyone have a clue what to do next? Or what I might do wrong?

You can make the ESP8266 behave as a router, see Google for details.  By default it won't do this.

You need to create two separate WIFI networks and then tell the ESP to 'route' traffic between them.

Your ESP needs to form one network (STA mode?).  Your laptop needs to be on one network with the ESP.  The laptop needs to be configured to use the ESP as the gateway and unless your ESP has a DHCP server the laptop needs a static address.

Your ESP also needs to be a client to you router's network, and needs to take an address from the Router's DHCP server.


Replace Wire library with TinyWireM I want to integrate Pololu's vl53l0x Time of Flight distance sensor into a project of mine. They created a library to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.

TinyWireM is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?

Thanks!

In fact, there would be nothing to do now I guess, as TinyWireM is now included tiny boards packages.

If you just include Wire as usual, it should work as on an UNO.
Except for setting a different clock, if I remember well, it is fixed to 400kHz.