Using voltage divider to read voltage from sensor Good morning,

I would like to use an Arduino Duemilanove to read the voltage signal generated from a current sensor (CSLA2CD). The datasheet for this sensor can be found here.

The problem is that the sensor requires a supply voltage of 6 to 12v. The signal output voltage is half the supply when no current flows through the sensor. I am using a 8v regulator for its supply, so the signal voltage may range from 4v (no current sensed) all the way to about 6v (about 60 amps).

Unless I'm mistaken, the arduino's analog pin can detect from 0v to 5v. So it would only accurately provide me data up to the 5v signal mark.

My questions are:

Would a voltage divider be a good solution to reduce the signal voltage to a range the Arduino can read? If so,
what would be the best resistor combination to use?

If there are better solutions than a voltage divider then please share.

Thanks very much!

It should work, but I don't know if its the best way.

Because the maximum voltage is 12 volts (I know you are only giving it 8, but you don't want to fry your board) you need the divider to send the Arduino 5/12 of the power.  You don't need much current, so you can use big values or resistors.  10K and 24K should work, but you should research or test this before you hook it up to you kit.


Micro not detected, can't reset I just picked up a new Arduino Micro for a project, but the first time I tried to upload to it, things went terribly wrong. The USB cable was loose, so the power light kept blinking on and off. When I did get it stable, I accidentally had 'Uno' selected under 'Tools->Board'. I think this was the source of the problem.

I'm aware that the solution for these kinds of problems is to try to upload some simple code while in bootloader mode, but pressing reset shortly after pressing the Upload button. But this board doesn't even respond when I press reset. I have tried it with both the on-board button and with an externally button linking RS to ground.

Furthermore, the board doesn't show up in my Device Manager, not even as an "Unknown Device". The device managed doesn't even refresh when I plug it in.

I know the connection is okay because the power light is on. And I know it's not a driver issue or an issue with the port, because I have no trouble getting a different Micro recognized.

The only thing I haven't tried is burning the bootloader through ICSP, since I don't have the right cable. Is there anything else I can try, or is this just bricked?

Thanks, everyone

This is probably way to late, but with newer editions of the Micro you have to "double-press" the reset (input).

I have had some experiences today where playing with low-power modes that shuts down the usb interface, and the only way I got it back was activating the reset input twice fast, and then uploading a new scetch (this time with a 10sec delay before any usb-chaning stuff takes place!)

Richard


ESP8266 - 12F High consumption in led blink (with pictures) My esp is consuming 180mA with a led blink. The same consumption happens when I put it in WIFI_STA mode with the WiFi.mode(WIFI_STA); function.
What should I do to reduce consumption? Used AMS1117 CI as tension regulator.

My code:

void setup() {
  pinMode(2, OUTPUT); // pin number 2 is on board blue led
}

void loop() {
  digitalWrite(2, LOW); // blue led highlight with LOW level
  delay(100);
  digitalWrite(2, HIGH);
  delay(100);
}

Why all this consumption?

The SDK library of the ESP8266 remembers on flash memory the mode, SSID and password of the last WiFi network it connected. At start or by enabling STA mode it tries to connect to that network. The SDK library is always part of the compiled sketch for the esp8266.

The esp8266 WiFi library has some functions to control this:

WiFi.setAutoConnect(false)
WiFi.disconnect(true);
WiFi.persistent(false)


Why perform bitwise operations here? (SPI FRAM read method) See: https://github.com/adafruit/Adafruit_FRAM_SPI/blob/master/Adafruit_FRAM_SPI.cpp
The following method reads and converts the input to 8 bit. I have several questions concerning its function.

Using addr = 0xFFFF as an example, the method converts the variable to 0xFF. I understand that bits are removed from the end, but surely 65535 != 255. Perhaps relatively, to their max size, but how is this a useful conversion? I might be missing something about bitwise here..

uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
 digitalWrite(_cs, LOW);
 SPItransfer(OPCODE_READ); //read memory from fram array (2-byte)
 SPItransfer((uint8_t)(addr >> 8));
 SPItransfer((uint8_t)(addr & 0xFF));
 uint8_t x = SPItransfer(0);
 digitalWrite(_cs, HIGH);
 return x;
}

Correct me if I'm wrong, the casting is to keep sign extension from occurring.

The masking I understand in theory, but do not at all understand its application here.

Finally, it always returns the same value x = 0, why?

I also see there's a write method but no read method. Only read8. Reasoning?

Let's assume addr is 0xbeef. Then, if we break down each operation:

expression             │ value
───────────────────────┼───────
addr                   │ 0xbeef
addr >> 8              │ 0x00be
(uint8_t)(addr >> 8)   │   0xbe
addr & 0xFF            │ 0x00ef
(uint8_t)(addr & 0xFF) │   0xef

So this is essentially breaking down the address into two 8-bit chunks,
and transmitting those chunks individually. It's done like this because
SPI only transmits bytes.

  the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since addr is an unsigned number.
The casting really serves no useful purpose, other than documenting the
code. It would be done implicitly simply because SPItransfer() takes
an uint8_t argument. The casting could be useful if SPItransfer()
was overloaded with a 16-bit version.

  Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to SPItransfer(0); returns, i.e. the
data sent by the FRAM module.


Controlling 10+x 5m led strips with 10+ individual analog floor switches I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.

The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.

I have a number of questions:

How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)
How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:
How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.

Thank you!

I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.

Maybe this can be slightly overkill, but you can think of using a MAX7313.

This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.

This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.

Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...

This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.

Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).

Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).

Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you


Can't upload sketch to arduino Uno board I'm trying to upload a simple sketch to my Uno board but get this error message: avrdude: stk500_recv(): programmer is not responding (full error message at the end).

I have other Uno boards who work fine so I guess it is something to do specifically with this board (which used to work) and not my system or cables (port,drivers,settings etc..).

I did a loop-back test (http://forum.arduino.cc/index.php?topic=73748.0) on  the board and it worked fine.

I read about possible solutions but nothing seems to solve this.
https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi

I also tried using an Arduino as an AVR ISP but it failed. (https://www.arduino.cc/en/Tutorial/ArduinoISP)

Any help will be appreciated, thanks in advance.

Full error message:

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM3
     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=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd3

    avrdude done.  Thank you.

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

In Arduino IDE check that

correct port number is selected in Tools -> Port
correct programmer is selected in Tools -> Programmer (should be AVRISP mkII if you upload the code via USB cable)
correct board is selected in Tools -> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.


Make an Arduino board act as both a usb storage device and a keyboard? I am making an interface project that, when plugged into a computer, shows up as both usb flash storage and can type like a keyboard when some physical buttons on the board are pressed.

I have seen projects that do one or the other, but not both at the same time.

I have gotten it to work using a usb hub and two chips that are sharing the same storage (since I want the hot-key buttons to type out information stored in the flash drive side as well), with one acting like a HID and one acting as usb storage, but this has a few problems. First, it feels redundant. Second it's difficult to program since every time I plug the mess in it randomly assigns a name to each chip with no easy way of telling which to send the HID code to and with to send the USB Drive code to. I have to plug them in one at a time which wont work once this project is all on the same board. The last problem is the buttons work inconsistently since, im assuming, the two chips are not doing a nice job of sharing access to the text file it's trying to read for the text to 'type out' on the computer.

Is there a nicer way of doing this that uses one arduino acting in both roles accessing the one flash storage? Thanks!

The Leonardo can easily be used as a keyboard. There are also special codes to turn the USB-to-Serial chip on newe Unos into a keyboard (see here)

USB mass storage is another game all together. The Brondani EasyUSB is a simple chip that exposes 2MB of storage space on both the USB and microcontroller. They say they will be releasing larger capacities.

The easyUSB also has a serial link built into it from uC to computer.

If you really want, you can make your own USB stack to handle this on you own, but the pitifully small amount of ram on these chips would prohibit it.


Transistor amplifier to drive speaker using Arduino PWM I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker

But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.

I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are

1) How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?

2) Was the less audible sound is due to the Wav file i have used?

Kindly help me out, thanks in advance.

Your amplifier arrangement is fundamentally flawed. At the moment you are "tickling" the top end of the electromagnet in the speaker - that is, you are energising it when the Arduino outputs a HIGH, and leaving it energised to de-energise by itself when the Arduino outputs a LOW.  Coupled with that the fact that a PCM file outputs PWM with a carrier frequency much higher than a tone() function (and ideally above human hearing frequencies) you end up with almost nothing happening on the speaker.

The classic Class A amplifier has a different arrangement:

simulate this circuit – Schematic created using CircuitLab

With that arrangement the transistor and R1 form a simple RTL inverter. Size R1 to give the output current you need for your speaker (lower resistor = more power = more heat = bigger transistor as well). R3 and C2 remove the high frequency switching from the PWM (you could also replace R3 with a suitable inductor if you want less losses from the resistor). C1 removes the DC offset from the signal to give the full swing to the speaker and prevent excess clipping and heating.

It's not an efficient design by any means. A better "first stage" (replacing R1 and Q1) would be a high drive output logic gate (one of the CD4000 series, since it can run from 12V). I have seen AND gates used before - this also gives the benefit that you can use the second input to the AND gate as a MUTE signal. The rest (R3, C1, C2) remains the same.

The advantage of using a logic chip instead of the RTL arrangement is that it gives a more efficient "Push-Pull" output which can deliver much more current with far less heat losses.

Instead of the speaker you could connect an audio power amplifier to the output of C1 to then drive a more powerful speaker. In this case you can most likely remove the first stage (Q1/R1/R2) and drive the RC filter directly from the Arduino.


Using Arduino Nano as USB Host I'm pretty new to microcontrollers and Arduino and since I can't find any satisfying information on my problem, I hope that you might answer them:

My project is actually quite simple: I just want to write out data over a serial connection via USB, the problem: My Arduino Nano has to run as USB Host. That's because the other device is a vacuum cleaner: Neato XV-25 with a mini usb jack. I was already able to 'talk' to it using a Raspberry Pi.

Since I don't have much knowledge about USB communication, I would like to know the following, before I start digging deeper:

I found out, that I would not be able to use the 'usual' usb port of the nano. But I've read a few things about that 'V-USB' library, but did not understand very much. Would it be possible to create a USB Host with this library, that can communicate via a virtual serial connection?
I stumbled across the USBHost for Android Nano. It's a shield, but I'm not sure if it would fit my needs. Is it able to handle serial communication? And is there somewhere a store where I can get it cheap? I think more than 20$ for a shield is a bit too much...

V-USB is a software-only implementation of a low-speed USB device for Atmel’s AVR® microcontrollers

No host support here, sorry.
The USB host shield handles the hardware bit and simplifies the software bit. It is up to the firmware to support the various USB profiles. Version 2.0 of the library supports CDC with a few devices; check to see if they would be correct for your purpose.


ModbusMaster.h - changing node I'm using the ModbusMaster.h library on a project, with arduino-uno and a TTL/RS-485 converter, and the function has to identify the slave that it is communicating. The slaves goes from 1 to 16. After I've begun the connection,

ModbusMaster node(1);
node.begin(9600);

I have to send a message, and if this massage returns an error, I have to change the slave number, until I got an valid answer. But I didn't find any functions to close this connection, or to delete it, I even have tried,

delete &node;

but it didn't work. I'm trying to close this connection so I could begin another one with another node, because I didn't find a function to change the slave number.

Maybe this question is too old and the API has changed, so my answer is reference.

The ModbusMaster constructor does not accept parameters.

From reading the source code, the method begin(uint8_t slave, Stream &serial) just initializes variables and can be called again with a new slave value without the need to destroy the ModbusMaster object.

Reference:

[1] https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp, line 61.


Responding to a broken laser beam? Firstly, I must apologise as I'm a complete noob but the Arduino kits / lego pieces are fantastic and I can't stop tinkering.  Unfortunatley my knowledge does not match my passion.

I picked up a laser from Amazon: FamilyMall(TM) KY-008 Laser Transmitter Module 650nm 5V Diode For Arduino AVR PIC.

I'm wondering what the middle pin is good for and if I can somehow manage to detect and respond to the beam being broken?

Thanks for looking. :)

Without a data sheet or the device on hand not sure what the middle pin is used for.  On the topic of detecting a broken beam the item you purchased is purely an emitter, in order to detect the beam being broken there are two main ways, using a photodetector on the "opposite end" of the beam but this means having wires trailing the same path as the laser beam, alternatively you could mount a mirror where the beam lands and reflect it back to a photodetector mounted close to the laser diode.  You would them use the arduino to detect the state of the photodetector.


Arduino Nano, ICSP header and 595 Shift register I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.

74HC595   |    A. Nano
DS     <-----> MOSI (ICSP)
SH_CP  <-----> SCK (ICSP)
ST_CP  <-----> D6
MR     <-----> 5V (ICSP)
OE     <-----> GND (ICSP)
VDD    <-----> 5V (ICSP)
GND    <-----> GND (ICSP)

My code:

//pin connected to STCP
const int latchPin = 6;
//pin connected to SHCP
const int clockPin = 17;
//pin connected to DS (MOSI)
const int dataPin = 11;

byte val=0;

void setup() {
  // put your setup code here, to run once:
  //SPI pins are output
  pinMode(latchPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);

  pinMode(3,OUTPUT);
  updateRegister(0);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(3,HIGH);
  for (int i=0; i<8; i++) {
    updateRegister();
    delay(500);
  }

}

void updateRegister() {
  //pull latch low to write new bits to the register
  digitalWrite(latchPin,LOW);
  //shift out the data
  shiftOut(dataPin,clockPin,LSBFIRST,val);
  //pull latch pin high so that the leds light up
  digitalWrite(latchPin,HIGH);
}

It is extremely confusing to have a variable val and then use _val in your function but then:

  shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.

Also this is just going to give you a boolean:

 updateRegister(!i);

Why take "not i" there?

I suggest you use SPI and not muck around with shiftOut. I have a page about the 595 chip including example code. eg.

#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop


Integrating an analog signal using Arduino Uno SMD I need to integrate an analog signal using my Arduino Uno. I am sampling the input signal at 1 KHz using a delay command in my void loop() and adding up the values at the analog read at that specific time. Then I multiply my added output with 0.001 s to get my integration.

Since, I am new to Arduino Uno, I want some review on the code to check whether I am correct or not. Kindly help, I'll be indebted.

const int a=13; //my output pin
const int c=A0; //my input pin
int d=0; //my summation variable
int e=0; //my integration variable(integration as a summation)
void setup()
{
  pinMode(a, OUTPUT);
}
void loop()
{
  int b=analogRead(c);
  d=d+b; //my summation
  e=d*10^-3; //my integration as a summation, by sampling my signal at 1ms
  analogWrite(a,e); //writing my integration into my output pin

  //print the results to the serial monitor
  Serial.print("input=");
  Serial.print(b);
  Serial.print("\t output=");
  Serial.println(e);

  delay(1); //wait for 1ms as I want it sampled at that rate
}

There are a couple of issues with your code.

First of all, 10^-3 is not a valid constant in C/C++ code. The correct syntax would be 1e-3, which means 1 × 10-3. But you have the further problem that you're working with integer variables, and 0.001 rounded to the nearest integer is just zero. You'll probably want to use float variables for this math.

Also, the values you get from AnalogRead() are all non-negative integers, so your summation will quickly overflow unless you subtract a constant from each reading in order to get both positive and negative values.

The second issue is about the delay() function, and trying to use it to determine the sample rate of your system. The delay() function is not all that precise. It really is just guaranteed to produce a delay of at least the number of milliseconds specified, but it can be more — sometimes much more.

Furthermore, the other operations in your loop take much longer than 1 ms anyway. For example, you're printing on the order of 25 to 30 characters to a serial port on every iteration, which is an overall rate of 25,000 to 30,000 characters per second. Unless you're running your serial port at an insane baud rate (430.8 kbaud or more), it simply won't be able to keep up, and it will end up increasing the period of your loop to whatever time it needs.

All of this means that the sample period of your loop is NOT 1 ms as you want, and in fact, it can vary quite a lot based on other things that are going on in the system, such as interrupts. For doing this kind of DSP, you will want to learn how to use a timer interrupt to control the sampling of the analog input, and you'll need to trim the amount of data transmitted for each sample to an amount your serial link can handle.


Converting the 3.3V PWM signal to 5V PWM signal I am using ESP32....the max Pwm signal of it is 3.3V...And I have to control two motors speed by TB6612FNG motor driver...when i was using Arduino.. The arduino can send max 5V Pwm signal to the motor drivers PWM pin.. And the motor runs at the exact speed...but now i have to use ESP32..which sends 3.3V and the motors slow down..

So what should I do to convert the ESP32's PWM signal to 5v and according If i change the PWM value at the program..the output will also change similarly as Arduino??
Please help me

Looking at TB6612FNG datasheet i read

  Logic supply voltage (VCC) can be in the range of 2.7--5.5VDC

So, if you supply 3.3V to VCC all should be ok, if the motors themselves get enough power (via VM)


ESP8266 returning 400 bad request I am trying to get JSON data from my website using an HTTP GET request, but I'm getting a 400 bad request error. Can someone let me know why am I getting this error and how to fix that? I am tired of looking at online resources.

I am trying to fetch data from www.himalayavats.com/to_fetch/system_info.json

I am using this code:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  sendData("AT+RST\r\n",1000, true);
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
  connectToWifi();
}

void connectToWifi() {
  String ssid = "moto g";
  String pass = "hvats555";
  sendData("AT+CWMODE=1\r\n", 3000, true); // Configure as client
  sendData("AT+CWJAP=\"moto g\",\"hvats555\"\r\n", 5000, true);  // Connects to wifi
}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  ESP8266.print(command); // send the read character to ESP8266
  long int time = millis();
  while( (time+timeout) > millis() ) {
    while(ESP8266.available()) {
      // The ESP has data so display its output to serial window
      char c = ESP8266.read(); // read the next character
      response+=c;
    }
  }
  if(debug) {
    Serial.print(response);
  }
  return response;
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {
  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();
    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();
    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"himalayavats.com\", 80");
    delay(1000);
    printResponse();
    String cmd = "GET /to_fetch/system_info.json HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);
    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
}

I get this response every time:

AT+CWMODE=1

OK
AT+CWJAP="moto g","hvats555"

WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP

OK
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","himalayavats.com",80

4,CONNECT

OK

AT+CIPSEND=4,43

OK
>
Recv 43 bytes

SEND OK

+IPD,4,1370:HTTP/1.1 400 Bad Request
Date: Tue, 19 Dec 2017 08:30:21 GMT
Server: Apache
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Connection: close
Content-Type: text/html

My JSON file on the website looks like this:

{"power" : "high"}

Take a look at the HTTP specification:

Request       = Request-Line              ; Section 5.1
                *(( general-header        ; Section 4.5
                 | request-header         ; Section 5.3
                 | entity-header ) CRLF)  ; Section 7.1
                CRLF
                [ message-body ]          ; Section 4.3

Request-Line  = Method SP Request-URI SP HTTP-Version CRLF

You don't send the CRLF (carriage return, line feed) at the end of your request line and at the end of the header at the same time of the request. Why the delay?

You also miss the obligatory host header.

Host = "Host" ":" host [ ":" port ] ; Section 3.2.2


Can I safely connect my original Arduino Uno to a 19V adapter? I have an original Arduino Uno R3. According to the specifications the recommended input voltage is 7 to 12 Volt.

However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.

I don't want to damage the Arduino or the DFRobot 2A Motor Shield I'm using. Can I safely plug in the adapter and will it still work correctly?

According to the page you linked:

  The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

So, yes. You can use the 19V external power supply to power the board. However, be aware that the voltage regulator can overheat over time and damage the board.


How do I change the I2C address on the LCD backpack? The 20 x 4 LCD comes with a I2C backpack.  I know it has A0, A1, A2 to set the address, as shown at the bottom here:  https://tronixlabs.com.au/news/tutorial-serial-i2c-backpack-for-hd44780compatible-lcd-modules-with-arduino/

It points to here:  http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/i2c-bus-portfolio/i2c-general-purpose-i-o/remote-8-bit-i-o-expander-for-icbus-with-interrupt:PCF8574_74A

My unit shows up as 0x3F.

And even with all this information I can't tell how to change it.

I need to have a second display on the same I2C bus.

Question:  How do I change the address of the second one?

As mentioned in the page you linked, jumper together one of the address jumpers. For example, above A0 are two pads. Solder a wire across them (vertically - between the two pads above A0). I am guessing the address is pulled high by a resistor, so that will probably make the new address 0x3E, but you could run the I2C scanner to check that.


SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino I would like to know.

I have Pin 6, 7, 8 and 9 as INPUT_PULLUP. I have switch to each other pin. Why when I press switch at PIN 6. SOMETIMES PIN 7 also getting input. Other case, also when I press switch at 7, other pin also trigger. Why?

This case is random. Sometimes everything is ok when I press 10 times, but after that other pin also trigger. Another case only 4-5 times press, then other pin also trigger.

I use switch on/off not temporary switch.

How to fix this? Is it common problem with arduino?

UPDATE

Program. (Simple Program)

int led1 = 1;
int led2 = 2;
int led3 = 3;
int led4 = 5;

int switch1 = 6;
int switch2 = 7;
int switch3 = 8;
int switch4 = 9;

int led = 13;

//int counter = 0;

void setup()
{
  // put your setup code here, to run once
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(switch1, INPUT_PULLUP);
      pinMode(switch2, INPUT_PULLUP);
      pinMode(switch3, INPUT_PULLUP);
      pinMode(switch4, INPUT_PULLUP);
      pinMode(led, OUTPUT);
}
void loop()
{

if (digitalRead(switch1) == 0){
  digitalWrite(led1, HIGH);
  }

 if (digitalRead(switch1) == 1){
  digitalWrite(led1, LOW);
  }

if (digitalRead(switch2) == 0){
  digitalWrite(led2, HIGH);
  }

 if (digitalRead(switch2) == 1){
  digitalWrite(led2, LOW);
  }

if (digitalRead(switch3) == 0){
  digitalWrite(led3, HIGH);
  }

 if (digitalRead(switch3) == 1){
  digitalWrite(led3, LOW);
  }

if (digitalRead(switch4) == 0){
  digitalWrite(led4, HIGH);
  }

 if (digitalRead(switch4) == 1){
  digitalWrite(led4, LOW);
  }

digitalWrite(led, HIGH);

delay(1000);

digitalWrite(led, LOW);

}

Schematic

My Circuit is simple as like that for the input. For the output only to led, resistor and ground.

I found similar case http://www.instructables.com/id/Arduino-Push-Switch-Debouncing-Interrupts/

  On the website, He said, "The problem with this setup was when the
  button was pressed the interrupt was being called multiple times and
  even toggling other buttons. Why was this happening? It is caused from
  a switch bouncing feedback."

Is there any solution without modifying the hardware?

SOLVE

The problem is the wire.

My wire for switch is jumper cable, and each other closer (touch) to each other cable. I try to separate, and works. There is no other pin will be trigger.

You may be getting switching noise between the button wires, which is low-level and brief, but with no debouncing, it could be just enough to cause the effect you're seeing.

I'd suggest 1) writing a short function that debounces and reads any button; and 2) using if/else statements instead of testing each button twice.

A quick test is to hold one pair of wires closer together or farther apart from each other while you press one of those two buttons, and see whether the distance apart changes the effect. If it does, you've found the cause.


Arduino Start en Stop Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

Really stop Arduino is possible, it's called sleep mode, but the UNO is designed so badly with respect to power consumption that you may as well keep it running.

To have it done something at a specific time you could connect a real time clock (RTC) breakout board (SparkFun has a couple). Use a 1 second timer interrupt to read the clock and compare it with (a table of) times where you want things done. A table could hold the time, an output (e.g. for a relay) and the new status (on or off). If you have just a couple of those you can store them in the RTC's battery-backed up RAM.

edit
You can use your PC's time, all the hardware you need is the USB cable. On the PC you run a program that sends the current time to the Arduino. (There are Processing examples of how to communicate with the Arduino on the Net.)

Note that without an RTC your PC will have to be on all the time and connected to the Arduino. You could use the PC just to sync the Arduino's clock and keep time yourself, but the clock of the Arduino is not very accurate.

Getting the time from the Internet is also possible, but then you'll need a Wifi or Ethernet shield to make the connection.


Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding I'm newbie in Arduino Dev

I got Arduino Uno R3, at first it just worked fine.
I tried to upload my whole project sketch which almost up to the max size of arduino memory.

Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.

I already remove all cables connected, still failed to upload.

I really dont know how to fix this.

First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate.  If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening.  It sounds like you've covered this as well by trying simple sketches.  Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window.  Also, double check inside the IDE that you still have the correct board selected.  Occasionally / rarely, I've had to reboot Windows to cure the problem.

The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....


Three or more Arduino slaves sending bytes to 2 different I2C devices I'm trying to connect 3 Arduinos with this scheme: Arduino1 Master, Arduino2 Slave, Arduino3 Slave. The slave devices need to communicate with each other and I'm trying to programming Arduino2 and transmit bytes to the other slave device Arduino3 and Master Arduino1 at the same time. Is that possible?

Master CODE:

#include <Wire.h>

void setup() {
  Wire.begin();
}

void loop() {
  Wire.requestFrom(0x04, 2);
  while (Wire.available()) {
    var1 = Wire.read();
    var2 = Wire.read();
  }
}

Arduino1 Slave:

#include <Wire.h>

void setup() {
  Wire.begin(0x05);
  Wire.onReceive(receiveEvent);
}

void loop() {
}

void receiveEvent(int howMany) {
  var1 = Wire.read();
  Serial.print("VAR1 is : ");
  Serial.println(var1);
}

Adrduino2 Slave code:(Where I think I'm wrong)

#include <Wire.h>
int var = 123;
int var2 = 123;
int var3 = 123;

void setup() {
  Wire.begin(0x04);
  Wire.onRequest(requestEvent);
}

void loop() {
  Wire.beginTransmission(0x05);
  Wire.write(var);
  Wire.endTransmission();
}

void requestEvent() {
  Wire.write(var1);
  Wire.write(var2);
}

Is this the correct way to make the Arduino2 send to 2 devices?

As soon as an Arduino starts writing data, it is a Master. Do you use Arduino Mega 2560 and Arduino Uno and Nano boards ? In theory those ATmega microcontrollers can handle collisions in a multi-Master bus, and in theory the Wire library handles collisions as well. However, everyone tries to avoid that, because it causes a lot of problems. You would even have to program a complete new layer in the code to re-transmit data until it was received without collision.

Select one Arduino board as Master, and use the Master to read and write data. If you want to transfer data from one Slave to the other Slave, then use Master to read the data from one Slave and write the data to the other Slave.

It is possible to use other busses between the two Slave Arduino boards.


How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino? I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.

I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.


build fixed size strings from floats This is likely a duplicate, but I couldn't find the original question. This is really basic, but just can't figure it out.

I'm trying to combine a few char arrays together. This is what I've tried so far.

float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[4];
dtostrf(a, 4, 1, a_string);

char b_string[4];
dtostrf(b, 4, 1, b_string);

char c_string[2] = {'0', '\0'};
if (c) {
  c_string[0] = '1';
}

char output[12] = "-----------";

output[0] = a_string[0];
output[1] = a_string[1];
output[2] = a_string[2];
output[3] = a_string[3];

output[4] = ' ';

output[5] = b_string[0];
output[6] = b_string[1];
output[7] = b_string[2];
output[8] = b_string[3];

output[9] = ' ';

output[10] = c_string[0];

Serial.println(output);

Results in an empty string in seems.

If I remove the second dtostrf(), and change b_string[0] ... to a_string[0] Then I get 12.3 12.3 1. Doesn't seem to like having dtostrf() called more than once, but it seems like the function I want, since it allows me to set a fixed strint size. The output I'd be looking for is 12.3  5.4 1

another approach

String a_string = String(a, 1);
String b_string = String(b, 1);
String c_string = String(c);

String output;
String space = " ";

output.concat(a_string);
output.concat(space);
output.concat(b_string);
output.concat(space);
output.concat(c_string);

Serial.println(output);

This outputs 12.3 5.4 1. Is there a way to make the String fixed width? I'm looking for

12.3  5.4 1 instead of

12.3 5.4 1

What's the proper way of doing this?

EDIT

After trying to use the @Majenko's answer I sometimes get garbage values printed. Any ideas why?

float a = analogRead(A1) / 1023.;
float b = analogRead(A2) / 1023.;
bool c = analogRead(A3) / 1023;

char* output = createString(a, b, c);
Serial.println(output);

char* createString (float _a, float _b, bool _c)
{
    char a_string[5];
    dtostrf(_a, 4, 1, a_string);

    char b_string[5];
    dtostrf(_b, 4, 1, b_string);

    char out[12];
    snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
    return out;
}

and the output:

 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.�tS
�
 0.6  `S
�
 0.6  1.0
}
 0.6  1.0 0
 0.7  1.0 0
 0.6  1.0 0
 0.6  1.0 0

using

  Serial.print(a_string);
  Serial.print(" ");
  Serial.print(b_string);
  Serial.print(" ");
  Serial.println(c);

doesn't produce the errors

The simple way would be to format the string with sprintf - however sprintf on the Arduino lacks floating point support (although it is possible to enable it).

So if you convert your floating point numbers into strings first (remember to provide room for the NULL terminating character!) you can then use sprintf to format those converted numbers into what you want:

float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[5];
dtostrf(a, 4, 1, a_string);

char b_string[5];
dtostrf(b, 4, 1, b_string);

char out[12];

snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);

%4s is replaced by a string which is padded to at least 4 characters wide. The padding is to the left of the string. If you want the padding to the right you can use %-4s instead.

Addendum:

In your new posted code you are making a fundamental error:

char out[12];
snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
return out;

out is a local variable to the function. Its memory is allocated on the stack. You fill that with data and then return the address of that location on the stack. As soon as you leave the function that memory allocation is lost. Yes, the data is still there, but the moment you call another function that memory gets overwritten with the call frame of the new function you have called - thus corrupting your data.

You have two main options:

Make out global
Make out static

The effect of the two options is pretty much the same, except that in the second option the scope of out is restricted to the function which means you can use the name out elsewhere without it conflicting. In both options though the memory allocated to out is in the BSS not the stack and thus won't get overwritten.


I need help with code for two 74HC595 I created and learned this code myself from many examples. I tried to add another chip to it, but I have no idea. Do I need to rewrite all of it? Just some simple code is needed.

int latchPin = 2;
int dataPin = 3;
int clockPin = 4;
const int analogPin = A0;
const int ledPin = 13;
const int EmptyEn = 0;
const int GreenOne = 100;
const int GreenTwo = 200;
const int GreenThree = 300;
const int GreenFour = 400;
const int YellowOne = 500;
const int YellowTwo = 600;
const int RedOne = 750;
const int RedTwo = 900;
const int MaxHold = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop() {
  int analogValue = analogRead(analogPin);
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenThree) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11100000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > GreenFour) {
    digitalWrite(latchPin, HIGH);
    shiftOut(dataPin, clockPin, MSBFIRST, B11110000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > YellowOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > YellowTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111100);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111110);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > MaxHold) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(100);
  }
  Serial.println(analogValue);
  delay(1);
}

Look for a repetition in your code.

  //Repeating code..
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You will notice that you have a lot of repetition of the general structure of a if-comparison (always with a different value) and then a shiftOut with a different value to be shifted out.

  //General code structure
  //Only things to change is someComparisonValue and someDataValue
  //the rest is the same.
  if (analogValue > someComparisonValue) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, someDataValue);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You can generalize and simplify the code by storing those different comparison values and data values in a look-up table (LUT). Now you could use two arrays to hold these values but you could also further condense it in a C struct, a "data structure".

Let's define a data structure which holds a threshold value and then the data to be shifted out as  struct.

/* Defines a LUT entry */
struct LutEntry {
    int treshhold;  /* threshhold value */
    byte data;      /* data to be shifted out */
};

We can then pack the actual data into a single variable. Because this is constant data, it will take up flash memory instead of RAM.

static const LutEntry lutTable[] = {
    { GreenOne, B00000000},
    { GreenOne, B10000000},
    { GreenTwo, B11000000},
    { GreenThree, B11100000},
    { GreenFour, B11110000},
    { YellowOne, B11111000},
    { YellowTwo, B11111100},
    { RedOne, B11111110},
    { RedTwo, B11111111},
    { MaxHold, B00000000}
};

From there we can also see that there is a computable relationship between the index of the treshhold value and the data to be shifted out - an entry at index i will be associated with the data bitstring in which all bits from the MSB up to i inclusive are 1, the rest being 0. Except for MaxHold as special value. We could exploit this property to get rid of that data member entirely, but that is an exercise left to you.

Now we can re-write the loop code by simply taking a analogRead sample and then iterating through the entires of the LUT to shift out the corresponding data.

void loop() {
    int analogValue = analogRead(analogPin);
    int numLutEntries = (int)(sizeof(lutTable) / sizeof(lutTable[0]));

    for(int i=0; i < numLutEntries; i++) {
        if (analogValue > lutTable[i].treshhold) {
            digitalWrite(latchPin, LOW);
            shiftOut(dataPin, clockPin, MSBFIRST, lutTable[i].data);
            digitalWrite(latchPin, HIGH);
            delay(1);
        }
    }
    Serial.println(analogValue);
    delay(1);
}

Which transforms 69 lines of repeating code into 12 lines of non-repeating code.

After this general code cleanup it becomes easier to add another shift register: You can define a new look up table, or modify the structure of the old one, to hold the information you need (treshholds, data to be shifted out, the clock, data and latch pin for the register, ...). What logic needs to be there is something only you know, because the description "add another chip [to this code]" is quite broad.

In short:

DRY: Don't repeat yourself. If you use a piece of code over and over again with only slight variances in used values, make it a function
recognize the differences of the used data values in used code pieces and try to group them neatly together. Use the language feature of structs or class to express the meaning of this data
exploit certain properties / relationships of your data to save even more memory / computing time.


How can I add phonebook entry to sim card using Arduino GSM shield? I am using Arduino GSM Module and Arduino UNO

I want my GSM module to be stand alone once I programmed it. It will store the phone number of the user if he sends a correct passcode. Since I want the data to available even after I power off my module. I need to store it to my sim. I don't want to use an SD card shield or store data to arduino's EEPROM.

I have read Getting the contacts/ storing contacts to SIM card. The only clear reply is reading from the SIM.

Is it possible to add phonebook entry to SIM card?
Do you know a tutorial?


ESP8266 RF Calibration As an off-Topic to my main question, regarding Robodyn's Uno+Wifi - it seems that Wifi does not work ( fail to connect and fail find any network ).
Juraj advised to use External Antenna ( did not work ) and try to make an RF calibration as shown on espressif's site. Which I fail to understand how it is done.
a) Can anyone help with RF Calibration ?
b) Might it be another reason for that ?
Guy
EDIT_1
Just to be clear, a sלetch was uploaded and executed successfully to the ESP8266 module (Basic WiFi connect and network scan ).
Edit_2

You can't do anything else with the RF calibration then to clean the flash area where it is stored. There are two reason for doing it:
First is reason to delete the RF calibration area is, if it was written by different version of Espressif SDK, including changing between AT firmware and Arduino. Then it is almost always wrong. I think they changed the data structure so some values are swapped.
Second reason is if the SDK did the calibration in wrong conditions like without antenna.
There is not much information about RF calibration. The FAQ has "Please erase the RF parameters to trigger overall calibration."
The AT firmware reference has (addresses for 4MB-C1):

blank.bin 0x3FB000 Initializes RF_CAL parameter area.
esp_init_data_default.bin 0x3FC000 Stores default RF parameter values, has to be downloaded into flash at least once. If the RF_CAL parameter area is initialized, this bin has to be downloaded too

The esp8266 Arduino core writes the data of esp_init_data_default.bin as part of the sketch's binary.
EDIT: the SDK does the 'digital calibration' at boot. it takes some microseconds. it is not done at every boot, but after some count of resets. this can be configured in the init section


How to avoid pulling the RX0 pin to reset sketch My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.

My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.

However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.

If the board ever loses power it will have to be reset manually which is not ideal.

Please help me understand Why is this happening? and how can I fix it?

It looks like your RFID readers are very chatty on startup, and the board is going into bootloader mode.

I'd consider either controlling the RFID reader's power using another pin (and a transistor or mosfet if the reader needs more than 20mA), or using a gate ( AND for instance, or a simple switch IC like the 4066) that you can control to disable the RX0 input until program start.

Another thing I've done in the past is multiplexed multiple serial devices to one serial input.  The RFID readers probably have outputs that indicate a card presence, so use those and a multiplexor.  When the card presence is indicated, connect that serial port using the multiplexor, read the card and act accordingly, then wait for another card detect event.


I’m having a tough time trying to program 2 fsr sensors Can anyone help me please?
I’m having a tough time trying to program 2 fsr sensors.                                                                                The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed?                     I have got only one to work by using this code:

/* FSR simple testing sketch.

Connect one end of FSR to power, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground

For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading

  // We'll have a few threshholds, qualitatively determined
  if (fsrReading < 10) {
    Serial.println(" - No pressure");
  } else if (fsrReading < 200) {
    Serial.println(" - Light touch");
  } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze");
  } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze");
  } else {
    Serial.println(" - Big squeeze");
  }
  delay(1000);
}

So what would be the correct code in order to get two sensors to work at the same time?

Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:

int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);
  delay(5);
  fsr2Reading = analogRead(fsr2Pin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading
  Serial.print("\t");
  Serial.print(fsr2Reading);


Merging two 2-d arrays in order of axes Looking to merge two different 2D arrays of different row sizes into one long array:
 int 2dArray1[][] = {
   {1, 2, 3},
   {4, 5, 6}};
 int 2dArray2[][] = {
   {10, 20},
   {30, 40}};
 int 1dLongArray[10];

This is where I need help in order to have the values of 1dLongarray be arranged as follows:
1, 2, 3, 10, 20, 4, 5, 6, 30, 40

How would I achieve this? Thanks in advance.

Consider using loops of length specific to the desired number of transactions.  For example, using this pseudo code create a sketch which follows this pattern:
initialize i to zero
loop 2 times for each row using the variable x
  loop 3 times for each element in first array using the variable y
    long array [i] = first array[x][y]
    increment i
  loop 2 times for each element in a second array using the variable z
    long array [i] = second array[x][z]
    increment i


Arduino mini pro as ISP for Atmega329P-PU serial monitor failing After trying a lot of tutorials and manuals around the web including at least 20 solutions here on StackExchange, I don't know what to try anymore.

My goal is to write a message in the serial monitor window of the Arduino IDE from my ATMEGA328P-PU.

I have written the Arduino bootloader (tried 8 and 16MHz) to the ATMEGA and I use a 'blink' sketch as follows:

void setup()  {
 Serial.begin(9600);
 delay(100);
 pinMode(9, OUTPUT);
}

void loop()
{
 digitalWrite(9, HIGH);
 Serial.print("high");
 delay(1000);
 digitalWrite(9, LOW);
 Serial.print("low");
 delay(1000);
}

The blinking works fine, the timing looks good, not overly fast or slow.

I connect PIN3 (PCINT17, PD1, TXD) directly to the RX on the Arduino (lower red wire) and the serial monitor responds by returning nonsense like ����������.

I have checked the baud rate. I have also tested with all other baud rates in combination with and without 8Mhz and 16MHz.

I have tested the entire setup with another ATMEGA328P-PU and using an entirely other PC. Same results.

It is not possible to upload a sketch while leaving the TXD -> RX connected, so I disconnect this cable when I upload a sketch. I have also tested with only power and TXD -> RX connected.

I have also tried a few types of resistor between the TXD and RX, one of many tutorials recommended this.

This is what I am trying:
http://www.instructables.com/id/Attiny-serial-monitor-using-arduino-walkthrough/

And this is my boards.txt:

##############################################################

atmega328bb.name=ATmega328 (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=16000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

As you can see at image from linked instructables, they've connected TX pin from Tiny to TX pin on UNO through 220R resistor. This is extremely lousy idea as UNO and Tiny are both driving TX pins.

On the other side you've connected TX Output pin from Target CPU into RX Input of the Arduino ISP (pro mini). Arduino ISP returns some error responses from its TXO pin directly into the monitor. And it's at different speed I suppose, as default baud rate is 19200 in Arduino ISP sketch.

Also using internal 8MHz oscillator and: atmega328bb.build.f_cpu=16000000L means you are running at half speed as compiler and everything else expects. All speeds will be at half rate. Delays twice as long and so on.

Anyway, you can disconnect your USB to Serial converter and connect it directly to the target CPU. Or use two of them. Or just upload bootloader and get rid of ISP.


How to acheive fast and reliable communication between NodeMCUs? I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have  tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.

Any ideas how could I can acheive speed of 10Hz via WiFi?

Thanks for any help.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

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


Arduino Mega not receiving data from Neo-6M I am using the trying to get data from the Neo-6M GPS module with an Arduino mega, but, the condition 'While (gpsSerial.available() > 0' is being met. I believe this means the no bytes are being transferred from the module to the serial port but I'm not sure why.
The light on the Neo-6M was blinking which means it getting a lock but not giving out the data.

#include <SoftwareSerial.h>

// Choose two Arduino pins to use for software serial
int RXPin = 19;
int TXPin = 18;

//Default baud of NEO-6M is 9600
int GPSBaud = 9600;

// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup()
{
  // Start the Arduino hardware serial port at 9600 baud
  Serial.begin(9600);

  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
  Serial.write("123");
}

void loop()
{
  // Displays information when new sentence is available.
  while (gpsSerial.available() > 0)
    Serial.write(gpsSerial.read());
}

I had it working on an Uno by connecting to pins 2,3 rather then 18 and 19. I have also tried swapping the 18 and 19 pins over but still noting.

Thanks for the help

EDIT:
I have the RX and TX plugged into the mega at pins 1 and 2, however, it will only print GPS information when the reset button is pressed or held down

Not all pins on the Mega support software serial, have a read below:

https://www.arduino.cc/en/Reference/SoftwareSerial

Pins 18 / 19 are actually hardware serial pins so should not need the use of software serial.

Edit, should have noted to use hardware pins 18 / 19 you would use the constructor Serial1.begin(9600)


How to control Arduino robot wirelessly? I have a few potentiometers connected to analog inputs in an Arduino UNO. These are then processed and then the servo motors start moving to move the bot.
I would like to keep the motors with the uno and send signals from the pots to the uno. I do not want to use a laptop or another arduino as the remote control. However.. XBEE and other related stuff will do... Thanks

Edit- The wireless solution has to cover a long range preferrably 1 mile.(I dont think I will get any that will cover a mile but I'll give it a try.)

Edit 2- I have 8 servos and 4 potentiometer. I don't necessarily need an xbee. However it may be used.

A 13 year old programming an embedded device? Good luck to you, if you conquer it you will be years ahead of your age group.

What you need to understand are the fundamentals; how can you transmit a 'pot' over an XBee? That is an electronics question, start there. You will find that another arduino or laptop is probably required. The XBee itself requires some sort of host adapter, and it might as well be another Arduino since something has to electronically read the 'pots'.

Then you need to develop your own protocol for signals sent between the 2 Arduino (over XBee or on a serial wire , it is the same).  There are many already out there, but they assume you know the basics before you use them (eg firmata). This is the basics.

The fact that your google results showed nothing similar is probably a good indication it can not be done as you had hoped.

update: I like @gerben comment, but even as an advanced person, I would find it challenging.


how to calculate correct resistor value to use with LEDs Potentiometer and other devices? I have been following http://arduino.cc/en/Tutorial/Fade to fade and LED. But I don't know why they are using a 220 Ohm resistor.
According to Ohms law if LED is of 2.2 V and it runs on 0.025Amps and is connected to 5V pin of Arduino then the resistor should be of 120 Ohms but why we are using 120 Ohm resistor ?
One more thing. How can I collect value of resistor to be used with different output and input devices ?

Thanks in advance

If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)

It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.

Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:

http://led.linear1.org/led.wiz

For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.


Can arduino-cli verify sketches? I'm trying to do some simple unit testing with arduino-cli in a .gitlab-ci file like so

variables:
  DOCKER_HOST: tcp://docker:2375

image: "docker:latest"

services:
  - docker:dind

before_script:
  - docker pull "arduino/arduino-cli:latest"
  - arduinocli(){ docker run arduino/arduino-cli:latest "$@";}

search:
  script:
    - arduinocli lib search hi

but instead of arduinocli lib search hi at the end, I want to verify my sketch. Is there a way to do this with arduino-cli?

In Arduino parlance the word "Verify" is used (erroneously) to mean "Compile the code into a binary or HEX file, but don't upload it to the board".

To compile (and thus "verify") the code just pass the compile command to arduino-cli with the board you want to compile for and the sketch you want to compile.


Is it possible to save different values on address 0 and 1 in EEPROM? I want to save different values on address 0 and 1 on eeprom I tried to change it but when I put data on address 0 and also put data on address 1 the address 0 change its value stored into random number and vice versa .. Is it possible to change the value of respective address without affecting others ..

CODE

in the setup
     int eepromSize=EEPROM.length();
      Serial.print("EEPROM found, size=");
      Serial.println(eepromSize);
        // Get the last fade value (as an integer)
      EEPROM.get(0, WATEREQFORN1);
      Serial.print("Last Value N1: ");
      Serial.println(WATEREQFORN1);

      EEPROM.get(1, WATEREQFORN2);
      Serial.print("Last Value N2: ");
      Serial.println(WATEREQFORN2);

The user will input the value that will be save in eeprom i use switch because the user will input like this example .. 100A or 23B

case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        WATEREQFORN1 = val;

            EEPROM.put(0, WATEREQFORN1);
            Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
         WATEREQFORN2 = val;
         EEPROM.put(1, WATEREQFORN2);
         Serial.print("DATA SAVE TO EEPROM");

        break;

The problem is, when I change/write value into address 0 and after that change/write also into address 1 the value on address 0 also change into different random numbers.

EEPROM.put() and EEPROM.get() write or read the object you pass them. An int is 2 bytes so that is what they write or read. It sounds like you intended for the functions to only handle 1 byte. In that case, make the your variable's data type something that is 1 byte, such as int8_t; otherwise allocate 2 bytes of EEPROM to each.

Update:
It works because you had only allocated 1 byte in EEPROM for each variable but you store 2-byte variables. Now you're storing 1-byte variables, which matches your EEPROM allocation.


Why can this color sensor not recognize green? I got this color sensor last week, I've been able to get the sensor to recognize blue and red, but not green. still working on this.
I use the code in the product page.

so anybody have any idea about this issue? Pretty thanks.

Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.

It's the combination of signals on S2 and S3 which determines which colour is being detected:

S2    S3    Colour
----  ----  ------
Low   Low   Red
Low   High  Blue
High  Low   Clear
High  High  Green

If S2 is always low then you can only detect red and blue.

If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the #define S2 line in the code to match.


Shift Register 74HC595 circuit working weirdly I built the circuit from the arduino ShiftOut tutorial, but it is not working as expected. I made a simulation model and that one isn't working either.

The code I used is from the tutorial:

// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Any idea as to what's wrong?

I presume that you are referring to this tutorial, and this code.

The clockPin of Arduino should be connected to pin 11(SH_CP) of 595, dataPin to pin 14(DS), and latchPin to pin 12(ST_CP).

Swap the values of clockPin and latchPin in your code, and you should be good to go.

// SH_CP; 11
const int clockPin = 10;
// DS; 14 (not 15)
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 9;


How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor? const int pingPin = A0;

void loop() {
  long duration, inches, cm;
  pinMode(pingpin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

How to change this code for a 4-pin ultrasonic sensor?

The four pin Echo))) module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.

const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}


I get the following error while using esp32 rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0,
  SPIWP:0xee
  clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
  mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044
  load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac

  [E][camera.c:1049] camera_probe(): Detected camera not supported.
  [E][camera.c:1249] esp_camera_init(): Camera probe failed with error
  0x20004

I tried all the troubleshooting methods found in other forums

Welcome to StackExchange!

I guess you flashed esp32-cam firmware to off-branded ESP32-CAM with different pinout assignments.

To fix this, maybe you should try around with different settings.

Your code should have something similar to this:

// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
//#define CAMERA_MODEL_AI_THINKER

Now try to comment out the third line, and uncomment the last one. Probably it would help.


Plug/socket between thermocouple wires and the amplifier I am building a temperature monitoring system that has 24 thermocouples. Managing all the wires is a hassle, and I'd like to connect all 48 wires to a few plug and socket connectors. Maybe 6 of these lead wire harnesses from eBay (see below).

The point of this would be to allow me to quickly disconnect all the thermocouples from their amplifiers when I need reposition the arduino, and then reconnect them afterwards without tracking each individual cable.

I don't know if this will have a negative impact on the function of the thermocouples. Is it ok to have a 'joint' (i.e., the socket) in the thermocouple cables, or do they need to remain intact from the end all the way to the amplifier?

Alternatively, would having a few inches of regular copper wire inserted between the thermocouple wires and the amplifier be ok? That is, having two copper wires attached to the amplifier, joining 8 of these wires together in a socket, and attaching the plug to the actual thermocouple (alumel/chromel) wires? The thermocouple wires are several feet long.

I do not know the accuracy that you will require in your temperature measurements.

Your idea of using copper wire and connector sockets is reasonably ok as long as you are aware of the following :

Where you make a connection from thermocouple wire to copper, that creates another thermocouple in itself. This isn't a great problem since the temperature of the "undesired" thermocouple is likely to be at room temperature (constant?)

No matter what you do, you always end up with undesired thermocouples (example when you connect your thermocouple directly to your circuit board copper, darn it.)

Thermocouple Selection and use is a page you can go to for more information.  Especially the Cold junction compensation (CJC) section.

EDIT added : You should twist your extention leads together to reduce electrical noise from the environment. Twist each pair, do not twist the bundle all together.


What board to use to send a text message via an arduino board I am fairly new to arduino boards and I was wondering which board to use. I was looking into the edison board because it has built in wifi and bluetooth.

The GSM Shield will suit your needs. This is a shield, meaning that is a board that will go on top of another Arduino board (e.g UNO, Leonardo, ..., choose whatever you'll need).

This is what it will look like:

To send SMS you'll also need a working SIM card and the GSM library to program the shield. On the previously linked page there are some tutorials to follow in order to check the basic functioning of the setup.


Bluetooth serial readings on 0.96'' Adafruit OLED I am trying to display the readings of LDR connected to slave arduino through serial monitor of master arduino paired with bluetooth. I got the readings and it is working fine.

But when I connected OLED to the master arduino so that the LDR readings can be displayed on OLED as well as serial monitor, it is not displaying as expected.

So for simplicity I tried sending the word "hello" from slave to master. The code for slave is :

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  BTSerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  BTSerial.println("hello");
  Serial.println("hello");
  delay(1000);

}

Then I tried displaying the same only on serial monitor of master. The code:

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
char state ;

void setup() {
 pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
 digitalWrite(9, HIGH);
 BTSerial.begin(9600);
 Serial.begin(9600);
 Serial.println("<Arduino is ready>");
}

void loop() {
 if (BTSerial.available()) {
   state = BTSerial.read();
   Serial.write(state);
 }
}

It is showing valid readings in serial monitor with hello being printed after every one second

<Arduino is ready>
hello
hello
hello
hello

But when I modified the code so that I can get the readings on OLED as well as serial monitor;

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
char sensor;
void setup()
{
  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);// initialize with the I2C addr 0x3C (for the 128x32)(initializing the display)
  Serial.begin(9600);
  BTSerial.begin(9600);
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
}

void displayreading()
{
   if (BTSerial.available()) //checks for incoming data
    {

      sensor = BTSerial.read();//reads data from bluetooth serial
      display.clearDisplay();
      display.setTextColor(WHITE);
      display.setCursor(30,0);
      display.setTextSize(1);
      display.print("LDR Reading:");
      display.setCursor(30,10);
      display.setTextSize(2);
      display.print(sensor);
      Serial.write(sensor);
    }
}

void loop()
{
    displayreading();
    display.display();
}

The OLED is showing one letter at a time clearing the screen after every letter rapidly (since I did not add delay which will add up to the problem of data lag). Like :
h , (clear screen)
e (clear screen)
l (clear screen)
l (clear screen)
0 (clear screen)

The serial monitor is showing the readings as:

<Arduino is ready>
hello
hello
hello
hello

But the word hello is printed letter after letter and not in a whole like in the previous master code.There is one second gap after every printing of "hello".

Can somebody please help me with this problem?
Thanks in advance

Instead of BTSerial.read(); there should be

String content = "";
char character;

while(BTSerial.available()) {
     character = BTSerial.read();
     content.concat(character);
 }

and then you send content to lcd by putting

display.write(content);


Getting random values on Arduino Duemilanove 328 I am using Arduino Duemilanove 328,and running the AnalogReadSerial example sketch.

Even when nothing is connected to the Arduino board it still shows a value of about 350 out of 1023. Ideally it should have shown 0 out of 1023 when nothing is connected to Arduino.

So how can I solve this problem?

Why do you think it should show 0 when not connected to anything?

Does the antenna of your radio give a zero signal just because the end isn't connected to anything?  An Arduino's input pin (either analog or digital) is just the same.  If it isn't connected to anything then it just picks up noise - be that radio transmissions, induction from nearby mains wiring, neutrinos from Alpha Centauri...  Basically if it's not connected to anything then there is no way you can possibly know what the value should be since there is no set value.

In order to read 0 on the ADC the ADC has to be connected 0V.  That means connect it to ground.


Is it possible to infer the length of a neopixel string using 1-wire protocol? I'have been looking at the AdaFruit NeoPixels recently and am trying to understand how the addressing scheme works.

All of the examples I've seen explicitly identify the length of the string (number of neopixel units) and are typically set using an array of 24-bit values to control the color of a particular neopixel.

My question is two fold:

How do the neopixels know where they are in a string to allow for addressing?
If the neopixels know where they are in the string, would it not be possible to potentially feed the output of the last neoxpixel back to a microcontroller to determine the number of neopixels in the string?

OP Note (this is my interpretation and may be suspect, but it is more or less my take away)

Thank you for all the answers on this - it has been very enlightening from ALL of the answers. General take away, the NeoPixel is not "directly" addressable in the sense that you can pick pixel "X" of "n" pixels. The string of NeoPixels acts essentially as a gigantic shift-register (as stated in one of the answers) so to "address" a particular pixel you have to update a buffer that represents the state of the entire string and then shift it down the wire. This is why micro-controllers, such as an Arduino, would have limitations on how many NeoPixels it could control. This is also why it is more practical to define the number of pixels in the string and allocate memory to represent that state.

Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain.  Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.

For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.

At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on.  You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided.  And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.


LCD 16x2 Blank Display I am using the following wiring diagram from a tutorial.  I need to follow this configuration because later tutorials build on this example.  I have looked at other solutions, but they follow a different pattern and I am still learning, so don't have the sophistication to adapt.  I've looked at:

Hacktronics
StackExchange

The picture shows Freeduino, but I am using an Arduino Uno (does that make a difference?)

Here is the code I am using:

#include <LiquidCrystal.h>
int rs = 3;
int enable = 4;
int d4 = 5;
int d5 = 6;
int d6 = 7;
int d7 = 8;

int rows = 2;
int cols = 16;
LiquidCrystal lcd (3, 4, 5, 6, 7, 8);

void setup() {
  // put your setup code here, to run once:
  pinMode (rs, OUTPUT);
  pinMode (enable, OUTPUT);
  pinMode (d4, OUTPUT);
  pinMode (d5, OUTPUT);
  pinMode (d6, OUTPUT);
  pinMode (d7, OUTPUT);
  lcd.begin(cols, rows);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  lcd.setCursor(0,0);
  lcd.print("Hello World");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("Goodbye World");
  delay(1000);
}

Unfortunately, I am getting a blank screen (it is lit up, but blank).  So questions:

Is the diagram correct?
Is the code the problem?
What else should I look for?

1) Diagram seems to be fine. However we don't see pin numbering on LCD. Sometimes pins are like:  15 16 1 2 3 4 ... 14 (at least pin 1 is usualy marked).

2) Library should take care of inputs or outputs. So you can remove pinModes for them. Also change variables to constant variables and use them for lcd initialization: LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);

3) Potentiometer in diagram is contrast setting. You have to preset correct value for it. Start with everything is black and find value where this black is almost invisible. If you've something displayed on LCD, it would be even easier to find right position as text just shows up.

Edit: I've just tested it and it's working fine. With the same wiring and contrast pot adjusted to the right position


arduino I2C maximum number of writes per Transmisson Is there any limit on the number of Wire.write() commands consecutively in between the Wire.beginTransmission() command and the Wire.endTransmission() command for the Arduino Wire library?

There are five buffers used by the TWI and Wire library. They are defined as 32 bytes.

In wire.h:

#define BUFFER_LENGTH 32

In Wire.cpp:

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
...
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];

In twi.h:

  #define TWI_BUFFER_LENGTH 32

In twi.c:

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
...
static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
...
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];

So immediately you are using 5 x 32 bytes (160 bytes).

You could increase that to (say) 64 bytes, bearing in mind your 160 byte overhead is now 320 bytes, and you don't have a lot of RAM.

The comments about endTransmission() are correct. After a Wire.beginTransmission() nothing is actually transmitted until the endTransmission() call. This lets you fill up the buffer at your leisure, and then let the library do the writes in a fairly timing-specific way.

Reference

I2C
Wire Library


The reason for signal not going back to LOW I have written a simple Arduino sketch, that shall produce a clock signal.

Here is the code:

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(8,HIGH);
  delayMicroseconds(500);
  digitalWrite(8,LOW);
  delayMicroseconds(500);
}

Namely the pin 8 of Arduino Uno is periodicaly set to HIGH and LOW.

The output that I receive, for three different frequencies, is:

My question is: Why is falling edge not as sharp as rising edge? As can be noted, for high frequencies the signal wouldn't go to LOW after all.

The pin is not configured as OUTPUT.

By default, all of the GPIO pins on pretty much any microcontroller are configured as inputs following reset. This prevents the chip from "fighting" an external device that might be driving any of those pins before the firmware has had a chance to configure the GPIO correctly.

On the MCU used on the Arduino, the output latch controls the state of an internal pullup resistor when the pin is configured as an input. Your code was simply enabling and disabling this resistor. When you set the pin low, it makes the pin open-circuit, and you see a slow decay of voltage through your oscilloscope probe.


Interconnected Arduinos via digital pins and magnets Before i get too far into the design phase of a project i have in mind, is there a way to connect arduinos in a non-master/slave manner to pass a few different combinations of HIGH/LOW (say 5) or 'information' both ways using digital pins? Perhaps some library i don't know about?

Each of these modules should be identical and be able to connect on any face to any other module. I've included a crude image of what I would like to accomplish.

I've already determined that i can solder to these neodymium magnets without loss of magnetic properties by having the little magnets attached to a stronger magnet during the soldering process. Magnet to magnet connection shows only a very tiny resistance.

If it can't be accomplished, i will need to abandon the project and look for some other means to make my project. Thanks in advance!

~zen

While idea looks cool, you need some kind of "locks" because not "any combination" can work.

Rotate second Arduino in bottom row on 180 degree and you will see that GND/5V reversed relatively to first arduino in second row.

You have to account magnet N-S polarities to allow good lock. Probably you can use magnet polarities to achieve proper orientation.


What is "tCAN" in codes of CAN bus? I'm new to Arduino and CAN bus. I'm studying some code examples which contain "tCAN message".
My guess it defines a class for of CAN messages. I did a lot of search but found no information on it except for sample codes. Can anyone help me out.  Thank you!

Some code from the example project:

void activateCAN()
{
 //***PREPARE MESSAGE***//
    tCAN message_act;
    message_act.id = 0x750;
    message_act.header.rtr = 0;
    message_act.header.length = 8;
    message_act.data[0] = 0x00;
    message_act.data[1] = 0x00;
    message_act.data[2] = 0x00;
    message_act.data[3] = 0x00;
    message_act.data[4] = 0x00;
    message_act.data[5] = 0x00;
    message_act.data[6] = 0x00;
    message_act.data[7] = 0x00;

    mcp2515_bit_modify(CANCTRL, (1 << REQOP2) | (1 << REQOP1) | (1 << REQOP0), 0);
    mcp2515_send_message(&message_act); //SEND MESSAGE
}
//******CAN ACTIVATION*****ENDS****//

tCAN will be a struct that defines the structure of the CAN message being sent.  The name tCAN is not a standard and will have been chosen by the author of the library you are using.  At a guess it's using a variant of Hungarian Notation, and the t prefix means type - so it's probably been typedef'd from a struct to a type name.

I am not familiar with CAN, but if there are standard message formats this struct will correspond with one of them.  You can find the actual structure within the header file for your chosen library (or maybe in the example sketch code itself?).


HM-10 send and receive data and checking received value I am wondering what is wrong with my code below. I have 2 issues.

The first issue, I am checking if c equals "hi" and if it does then display said hi. I currently see the output of c when it hits Serial.println(c); but never see the said hi even though Serial.println(c); does say "said hi".

The second issue is that when I start up the Arduino I am sending the AT command using bluetooth.println("AT");, but all it seems to do is display AT on the phone instead of OK as it should.

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(8,9); // RX, TX

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("PC Side Connected");
  bluetooth.begin(9600);
  while (!bluetooth) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop() { // run over and over
  String c;
  if (bluetooth.available()) {
    //What is sent back from the BT module
    c = bluetooth.readStringUntil('\n');
    delay(10);
    Serial.println(c);
    if (c.equals('hi')) {
      Serial.println("said hi");
    }
  }
  if (Serial.available()) {
    //Send back data to Bluetooth module
    bluetooth.write(Serial.read());
  }
}

The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is not how you compare:

  if (c.equals('hi')) {

Single quotes indicate a single (or multi-byte) character.  A character string (lower-case) is enclosed by double quotes:

  if (c == "hi") {

But it's better to avoid the String class (more info here).

To eliminate the String class, use char arrays instead (aka "C strings") and accumulate characters until the newline is received.  There are many, many C string functions for manipulating and searching.  In this specific case, you would use strcmp or strstr for comparison:

#include <AltSoftSerial.h>

AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

char btResponse[ 20 ];
uint8_t count;
const uint8_t BT_MAX = sizeof(btResponse);

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

  Serial.println("PC Side Connected");
  bluetooth.begin(9600);

  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop()
{
  if (bluetooth.available()) {
    // Read what is sent back from the BT module
    char c = bluetooth.read();

    if (c == '\n') {
      btResponse[ count ] = '\0'; // NUL-terminate the character array

      // Use C string functions to parse the response

      if (strcmp( btResponse, "hi" ) == 0) {
        Serial.println("only said hi");

      } else if (strstr( btResponse, "hi" ) != nullptr) {
        Serial.println("said hi, among other things...");

      }

      // And if there is a comma in there somewhere, display all comma-separated fields
      if (strchr( btResponse, ',' ) != nullptr) {
        uint8_t fieldNumber = 0;

        char *field = strtok( btResponse, "," );
        while (field != nullptr) {

          Serial.print( "Field " );
          Serial.print( fieldNumber );
          Serial.print( " = " );
          Serial.println( field );

          // Some fields might be numbers.  Parse them into integers.
          if ( isdigit( field[0] ) ) {
            int value = atoi( field );
            Serial.print( "  value = " );
            Serial.println( value );
          }

          // get next field
          field = strtok( nullptr, "," );
          fieldNumber++;
        }
      }

      // Reset the counter to receive another response
      count = 0;

    } else if (c >= ' ') {
      // Accumulate another non-control char, if there's room
      if (count < BT_MAX-1) {
        btResponse[ count++ ] = c;
      }
    }
  }

  if (Serial.available()) {
    // Send data to Bluetooth module
    bluetooth.write( Serial.read() );
  }
}

Notice that it shows how to use strtok to break the response string into individual fields, if a comma character is somewhere in the line.  For example, entering this:

hi,123,456

... produces this output:

said hi, among other things...
Field 0 = hi
Field 1 = 123
  value = 123
Field 2 = 456
  value = 456

It also uses AltSoftSerial for the BT connection.  SoftwareSerial is very inefficient, and it cannot send and receive at the same time.  It will lose received data while it is transmitting to the BT.  This can also interfere with other parts of your sketch or other libraries.

This answer has a good summary of the alternatives and how to select one.  Since you are already using pins 8 & 9, it would be easy to switch to the AltSoftSerial library.  All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.


Make Arduino Executable File On a Pi, to execute a C++ code, you'll need a Makefile.

Is there an equivalent with the Arduino? Where I have some valid C++ files to upload without the IDE's help, but instead with an executable?

Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file.  This is a text file describing the data to load into the flash memory.

You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).

A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the make program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.

There are many Arduino Makefile projects out there that do it all for you.