Read a String from serial to debug the AT commands sent to my GPS shield I want to extract an AT command's response (via serial port) to find out if the GPS shield is working as it should be.

I used:

  if(Serial.available()>1){
     String response = Serial.read();
     Serial.println(response);
  }

Normally the response to AT is OK but it keeps telling me that it cannot convert int to String .... can someone help?

if (Serial.available() > 1) is wrong. Always use if (Serial.available()) in such cases. Also it seems you are communicating with the GPS shield using Hardware Serial. However, the Arduino also uses the same serial port for communicating with the PC via the USB connection. So what you have basically is:

Arduino TX, PC RX and GPS RX are all connected
Arduino RX, PC TX and GPS TX are all connected

So anything the Arduino writes to the Serial port using Serial.println() is received by both the PC and the GPS shield. And the other hand, responses from the GPS shield and commands sent from the serial monitor all arrive at the same Arduino pin. So when you use Serial.read(), assuming you used the serial monitor to send the command, you will end up receiving your own command (like some sort of echo), and according to your program, you use Serial.println() to send the command again which is received by both PC and GPS shield, with the GPS shield responding to the same command again. All undesirable.

TLDR; use SoftwareSerial instead for the GPS shield. Connect the GPS shield TX to pin 2 and its RX to pin 3 and use this code:

    #include <SoftwareSerial.h>

    SoftwareSerial gps(2,3);   // pin 2 = RX, pin 3 = TX

    void setup(){
        Serial.begin(57600);
        gps.begin(57600);    // change to your baud rate, if not auto-baud
    }

    void loop(){
        while (Serial.available())     //used to send commands from PC
            gps.write(Serial.read());   // to gps
        while (gps.available())        // used to read responses from gps
            Serial.write(gps.read());  // to PC
    }

So the Arduino forwards everything it receives from the PC monitor (commands) to the shield and sends everything it receives from the shield (responses) to the PC to be displayed in the serial monitor.


How to increment and decrement an output voltage by using two buttons? I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below.

The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0.

I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as attachinterrupt() and Debounce() functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions?

I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic.

simulate this circuit – Schematic created using CircuitLab

Here is my code I have made. I'm using an LED to test the Vout aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?

int PWMPin = 6; // output pin supporting PWM
int buttonApin = 9; // buttonA to pin 9 PWM
int buttonBpin = 10; // buttonB to pin 10 PWM
float value = 0; // read the value at 0
int fadeValue = value;

void setup()
{
  Serial.begin(9600); //initialize serial communication at 9600 baud
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(PWMPin, OUTPUT);
}
void loop()
{
  {
    int port = analogRead(0);
    port = map(port, 0, 10, 0, 255);
    analogWrite(6, port);
  }

  {
  if (digitalRead(buttonApin) == LOW, fadeValue)
  {
  // fade from min to max in increments of 25.5 points: basically (0.5 volts)
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)

    digitalWrite(PWMPin, fadeValue);

    // sets the value (range from 0 to 255):
   Serial.println(PWMPin);
   analogWrite(PWMPin, fadeValue);
  }
  }

  {
    if (digitalRead(buttonBpin) == LOW, fadeValue)
  {
  // fade from max to min in increments of 25.5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)

    digitalWrite(PWMPin, fadeValue);

  // sets the value (range from 0 to 255): basically (0.5 volts)
  analogWrite(PWMPin, fadeValue);
  }
  }
}

If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop.
The Bounce2 library does basically the same.

Also, about the PWM, why not an R-2R?

10V/0.5V + 1 => 21 steps < 32 => 5 bits => 6 resistors.

But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.


Does analogueRead() change the way a number is represented etc? Explanatory Comment: The ADC conversion result is a 10 bit number and is placed in two 8 bit registers: ADCH & ADCL. AnalogueRead() reads the output of the ADC. This, I believe is an unsigned number. But, generally taken as only a positive number.

I'm interested in what changes, if any, take place to the number (in it's representation, interpretation, or construction or whatever) when analogueRead() reads the number and presumably makes something of it, or sends it or stores it somewhere.

There is no change in representation. analogRead() reads two I/O
registers, ADCL and ADCH, which on the Uno are memory-mapped to
addresses 0x0078 and 0x0079 respectively. It returns the result in a
register pair, r24 and r25, which per the AVR C calling
conventions is the
standard way of returning a 16-bit number. Thus, r24 holds the value
read from ADCL, and r25 the value read from ADCH. That's it. No
conversion whatsoever.

There is a change in interpretation... of sorts. The function is
declared as returning an int, which on the AVR is a 16-bit signed
integer, whereas it could be argued that the I/O registers contain an
unsigned number. However, since the sign bit will always be zero, the
signed/unsigned distinction is moot: either way the result will be
interpreted as a number between 0 and 1023.

Edit: As a clarification: the ADC register (which is another
name for the ADCL/ADCH register pair) is a 16-bit I/O register. At
the end of a conversion, it holds the 10-bit result right-adjusted into
this 16-bit space, zero-padded on the left, as follows:

-------- ADCH --------- --------- ADCL --------
0  0  0  0  0  0  r9 r8 r7 r6 r5 r4 r3 r2 r1 r0
----------------- ADC (16 bits) ---------------

where the bits r9..r0 represent the 10-bit conversion result. Since the
MSB is zero, it is irrelevant whether you interpret it as a sign bit or
as a regular unsigned bit.

Just for completeness, it could be noted that it is possible (though not
through the Arduino core library) to configure the ADC to left-adjust
the result, as follows:

-------- ADCH --------- --------- ADCL --------
r9 r8 r7 r6 r5 r4 r3 r2 r1 r0 0  0  0  0  0  0
----------------- ADC (16 bits) ---------------

In this case, the MSB could be one, at it would obviously be incorrect
to interpret it as a sign bit.

As a side note, the avr-libc defines ADC as
(*(volatile uint16_t *)(0x78)), which is unsigned. And it makes sense
considering that, unlike the users of Arduino core, the users of
avr-libc are supposed to know they have the choice to get a
left-adjusted result.


Read BLE Characteristic Value in Arduino Uno I am trying to build a Smart Led project using Arduino Uno, RGB Led, HM-10 BLE module, and Android device.

I am able to connect HM-10 with my android device and read and write characteristic values using Android BlueDroid stack.

But for this project to work I need to check changes in characteristic value in Arduino and process color value and produce output to light up LED.

I thought I could possibly use AT commands (like AT+Name? AT+POWE? AT+CHAR?) parse their result , but I couldn't find any AT command to read characteristic value. If anyone know such working AT commands for HM-10, please answer?

Also, I looked into CurieBLE library from Intel for Arduino. I think the library is to work on an Arduino board which has BLE hardware as a built-in feature. If that's not the case, please help me how can I communicate Arduino and HM-10 using CurieBLE or any other available library?

I was able to communicate Arduino UNO and HM-10. Whenever one writes a characteristic on BLE using Android application, the exact bytes are transmitted to Tx/Rx channel to Arduino and can be read using SoftwareSerial Arduino library.

CurieBLE library works on Genuino/Arduino 101 board which has Intel Curie Module.


What are the components of a Xively HTTP PUT request to send to my SIM800 GPRS module? I have an Elecrow GPRS shield which I want to use to post temperatures from 3 x DS18B20s to Xively. The example code is a mystery to me. You can find in full at this link: http://www.elecrow.com/wiki/index.php?title=GPRS/GSM_Shield_v1.0#A_Simple_Source_Code_Example

The relevant function is here:

///send2Pachube()///
///this function is to send the sensor data to the pachube, you can see the new value in the pachube after execute this function///
void Send2Pachube()
{
mySerial.println("AT+CGATT?");
delay(100);

ShowSerialData();

mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);

ShowSerialData();

mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);

ShowSerialData();

mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSPRT=0");
delay(3000);

ShowSerialData();

mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();
String humidity = "1031";//these 4 line code are imitate the real sensor data, because the demo did't add other sensor, so using 4 string variable to replace.
String moisture = "1242";//you can replace these four variable to the real sensor data in your project
String temperature = "30";//
String barometer = "60.56";//
mySerial.print("\"method\": \"put\",\"resource\": \"/feeds/43634/\",\"params\"");//here is the feed you apply from pachube
delay(500);
ShowSerialData();
mySerial.print(": ,\"headers\": \"X-PachubeApiKey\":");//in here, you should replace your pachubeapikey
delay(500);
ShowSerialData();
mySerial.print(" \"_cXwr5LE8qW4a296O-cDwOUvfddFer5pGmaRigPsiO0");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("jEB9OjK-W6vej56j9ItaSlIac-hgbQjxExuveD95yc8BttXc");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("Z7_seZqLVjeCOmNbEXUva45t6FL8AxOcuNSsQS\",\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" \"version\": \"1.0.0\",\"datastreams\": ");
delay(500);
ShowSerialData();
mySerial.println("[\"id\": \"01\",\"current_value\": \"" + barometer + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"02\",\"current_value\": \"" + humidity + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"03\",\"current_value\": \"" + moisture + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"04\",\"current_value\": \"" + temperature + "\"],\"token\": \"lee\"");

delay(500);
ShowSerialData();

mySerial.println((char)26);//sending
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

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

Note that although this is called "send2Pachube" it uses the Cosm API, which still works.
The section following the line

mySerial.println("AT+CIPSEND");

is where the HTTP gets formulated. I've assembled the string in the example code and it looks odd. The API key goes on about four times longer than it should. I'm not sure what all those colons are doing in there, are they a String operator? Can anyone give me an example of an HTTP PUT request for Cosm or Xively that illustrates how this string should be assembled?
Thanks

I've got a working solution to this issue. Here's the values you can edit and the function:

String FEED = "YOUR_FEED";
String KEY = "YOUR_API_KEY";
String DATASTREAM1 = "YOUR_DATASTREAM1_NAME";
Int VALUE1 = YOUR_VALUE1;
String DATASTREAM2 = "YOUR_DATASTREAM2_NAME";
Int VALUE2 = YOUR_VALUE2;

void send2Cosm()
{
mySerial.println("AT+CGATT?");
delay(100);
ShowSerialData();
mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);
ShowSerialData();
mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);
ShowSerialData();
mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSPRT=0");
delay(3000);
ShowSerialData();
mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();

mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/" + FEED + "/\",\"params\"");
delay(500);
ShowSerialData();
mySerial.print(": {},\"headers\": {\"X-ApiKey\":");
delay(500);
ShowSerialData();
mySerial.print("\"" + KEY + "\"},\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\":");
delay(500);
ShowSerialData();
mySerial.print("[{\"id\": \"" + DATASTREAM1 + "\",\"current_value\": \"");
mySerial.print(VALUE1);
delay(500);
ShowSerialData();
mySerial.print("\"},{\"id\": \"" + DATASTREAM2 + "\",\"current_value\": \"");
mySerial.print(VALUE2);
delay(500);
ShowSerialData();
mySerial.println("\"}]}}");
delay(500);
ShowSerialData();

mySerial.println((char)26); //sending = ctrl+z
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}

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

To answer part of my question: no, the colons aren't a String operator, they're part of the HTML. Here's an example of the formed URL that gets sent:

{"method": "put","resource": "/feeds/YOUR_FEED/","params": {},"headers": {"X-ApiKey":"YOUR_API"},"body": {"version": "1.0.0","datastreams":[{"id": "DATASTREAM1","current_value": "VALUE1"},{"id": "DATASTREAM2","current_value": "VALUE2"}]}}

This code updates my feed but after several hours the updates stop. I'm still troubleshooting this new problem so I'm not 100% sure that this code is good. I will post back if the problem's in here.


Arduino Nano Atmega328P doesn't work on Macbook I've bought and Arduino Nano compatible on eBay:

But by the time I connect it to my Macbook Pro (OS X El Capitan 10.11.2) doesn't appear under "Tools -> Port" in Arduino IDE:

I've followed some instructions by other posts here in StackOverflow:

Arduino Nano no serial port for MacBook Air 2013
Arduino Nano with Mac OS Yosemite 10.10

But none of them worked :(

If someone could help me out with this issue I'll be grateful.

Thanks.

I was be able to solve the issue.

By looking for the serial chip my board has: CH340G I found this blog post:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

So I downloaded the signed driver for my chip and now it works :D

Driver: http://kiguino.moos.io/downloads/CH34x_Install.zip


List of Arduino board preprocessor #defines When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.

After a lot of hunting and some good fortune I found that the format of this definition is:

#define ARDUINO_<PROCESSOR-DESCRIPTOR>_<BOARDNAME>

Some are easy to guess (ARDUINO_AVR_UNO, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.

Question 1: Is there a list in existence of the possible definitions?

Question 2: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between BoardX-5V and BoardX-3.3V, and how is this distinction defined?

The list of board symbols can be generated by this shell command:

$ grep board= boards.txt | cut -f2 -d= | sort -u
AVR_ADK
AVR_BT
AVR_DUEMILANOVE
AVR_ESPLORA
AVR_ETHERNET
AVR_FIO
AVR_GEMMA
AVR_LEONARDO
AVR_LILYPAD
AVR_LILYPAD_USB
AVR_MEGA
AVR_MEGA2560
AVR_MICRO
AVR_MINI
AVR_NANO
AVR_NG
AVR_PRO
AVR_ROBOT_CONTROL
AVR_ROBOT_MOTOR
AVR_UNO
AVR_YUN

The boards are defined by the "build.board" property in the boards.txt file.

mini.build.board=AVR_MINI

This property is used by the build recipe together with ARDUINO_-prefix.

-DARDUINO_{build.board}

Cheers!


Arduino Nano (clone) not recognized Asking here cause I ran out of options in searching. My Arduino Nano clone isn't recognized by my computer anymore. It was, until I plugged into a Windows machine, that did not recognize it... and now even my Linux Mint distro doesn't detect the Nano at all. Here's the thing, though: the green power LED still lights up and, if I connect my DC motor to it like I used to before, the LED turns off and the motor is powered only a little bit, with less speed than if it were powered by a 1.5V battery.

My voltimeter reads a 2.18V out of the 5V pin.

Here's all I did: uploaded a sketch to power a 5v motor, it worked, unplugged the Arduino, took it home to my Windows machine on the casing I got it from my school, plugged it there, then it didn't detect anything. Go back to the lab today, plug it in, doesn't detect it there either.

From there, I've replaced USB cables, tried different USB ports, checked with lsusb and dmesg, tried finding it using the FTDI tool (the chip underneath is FTDI), then tried powering it from a phone charger, but the voltage readings at the 5v pin still are around 2.18V with that. Nothing seems to give this little thing an output greater than 2.18V.
The only thing I haven't tested is powering it through the VIN pin.

I came across other questions of similar problems but nothing that seems quite like mine... since they all either are able to detect the device but it is displayed as an unknown device or can't recognize the device at all but their power LED does not turn on.

Any ideas on what is going on?

It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.


How to add calibration to a humidity contoller using UNO and DHT22 sensor? I am using a setup that helps controlling humidity in an enclosure used to store a humidity sensitive product.   My original posting is here.

I'm using a NANO and a DHT22 temperature/humidity sensor to acquire information on the actual condition in the enclosure; I am also using a 75% RH calibration kit to check the accuracy oh the humidity reading by the UNO and I found the value 9 percentage points higher than the kit's calibration value.   Right now, until I find a solution to calibrate the unit, I have set my setpoint 9 points higher to compensate for the error.
Any ideas on how to tackle this issue would be highly appreciated.

At the moment I can read the DHT sensor and show the humidity value on the LCD like this:

[...]
  int chk = DHT.read22(DHT22_PIN);
  lastcheck = millis();

  lcd.setCursor(0, 0);
  lcd.print("Humidity: ");
  lcd.setCursor(13, 0);
  lcd.print(DHT.humidity);
[...]

@Thomas_Weller,
I'm running tests with your calibration routine and other code changes; I'm using your arbitrary values for testing purposes only; the compensation algorithm works, as sampled below, however the LCD output is the actual DHT22 reading, not compensated.
I am testing with a different sensor, whose output is 9% below the actual RH value.
Here's a sample of the serial output:

DHT value: 58
Compensated to: 55
DHT value: 59
Compensated to: 56
DHT value: 60
Compensated to: 57
DHT value: 61
Compensated to: 58
DHT value: 62
Compensated to: 59
DHT value: 63
Compensated to: 60
DHT value: 64
Compensated to: 60

setpoint = 72
DHT read = 66.80%
displ + backlights off
humidifier ON, fan OFF
setpoint = 72
displ + backlights off
humidifier ON, fan OFF
setpoint = 72
displ + backlights off
humidifier ON, fan OFF
setpoint = 72
DHT read = 66.80%
displ + backlights off
humidifier ON, fan OFF
setpoint = 72
displ + backlights off
humidifier ON, fan OFF
setpoint = 72
displ + backlights off
humidifier ON, fan OFF

To get better calibration, you need more calibration points. In the example below, I use 8 measurement points.

Given 8 humidity calibration bags for 20, 30, 40, 50, 60, 70, 75 and 80%.

int calvalues[] = {20, 30, 40, 50, 60, 70, 75, 80};

You would take several samples with the DHT sensor and build a table using the averages:

int dhtvalues[] = {15, 28, 39, 51, 63, 75, 84, 89};

As you can see, the DHT is below the real values in the lower range and above the real values in the upper range. But it could also be the opposite way.

You can then write this function:

#define COMPENSATION_POINTS 8

int compensate(int sensor_value)
{
  for(int index=1; index<COMPENSATION_POINTS; index++)
  {
    if (dhtvalues[index]>sensor_value)
    {
      int dhtLow = dhtvalues[index-1];
      int dhtHigh = dhtvalues[index];
      int calLow = calvalues[index-1];
      int calHigh = calvalues[index];

      return map(sensor_value, dhtLow, dhtHigh, calLow, calHigh);
    }
  }
}

which does linear interpolation for all the values that fall somewhere in between.

Here's some test code, which goes through the values in the expected range.

void setup() {
  Serial.begin(9600);
  for(int hum=15; hum<=89; hum++)
  {
    Serial.print("DHT value: ");
    Serial.println(hum);
    Serial.print("Compensated to: ");
    Serial.println(compensate(hum));
  }
}

void loop() {
  delay(1000);
}

Output:

DHT value: 15
Compensated to: 20
DHT value: 16
Compensated to: 20
DHT value: 17
Compensated to: 21
DHT value: 18
Compensated to: 22
...
DHT value: 87
Compensated to: 78
DHT value: 88
Compensated to: 79
DHT value: 89
Compensated to: 79

Applied to your case:

[...]
  int chk = DHT.read22(DHT22_PIN);
  lastcheck = millis();

  lcd.setCursor(0, 0);
  lcd.print("Humidity: ");
  lcd.setCursor(13, 0);
  int compensated = compensate(DHT.humidity);   // <- new line
  lcd.print(compensated);                       // <- changed line
[...]


SPI: test by connecting MOSI to MISO Is it possible to test a SPI connection by wiring the MISO directly to the MOSI pin?  I'm working on a low-level SPI implementation, and I want to check that the library is basically working.  It would be nice to be able to test the connection itself without additional hardware.

Usually the SPI Master clocks data out while the Slave clocks data back in. So if you were sending and receiving 8 bits per transaction you can clock out 8 bits and at the same time clock in 8 bits for a total of 8 clocks.  This is described in this Wikipedia paragraph. That said, often the first 8 clocks are used to transmit a command and an additional 8 clocks are used to retrieve the result.

If you looped MOSI to MISO you would clock in what you clocked out. You would complete the entire transaction in 8 clocks. At a low level I'm thinking this does not matter. But at a higher level the software would have to be re-written to accommodate this weirdness.


Using SPI and 2 shift registers WITHOUT libraries Arduino Mega 2560 board and SN74HC595 shift register(s). I'm working on a school assignment and having issues getting the shift register(s) working without using Arduino libraries.

I know with the libraries you can use functions such as digitalWrite(....); and shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);.

For my project, I've set up my individual pins as inputs and outputs, but I am having trouble converting the library code into basic code.

IE:

digitalWrite(latchPin, LOW);

can be rewritten as

DDRB &= ~(1 << DDB1);

where latchPin is the SCK pin.

At this stage in the project, we're just trying to get 8 LEDs lit up using 1 shift register, then 16 using 2 shift registers. Any help in understanding what I need to do or direction in which to look would be appreciated.

Thank you,

Nic

Edit:

This is what I have converted from the void setup from https://www.arduino.cc/en/Tutorial/ShftOut12 :

void setup() {
  //Clear the shift registers prev data, Need a low input to reset registers
  //PORTL0 to first SReg SRCLR, PORTL2 to second SReg SRCLR
  //* See data sheet for sn74hc595 shift registers
  DDRL &= ~((1 << PORTL0) | (1 << PORTL2)); //Pg 100 - 21.2.3
  //Use port L0/L2 for SRCLR pin on SReg
  PORTL |= (1 << PORTL0) | (1 << PORTL2); //Pg 100 - 21.2.3

  //Set OE (Enable) to 0 until after last bit is sent
  DDRL &= ~(1 << PORTL4); //Pg 100 - 21.2.3
  //TODO SPI DELAY HERE USING SPDR pg 199

  //Enable SCK as output to drive RCLK and SRCLK on SR
  DDRB &= ~(1 << DDB1); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB1); //Pg 96 - 13.4.5

  //Enable MOSI as output to drive SER Input on SR
  DDRB &= ~(1 << DDB0); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB0); //Pg 96 - 13.4.5

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

My strategy: Write the sketch using the standard Arduino library. The goal is have the LED lit up, as you need.

Then, change all standard function calls in your sketch (like digitalWrite) with your own (called it digitalWrite2).

Now implement digitalWrite2 using register manipulation.

Pros:

Divide and conquer. You know have two independent smaller problems (LED and registers).
When is time to implement digitalWrite2 you can learn from your classmate how to do that. I bet that they will start with the hard part (register manipulation).
It makes for a easier debuging. You can compare your own implementation against the standard implementation just by deleting/adding a single "2" in the call.

Of course, taking a look at the Arduino source code will made things trivial :-)
Is that cheating? No, we learn from others, we learn reading other people's code.

Edit: Step by Step Example

Let use Blink to show how to do it:

Original

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

For the new version I will replace pinMode and digitalWrite for the my own  implementation them. How?

Go to the directory where you put your Arduino binaries, which include the source code. There is a subdirectory with the sources (mine is ~/bin/arduino-1.8.3/hardware/arduino/avr/cores/arduino).

There is a file (wiring_digital.c) where I found the source code for pinMode and digitalWrite. Without any shame, I copy-paste and rename.

Note: the original includes a call to turnOffPWM, which I simply comment out, because we will not use it here and I want to cut it short.

That's all.

New version

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode2(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite2(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite2(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

void pinMode2(uint8_t pin, uint8_t mode)
{
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg, *out;

  if (port == NOT_A_PIN) return;

  // JWS: can I let the optimizer do this?
  reg = portModeRegister(port);
  out = portOutputRegister(port);

  if (mode == INPUT) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out &= ~bit;
    SREG = oldSREG;
  } else if (mode == INPUT_PULLUP) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out |= bit;
    SREG = oldSREG;
  } else {
    uint8_t oldSREG = SREG;
                cli();
    *reg |= bit;
    SREG = oldSREG;
  }
}

void digitalWrite2(uint8_t pin, uint8_t val)
{
  uint8_t timer = digitalPinToTimer(pin);
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *out;

  if (port == NOT_A_PIN) return;

  // If the pin that support PWM output, we need to turn it off
  // before doing a digital write.
  // if (timer != NOT_ON_TIMER) turnOffPWM(timer); By Look Alterno

  out = portOutputRegister(port);

  uint8_t oldSREG = SREG;
  cli();

  if (val == LOW) {
    *out &= ~bit;
  } else {
    *out |= bit;
  }

  SREG = oldSREG;
}


Driving two stepper motors using one stepper motor driver Using an Arduino Mega, I currently control two stepper motors that never operate at the same time and never will. I am using two EasyDriver stepper control boards with two separate power sources. I was wondering if I could go down to just one stepper control board, one power source but somehow switch the 4 input wires from one motor to another when I need to turn a specific motor. Is there a switch I can control with Arduino where I can plug in 8 wires and say "ok, use the 4 left most wires" or "switch to the right most 4 wires". Does that exist or is that more complicated than what I currently have?

If we call the motor leads A1, A2, B1, B2 on each motor and control, you could tie the two motor A1's to A1 on the control, and motor B1's to B1 on control.  Then wire a DPDT relay as below.  (Coil not shown.)  Note, DPDT relays are about $4 on ebay, with labels like “DR21A01 DC 5V DPDT Relay Module Polarity reversal switch Board for Arduino UNO”.

simulate this circuit – Schematic created using CircuitLab

Since you have equipment in place and working, it might not be worthwhile to change your setup.  However, even without adding a relay, you probably can power both motor controls and motors with a single power supply, ie could use one instead of two power supplies.  The current draw when a stepper motor is idle is a small fraction (eg 10-20%) of the high current drawn when the motor steps.  If you don't have power attached to a stepper motor, there is only its cogging resistance to keep it from turning; it does not take a large torque to turn an unpowered stepper motor.  If that's a concern, the DPDT relay approach might be unsuitable.


How can I alter my program to read PWM signals from Arduino Mega? I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).

This is my code that isn't working.

unsigned long timer[3];
byte last_channel[2];
int throttle;
int aileron;

void setup() {
pinMode(8, OUTPUT);//Right motor fowards
pinMode(9, OUTPUT);//Right motor reverse
pinMode(10, OUTPUT);//left motor fowards
pinMode(11, OUTPUT);//left motor reverse

PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

PCMSK0 |= (1 << PCINT0); // This tells the mask register
which pins will cause an intterupt (Pin 2)

PCMSK0 |= (1 << PCINT1); // (Pin 3)

Serial.begin(9600); //Sets the data rate in bits per second
}

void loop() {

}
ISR(PCINT0_vect) {

timer[0] = micros(); // registers intterupt time

//Throttle_Channel----------------------------------------------------------

if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
changed from low to high

last_channel[0] = 1;

timer[1] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000001)){

last_channel[0] = 0;

throttle = timer[0] - timer[1]; //calculates the change in time and sets to

input[0]
//--------------------------------------------------------------------------
}
//Aileron_Channel-----------------------------------------------------------

if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

changed from low to high

last_channel[1] = 1;

timer[2] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

changed from high to low

last_channel[1] = 0;

aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

input[0]
//--------------------------------------------------------------------------
}

//Calculations to put output in correct form--------------------------------
int throttle_pwm = (throttle - 1500) / 1000;

int aileron_pwm = (aileron - 1500) / 1000;

int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

int lm = v + (w/2) * 255;

int rm = v - (w/2) * 255;
//--------------------------------------------------------------------------

if (lm > 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm > 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm <= 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,0);

analogWrite(11,abs(lm));

}

else if (lm <= 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,0);

analogWrite(11,abs(lm));

//--------------------------------------------------------------------------
}
}

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.

It looks like the code in the ISR is slow and it may compute incorrect results.

It is slow because of using floating point arithmetic in throttle_pwm and aileron_pwm calculations.  It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed.  This will delay trailing edge processing, and mis-measurement of pulse lengths.

The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase.  You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in analogWrite() statements there.

Note, in 16-bit int arithmetic, the value of expression (t-1500)/1000 is 0 for 500 < t < 2500.   Because throttle and aileron are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your  throttle_pwm and aileron_pwm will be zero.  That means you can replace the following code,

int throttle_pwm = (throttle - 1500) / 1000;
int aileron_pwm = (aileron - 1500) / 1000;
int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
int lm = v + (w/2) * 255;
int rm = v - (w/2) * 255;

with this code:

int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

which should save you several milliseconds of computation!  Also, having lm and rm as constant zeroes means that you don't need all those lengthy and laborious if and else blocks.   You can replace those 24 lines of stuff with just the following:

analogWrite(8,0);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(11,0);

Slightly more seriously, it looks like you intended for your arithmetic like (throttle - 1500) / 1000, etc. to determine whether to raise or lower the throttle, etc.   Instead of doing that time-consuming division, just say:

int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

Instead of all those 24 lines of stuff, just say:

analogWrite(8,  (rm>0) * Level);
analogWrite(9,  (rm<=0)* Level);
analogWrite(10, (lm>0) * Level);
analogWrite(11, (lm<=0)* Level);

where Level is some level you want to set the control to.  Note, an expression like (rm>0) has a value 1 when it is true and and 0 when it is false.  So when rm>0, you have, in effect, analogWrite(8,Level); and analogWrite(9,0);.

If instead you end up with a calculation where lm and rm are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:

analogWrite(8,   (rm>0) * rm);
analogWrite(9,  -(rm<=0)* rm);
analogWrite(10,  (lm>0) * lm);
analogWrite(11, -(lm<=0)* lm);

or could say:

analogWrite(8,  rm>0  ?  rm : 0);
analogWrite(9,  rm<=0 ? -rm : 0);
analogWrite(10, lm>0  ?  lm : 0);
analogWrite(11, lm<=0 ? -lm : 0);

Also see my answer to the question  Read RC receiver channels using Interrupt instead of PulseIn and see my answer to the question  Arduino read PWM duty cycle value with input (analog / digital).


Moving average sticks in fictitious zeroes for the first readings. This delays accuracy My 9/10 Moving Average inserts zeroes for the first 9 readings. For example, if the first voltage reading is 100, the first moving average given is 10. That is the average of 9 zeroes and one 100. How can I get the moving average to only use actual readings from the adc? Or how can I get the moving average to wait until at least 10 readings are finished before starting its calculations?

#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262; // class

float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  volatile int i, data;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) {
    // monitor Data   ready(DRDY pin)
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // read 6 bytes conversion register
    Responsebyte = true;
  }
  if(Responsebyte == true) {
    for(i = 0; i <5; i++) {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }
  if(SPI_RX_Buff_Count >= 5) {
    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];
    // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];
    uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|        ads1262_rx_Data[3]);
    //get the raw 32-bit adc count out by shifting
    sads1262Count = (signed long) (uads1262Count);
    // get signed value
    resolution = (double)((double)VREF/pow(2,31));
    //resolution=  Vref/(2^n-1) , Vref=2.5, n=no of bits
    volt_V = (resolution)*(float)sads1262Count;
    // voltage = resolution * adc count
    MovingAverage = (9*MovingAverage + volt_V)/10;
    Serial.print(MovingAverage,8);
  }
  SPI_RX_Buff_Count = 0;
}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

There are essentially two ways of initializing a low pass filter. The
first is to let it initialize itself “naturally” by feeding it data
until it reaches its steady state. This is the approach of jwpat7's
answer, and it works really well with FIR filters, like a plain
moving average.

Your exponentially-weighted moving average, however, is an
IIR filter. Given constant input, it converges asymptotically to its
steady state. After feeding it 10 values, it will only have reached 65%
of the steady state (exactly 1 − 0.910), thus you
may want to feed it significantly more than 10 points. E.g., you should
give it 22 points if you want it to be 90% initialized.

The other approach is to provision a specific initialization procedure
that sets the internal state of the filter to what it would have been
had it processed an infinite stream of constant values. This is actually
really easy to do with this particular filter, as we only have to set
the output equal to its first input. Here is the self-initializing
filter written as a function (this keeps the code cleaner):

static float movingAverage(float x)
{
  static bool initialized;
  static float output;

  // Initialize the filter as if this input had been on forever.
  if (!initialized) {
    output = x;
    initialized = true;
  }

  output += 0.1 * (x - output);
  return output;
}

You loose the benefit of the averaging on the very first data points,
but in return you have a simple to use self-initializing filter.

Unrelated to your question, I looked at your code and fond so many
confusing and useless statements that I felt compelled to remove all
that cruft. I did not test the simplified version though:

#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

static float movingAverage(float x) { ... }  // as before

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                      | (uint32_t) buffer[2] << 16
                      | (uint32_t) buffer[3] <<  8
                      | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(movingAverage(voltage), 8);
}


No usb serial on Mac I've been using my Arduino UNO without a hith for a few days now, but suddenly I can't program it anymore.

When I try to programm my Arduino on Mac, I get the following Error:

avrdude: stk500_recv(): programmer is not responding

The USB option under serial port has disappeard (It was there before). Has anyone an idea on how to fix this?

The last thing I did is use the serial port for some communication. A reboot hasn't improved anything.

I tried programming Linux, but it resulted in the exact same result.

It seemed to be a hardware problem on the board. Thanks for the effort.


Function pointers that call one function I'm reading a library file timer.h for STM core library that I just installed in Arduino hardware folder.

Of course, there has to be a lot of questions for me as a beginner about many approaches/stratgegies that programmers rule in writing the code.

One thing is that calling a function with a function pointer that only call one function, but the difference is that the function pointer is declared/defined as an inline function.

Edit: I deleted the code and posted a link for it in github.

stm32/timer header file

OK, the part that I started to think about starts from line 595.

It's functions declarations.

In line 598, it's a declaration for a function that receiver a pointer to a function.

In later lines, starting from line 634, these functions have only one line to execute. So my question is why to develop a function to only execute one line ?

Why they didn't just put that line directly instead of putting it inside function ?

bb_perip is a function that returns a pointer to a bit from a register that is related to a specific timer peripheral (there's more than one).  That pointer is then dereferenced with the * operator to make *bb_perip(...).

What bb_perip returns is dependent on what timer you are using and what value you are interested in.

bb_perip is not a pointer to a function, it is a normal function that happens to return a pointer.


USBasp problem: could not upload sketches to Arduino clone with PL2303 USB-to-UART chip I'm trying to upload sketch to a Gizduino board (these boards have PL2303 chip for USB-to-Serial communication; other than that they are entirely similar with Arduino Uno).

I have installed the driver for it and can verify that the board associates to a COM Port whenever the board is connected to my PC (Win10) via USB. But everytime I try to upload a sketch, IDE (tried with 1.8.2 and 1.6.9) throws the error below, with or without the PL2303 driver installed on my PC.

avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

I'm certain that I have selected the right board from the Boards List.

So my intuition was that the PL2303 driver is not working the way it should be. I've been trying to get more information about avrdude and USBasp but so far was not able to find anything remotely similar to my case.

UPDATE: Realized that all I needed to do is install the driver for USBasp (whihch I'm having trouble doing); this post could be off-topic. But I'm urged to raise another question: Which programmer should I select from the programmer list? Currently its "AVRISP mkII". In fact it doesn't matter which one I use. Same error about USBasp occurs with any of them selected.

Do you have a USBasp plugged into the computer? if yes then you need to install USBasp driver else why don't you just use the bootloader option from the arduino IDE.


Passing serial data to Processing using something other than ln to trigger Processing I have a Uno program and I can transfer data to Processing using println. In Processing bufferUntil('\n') interprets the ln  as \n, stops buffering, and reads the string until the next '\n'. I would like to use something other than ln to trigger Processing. That way I can use Serial Monitor in the Uno to see serial data when Processing is not running at the same time.

I have searched the net but have not found the technique to use something other than ln. Thanks.

If I understand your question (which is not certain):

Pick a different "trigger" byte that you won't be sending in your messages.  Maybe TAB?
In your "Processing" program, use: port.bufferUntil(TRIGGER);
In your Arduino sketch, rather than println, use print to send both your data and the trigger byte:  Serial.print(your_message); Serial.print(TRIGGER);

Note that sending binary data will cause this to fail when the data uses the trigger byte.

From: https://www.arduino.cc/en/Serial/Println The println()
   method sends your output then a CR and NL.  And it seems bufferUntil() takes a character on which to trigger:
https://processing.org/reference/libraries/serial/Serial_bufferUntil_.html


How to post image using Arduino HTTPClient I am using arduino HTTPClient to do the post request in ESP32. Can anyone help me with the part where I will be able to post an image file along with some data.
The below code works perfectly fine with only sending user_name and image_type-
#include <HTTPClient.h>

http.begin("https://www.somelink.com/post-image");

http.addHeader("Content-Type", "application/x-www-form-urlencoded");

String httpRequestData = "user_name=Shidhartha&image_type=Outdoor";

int httpResponseCode = http.POST(httpRequestData);
if(httpResponseCode > 0){
  String response = http.getString();
  Serial.println(response);
}else{
  Serial.print("Error on sending POST: ");
  Serial.println(httpResponseCode);
}

Below is the perfectly working code I got from here.
#include <Arduino.h>
#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "esp_camera.h"

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

String serverName = "192.168.1.XXX";   // REPLACE WITH YOUR Raspberry Pi IP ADDRESS
//String serverName = "example.com";   // OR REPLACE WITH YOUR DOMAIN NAME

String serverPath = "/upload.php";     // The default serverPath should be upload.php

const int serverPort = 80;

WiFiClient client;

// CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

const int timerInterval = 30000;    // time between each HTTP POST image
unsigned long previousMillis = 0;   // last time image was sent

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("ESP32-CAM IP Address: ");
  Serial.println(WiFi.localIP());

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  // init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 10;  //0-63 lower number means higher quality
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_CIF;
    config.jpeg_quality = 12;  //0-63 lower number means higher quality
    config.fb_count = 1;
  }

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    delay(1000);
    ESP.restart();
  }

  sendPhoto();
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= timerInterval) {
    sendPhoto();
    previousMillis = currentMillis;
  }
}

String sendPhoto() {
  String getAll;
  String getBody;

  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
  }

  Serial.println("Connecting to server: " + serverName);

  if (client.connect(serverName.c_str(), serverPort)) {
    Serial.println("Connection successful!");
    String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"imageFile\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
    String tail = "\r\n--RandomNerdTutorials--\r\n";

    uint16_t imageLen = fb->len;
    uint16_t extraLen = head.length() + tail.length();
    uint16_t totalLen = imageLen + extraLen;

    client.println("POST " + serverPath + " HTTP/1.1");
    client.println("Host: " + serverName);
    client.println("Content-Length: " + String(totalLen));
    client.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
    client.println();
    client.print(head);

    uint8_t *fbBuf = fb->buf;
    size_t fbLen = fb->len;
    for (size_t n=0; n<fbLen; n=n+1024) {
      if (n+1024 < fbLen) {
        client.write(fbBuf, 1024);
        fbBuf += 1024;
      }
      else if (fbLen%1024>0) {
        size_t remainder = fbLen%1024;
        client.write(fbBuf, remainder);
      }
    }
    client.print(tail);

    esp_camera_fb_return(fb);

    int timoutTimer = 10000;
    long startTimer = millis();
    boolean state = false;

    while ((startTimer + timoutTimer) > millis()) {
      Serial.print(".");
      delay(100);
      while (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (getAll.length()==0) { state=true; }
          getAll = "";
        }
        else if (c != '\r') { getAll += String(c); }
        if (state==true) { getBody += String(c); }
        startTimer = millis();
      }
      if (getBody.length()>0) { break; }
    }
    Serial.println();
    client.stop();
    Serial.println(getBody);
  }
  else {
    getBody = "Connection to " + serverName +  " failed.";
    Serial.println(getBody);
  }
  return getBody;
}


What is an easy way to power a 3.3v BMP-180 barometer board from a 5v Arduino Nano? Scenario:

I have a functioning weather station (temp/humid, MQ-2 smoke sensor, anemometer), and want to add a barometer.  The weather station is outside, linked to my inside display and RTC by the I2c&Power modules and ethernet cable.  The cable supplies 12v and I use a small converter to provide the 5v to run the I2c&Power board and the rest.

So I have 12v and 5v available out at the weather box.

Inside along with the RTC and LCD display I have a 2-port I2C&Power which will be used in the future (with the new pgpio library) to feed the info to an Rpi3 to create a web page to show changes over time.

The barometer module I bought is the BMP-180.  It is nice and tiny and looks perfect for the job, but the instructions all over the web tell me that it will burn up if powered by 5V.  The Arduino Nano does not have a 3.3v output pin like the Uno does.

Q:  What is the easiest way to accomplish adding this 3.3v board to the weather station?

Here is the solution I settled on:  a small part that will step 5 volts down to 3.3 volts.  The price is right, but it will be shipped by the slow boat so will take a month or so to receive.

5Pcs 5V to 3.3V DC-DC Step-Down Power Supply Buck Module AMS1117 LDO 800MA

http://www.ebay.com/itm/5Pcs-5V-to-3-3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-LDO-800MA-/261983164332

It has 3 pins - Vin, Vout, GND.    Easy to hook up.

Upvote to everybody for the discussion.


What are the current limits on an Arduino Micro? Just to make sure I don't set my board on fire, is there any information out there about the maximum current per pin/pin group on an Arduino Micro?

This page states I can get 40mA per pin, but are there limits on group of pins?

As stated here, there are pin groups which should not exceed 100mA. But could not find anything about that in the ATmega32u4 datasheet, or any other Arduino Micro related websites.

It's in the notes in section 29.2:

  Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
  If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
  than the listed test condition.
  Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
  state conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not fail if these are exceeded, but the rest of the numbers in the table may no longer apply.


Communication between 2 Bluetooth modules I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:

http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/

I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:

Reveiver - Master

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX | TX
String Data = "";
void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
}

void loop(){
    while (mySerial.available()){
        Serial.println(mySerial.read())
    }
}

Sender - Slave

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

int c = 100;

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

void loop(){
     BTserial.println(c);
}

I tried

BTserial.write(c)

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.

println prints the int variable c as string "100" with /r/n at the end. And you read it as bytes with read and print the bytes as numbers with new line at the end. So you get ascii values of 1, 0, 0, \r and \n.

use write() to write a byte to Bluetooth and to Serial Monitor


Water level Detection using Ultrasonic Sensor and arduino I'm making a water level detector to control my motor which supplies water in water tank and for that I'm going to use ultrasonic sensor to be attached to tank lid. My question is whether the vapor arising from water inside the tank hamper the overall working of ultrasonic sensor and/or it may be damaged permanently. I can cover complete ultrasonic sensor using hot glue stick but cannot cover its diaphragm as it will block sound waves. Please suggest something.

A friend of mine worked on a liquid level monitoring project, and after many iterations finally abandoned the kinds of sensors you're talking about. Ultimately he just pointed a cheap USB webcam at the thing and used OpenCV and the edge detection algorithm to find the level of the water.  Then it's just a matter of doing some math using the dimensions of the container, to figure out how full it is.

If you are using a clear container and if you have the option of using a Raspberry Pi (or a PC, whatever) that can run OpenCV, you might find that option worth exploring.


How do you post json data to HTTPS endpoint from ESP8266MOD? Board: ESP8266MOD module from AI Thinker.

Using ArduinoHttpClient I am unable to send a post message to an Azure IOT Hub endpoint. The endpoint is listening on 443 and expects a shared key passed via a custom header.

The error I get is "Connection Timed Out"

Here is the brief sketch

char serverAddress[] = "myapp.azure-devices.net";
int port = 443;
string sig = "Azure shared access signature";
HttpClient client = HttpClient(wifiClient, serverAddress, port);
  String jsonPayload = payload; // passed into this function
  client.beginRequest();
  String contentType = "application/json";
  client.post("/devices/deviceId/messages/events?api-version=2016-02-03");
  client.sendHeader(HTTP_HEADER_CONTENT_TYPE, contentType);
  client.sendHeader("Authorization", sig);
  client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, jsonPayload.length());
  client.beginBody();
  client.print(jsonPayload);
  client.endRequest();

  statusCode = client.responseStatusCode();
  response = client.responseBody();

The Status Code is -3 indicating a Timeout

I then created a simple REST API that accepts the JSON. Hosted it as an Azure website on port 80.

The board is able to connect to this HTTP endpoint

Question(s):
1. Is the board underpowered to handle HTTPS?
2. Is creating an HTTP proxy the only option?
3. Am I not using the right library?

Thanks

You are only making an HTTP request to an HTTPS server. It's not going to work.

AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the HTTPSRequest.ino example.


Multiple push buttons I am behind a problem of controling multiple leds with multiple push buttons. Lets say that I have 5 push buttons and 3 leds. Led1 turns on if at least 1 out of the 5 push buttons is pressed. Led2 turns on if at lest 3 push buttons are pressed and Led3 turns on if at least 4 push buttons are pressed.
How can this be solved ? With if else ?arrays?
here is my code that i have

 const int led1 = 2;
 const int led2 = 3;
 const int led3 = 4;
 const int bp1 = 9;
 const int bp2 = 8;
 const int bp3 = 7;
 const int bp4 = 6;
 const int bp5 = 5;
 int state;

void setup()
 {
 Serial.begin(9600);
 pinMode(led1, OUTPUT);
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(bp1, INPUT);
 pinMode(bp2, INPUT);
 pinMode(bp3, INPUT);
 pinMode(bp4, INPUT);
 pinMode(bp5, INPUT);
}

void loop()
{
 state = digitalRead(bp1);
 state = digitalRead(bp2);
 state = digitalRead(bp3);
 state = digitalRead(bp4);
 state = digitalRead(bp5);
if (state = HIGH)
{ digitalWrite(led1, HIGH); }

if (state = 3 )
{ digitalWrite(led2, HIGH);
if (state >= 4);
{ digitalWrite(led3, HIGH); }
}
else { digitalWrite(led1, LOW); }
}

Your code won't work as is. Each time you assign a value to state you're overwriting it in the next line. You could, for example have multiple int state variables such as state1 for the first line in the loop then state2 in the second etc. Then you need to compare values (don't use = on its own in a compare as it will assign the value being tested - use == instead). This way you gather all the button states first.

Or you could test the state of a button and if pressed add 1 to state:

if (digitalRead(bp1)) {
    state++};

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.

However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.

R3.


I'm trying to upload a sketch to my arduino uno, but I get the Error-Message "avrdude: stk500_recv(): programmer is not responding" Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I selected the right board (Arduino Uno)
I selected the right port
I selected "USBasp" as programmer
I reset the board multiple times
I have uploaded to the same port multiple times before without getting an Error
I disconnected the USB-cable multiple times and used a different one
I don't get the Error Message on a different board (also Arduino Uno)
When I'm trying to upload with the serial Monitor open i see an orange lamp (RX lamp) blinking in the same speed the Errors are given
When I'm trying to "Burn Bootloader" I get following Error:

Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'
Error while burning bootloader.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The problem was an Bluetooth extension I connected to the board. I removed it, uploaded the program, reconnected it, and that worked!


What's the best way to control a USB-powered desk light I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
How to control the light when using an external USB power supply ?

You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.

To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin HIGH the transistor will allow current to flow and light up the lamp.

Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes HIGH, the lamp will light up.


How to read high voltage (40-65v) from a Solar Battery bank I would like to monitor the battery voltage of a 48v solar battery system. The expected voltage range is 40-65v.

I have tried creating a voltage divider with 2 resistors but with all values I have tried one resistor almost melts as soon as you connect to battery.

Also, using a voltage divider creates a (small) drain which I would like to avoid.

Can anyone suggest a way of reading high DC voltage (40-65v) with and Arduino (really I'm using an ESP8266)?

If Voltage Divider

please suggest resistor types (e.g. 1/4watt or 1-2% etc, I'm new here but know there are many types) and values that I could read with A0 (analog pin, max 5v)

Can I use a MOSFET to connect the voltage divider just before reading the voltage? How?

or another way

like a circuit (from AliExpress) or using some other component that would be greatly appreciated.

So far this article has been helpful, it talks about a voltage divider with a opamp to get more accuracy, but I need a bit more advice from someone that knows more than myself.

https://openenergymonitor.org/forum-archive/node/11011.html

Thanks in advance for any help.

You need a voltage divider with resistors that have large values.

  ...but with all values I have tried one resistor almost melts as soon as you connect to battery.

This suggests that you have been using values that are too low.

So lets go through the calculations to select good resistor values.

1/4 Watt resistors are common and easily available so I will base my calculations on that. These calculations will also be suitable for 1/2 Watt and 1 Watt resistors.

I am also going to add some margin above the 65V max that the solar panel can output (plus it makes the math easier)

Max Voltage = 100V

The voltage Divider:

Let's simplify. Almost all of the current will be going from your source, through the resistors (R1 & R2) to ground. Let's simplify by initially calculating the resistance required if R1 & R2 were combined into a single resistor:

From V = I x R
And P= V x I

Minimum resistor = V^2 / P

R = 75^2 / 0.25

R = 22500 Ω minimum

I would go further and say double that because I never like operating a resistor right on its maximum power rating. ie  the minimum that R1 + R2 should equal is 50kΩ.

Lets play it safe and say that R1 + R2 is 100kΩ. The ESP8266 ADC pin input voltage range is 0 to 1V. Input is 0-100 V (which covers the required 40-65V range). Now all we have to do is calculate for R1.

Note: Most ESP8266 development boards come with an internal voltage divider. For these boards the input range is 0 to 3.3V.

Edit: The OP tells me that they get a max analog reading at 3.0V not 3.3V. Adjust the below calculations for an input voltage of 3.0V not 1V.

The formula to calculate the output voltage is:

Vout / Vin = R2 / (R1 + R2)

1 / 100 = R2 / 100kΩ

0.01 = R2 / 100k

Therefore R2 = 1k Ω

R1 = 100k - R2 = 99kΩ

I would up R1 to 100kOmega; as it will only result in a 1% error.

So R1 = 100kΩ and R2 = 1kΩ

Values of R1 = 49.5kΩ and R2 = 500Ω would also work.

In this case R1 could be made up of 2-3 resistors in series:
47KΩ
2.2KΩ
300Ω or 330Ω (optional)

The raw ADC input on the ESP8266 chip is 0-1V with a high input impedance (~20M). This means an op-amp buffer is not needed.

However, if you are interested, a op-amp circuit can be built from a 741 IC (among others) and is configured like this:


How to make an arduino wifi repeater? I am trying to make a wifi repeater. My router's signals don't come to my study and instead of buying a proper wifi repeater I prefer making one.

I want to learn how to make a simple wifi repeater that:

repeats/boosts my existing home wifi network by connecting to it.
Has some kind of a GUI or something that allows me to connect to it first (from some smartphone or PC) to configure it to my home network. It should find and show wifi networks around and then connect to the one I want it to upon my command.

I am new to electronics. Arduino is my preferred platform. If there are other easy to do alternatives that shall work too.

Any kind of help will be appreciated...tutorials, blogs, etc.

An arduino wifi repeater would in theory be very slow. Since you need to record the bit stream to the internal memory, then switch the spi to the transmitter, and send the bit stream, im unsure about what would happen if you miss a few bits in the process.

Arduino Wifi Shield - the price of a wifi shield 85 usd

Wifi repeater ebay the price of a wifi repeater 22 usd.

This makes me question why one would go through the troubble of making a wifi repeater of an arduino.

Even investing in a raspberry pi and a wifi dongle would be less expensive.


Problems with passing objects in tree structure I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code:

TreeNode.h

class TreeNode {

  public:
    TreeNode(String inputNodeName);
    TreeNode *children[];
    TreeNode &getChild(int index);
    int getLength();
    String nodeName;
    void addChild(TreeNode &node);
    String getName();

  private:
    int childLength;
};

TreeNode.cpp

  TreeNode::TreeNode(String inputNodeName) {
    nodeName = inputNodeName;
    childLength = 0;
  }

  TreeNode &TreeNode::getChild(int index) {
    return *children[index];
  }

  int TreeNode::getLength() {
    return childLength;
  }

  String TreeNode::getName(){
    return nodeName.c_str();
  }

  void TreeNode::addChild(TreeNode &node) {
    children[childLength] = &node;
    childLength++;
  }

I'm initialising it in the setup function:

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

    TreeNode mainTree("main");
    TreeNode firstChild("first child");
    TreeNode secondChild("second child");
    TreeNode subChild("subschild");

    Serial.println(mainTree.getName()); //prints "main"
    Serial.println(firstChild.getName()); //prints "first child";
    Serial.println(secondChild.getName()); //prints second child";

    mainTree.addChild(firstChild);
    mainTree.addChild(secondChild);
    Serial.println(mainTree.getName()); // prints an empty string
    Serial.println(secondChild.getName()); //prints second child"

    secondChild.addChild(subChild);
    Serial.println(secondChild.getName()); //prints an empty string
}

So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed.
I think I misunderstood passing an object by reference. Can anybody explain what I did wrong?

TreeNode *children[];

That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.

If you only expect a small amount of children then you can use that upper bound as a static allocation:

#define MAX_CHILDREN 10

//...
TreeNode *children[MAX_CHILDREN];

Otherwise use a vector instead:

std::vector<TreeNode *> children;


How to measure room light without LEDs interfering? I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.

The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.

Is there any standard or well known solution to this problem?

I will appreciate any help you can provide.

Additional Information

The LED strip is the WS2812B.
The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.

Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.

Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.

What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.

LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

Regular AnalogRead takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.


Emulating 1-wire device(s) What I want to do is make a ATTiny IC become a slave on the 1-wire bus, with its own S/N and command list for its specific functions.

What I want to know is if I can use the one wire library from the arduino site to send data as a slave.

For example, you can have a slave in one room with multiple types of sensors which would report to the master on requested information, or the master can tell it to control something like blinds.

Question
Would I have to monitor the bus line and respond to a request from the master and also take into consideration the way a normal sensor would send data? What frequency should I run the slave at to get the best functionality?

I won't use parasitic power, as a note.

As far as I know, the 1-wire library you linked in your question allows only to act as a master, not a slave.

I've just released a library to turn an Arduino board into a 1-wire slave, here: https://github.com/neuoy/OneWireArduinoSlave (edit: moved here https://gitea.youb.fr/youen/OneWireArduinoSlave). I use it in my custom home automation system, and it works flawlessly in my setup (the 1-wire master, a DS9490R, is connected to a laptop via USB, and also provides power to the Arduino, which is an Arduino Uno). The library handles low level details: match rom, byte send and receive (which is actually quite hard to get right, mostly impossible without a logic analyzer). The rest is up to you.

It's entirely implemented with interrupts, all communications are performed in background, you can execute other code as usual, in parallel, and are notified by callbacks when bytes are received etc. Sending bytes to the master is also asynchronous.

I also know at least one other library exists, https://github.com/MarkusLange/OneWireSlave, as commented above by Ryu_hayabusa. It didn't work for me (don't know if it's because of my hardware setup or for another reason), but it definitely work for others, so also worth a try. It seems this library is not implemented with interrupts, so your program is blocked while waiting for master activity (which is perfectly acceptable in a lot of scenarios).


Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose) I need to have several Nanos on one USB port. They will have separate power, so power constraints won't be a concern. I need them all to go through the same serial port. They will never get anything sent to them, and should never send data simultaneously. Each one is connected to a switch, and upon pressing the switch, will send an 8-digit serial number over serial. I want to have a VB.NET application which listens over this shared serial COM for numbers, and collects them all, displaying them in a history list. Can this work?

For a USB topology to operate one needs a USB controller which knows about all the different USB protocols necessary to communicate with all the different USB peripherals (this is why a USB controller is usually a fully capable computer) all connected through a USB hub.  It is unlikely a USB network could be created using only peripheral USB devices which were wired directly together.

To communicate between several Arduinos and a computer it would be much easier to use a serial bus made for multiple drops like RS485. There are many RS485 to USB converters available like this one for computers that do not have an RS485 port.


How to have arduinos work together? I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?

Yes and no.

Yes you can make Arduinos communicate with each other and send messages to each other.

Can you use that to make a game?  Possibly.

Is it worth the effort?  No.

It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.


What alternatives are there to the Optiboot bootloader? Nearly all modern Arduino boards use the Optiboot bootloader. Compared to the ATmegaboot used before, this is smaller in flash terms (by about 1.5KB) and faster in upload speed (115.2k vs 57.6k) and starts your sketch quicker (the delay whilst waiting after reset is shorter).

Are there any alternatives to the Optiboot bootloader? Specifically, are there any smaller (in flash terms) boot loaders? What differences do they have?

Optiboot is about the smallest bootloader available.

But, there is a much more powerful (with inbuilt console for hardware testing, RAM and Flash contents checking, etc) bootloader with a more developed and robust stk500v2 communications protocol between avrdude and the AVR bootloader.

I've used it on the ATmega2560 and on the ATmega1284p. It works for both 3 byte and 2 byte program counter MCU.

I have a STK500v2 Bootloader version on Sourceforge.

This bootloader is based the Peter Fleury STK500v2 bootloader, updated by Mark Sproul. I've made edits to have it supporting with the Goldilocks (an ATmega1284p) board.

The key feature is to use the STK500v2 protocol for uploading the Flash image to the Arduino. This protocol is more robust and gives better error capabilities than the avr109 protocol. As an aside the avr109 protocol is called "Arduino" in the Arduino world, because it toggles DTR (to reset the board and automatically enter the bootloader), and the STK500v2 protocol is called "Wiring" in the Arduino world, because of the same reason.

The Fleury/Sproul STK500v2 bootloader is designed to work with the ATmega2560 which has a 3 byte program register, because of the larger Flash size. But, it also supports normal 2 byte boards (everything else really).

For boards with plenty of Flash (like Goldilocks 1284p), there is a hardware monitor that can be used to query Flash, SRAM and hardware; you can check connections without additional code, and check the actual contents of Flash and EEPROM. Because the 1284p supports 2 USART, I added the ability to have debugging on USART1, so that the upload process via USART0 isn't disturbed.


Pseudo-code of a program I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?

#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}

"Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.


Wemos: relay shield doesn't work on top of the stack I connected a SHT30 shield to a Wemos D1 mini (one on top of the other) to measure temperatures.

Wemos D1 mini (2.3.0):
SHT30 shield:

It works great but when I added a relay on the top of the stack it doesn't work anymore.

Relay shield:

Maybe there are a conflict with their pins. So these are their schematics:

This is the solution that I made but I don't know why this works instead of inserting the relay shield on top of the SHT30 shield:

Yes, there is a pin conflict.  The relay uses D1, however D1 is (as you can see from looking at the schematics) part of the I2C connection for the SHT30.

You will have to find some way of modifying the relay shield to use a pin that's not part of I2C.


Not able to control DC motor speed with l298N & pwm pins I am using arduino uno to control dc motor speed with L298N. But the problem is that the motor is only going at max speed. PWM pin doesn't work for some reason.
I heard many people had some problem but haven't found the solution yet.

code:-

#include <L298N.h>

#define ENA 9
#define IN1 8
#define IN2 7

L298N motor(ENA, IN1, IN2);

void setup() {
// Setup pin mode

//used for display information
  Serial.begin(9600);

}

void loop() {
//Drive Motor Forward
  motor.setSpeed(10);
  motor.forward();
  delay(500);
  motor.setSpeed(100);
  motor.forward();
  delay(500);
  motor.setSpeed(255);
  motor.forward();
  delay(500);

}

I only see the motor move at full speed every time. I connected 5V of Arduino to +12V pin of motor driver and Arduino is powered with my laptop USB.

I am using 4.5V toy dc motor for test - DC motor

What could be wrong here?

Try to use this code, without the library, and be shure to connect every pin to the correct arduino output! If everything is ok it should work! Check a tutorial here

int IN3 = 5;
int IN4 = 4;
int ENB = 3;
void setup()
{
 pinMode (ENB, OUTPUT);
 pinMode (IN3, OUTPUT);
 pinMode (IN4, OUTPUT);
}
void loop()
{

  digitalWrite (IN3, HIGH);
  digitalWrite (IN4, LOW);
  analogWrite(ENB,55);
  delay(2000);
  analogWrite(ENB,105);
  delay(2000);
  analogWrite(ENB,255);
  delay(2000);
  analogWrite(ENB,0);
  delay(5000);
}


Having difficulty uploading sketch to an Arduino Pro Mini Having developed and tested a project using an Arduino Uno, I would now like to upload it to an Arduino Pro Mini (5V, 328, 16MHz) for semi-permanent, long-term use, but I can't get any sign of life from the Pro Mini.

I'm using the latest Arduino IDE (v1.6.0 with Java 6, on Mac OS X Mavericks), and I've got a USB 2.0 to TTL UART 6PIN CP2102 Module Serial Converter to connect the Pro Mini to the Mac, and I've selected Tools —> Board —> Arduino Pro or Pro Mini (5V, 16MHz) w/ ATmega328.

The problem is that I don't see a suitable serial port in the list. When I plug in the Arduino Uno, "/dev/tty.usbmodem1421" immediately pops up in the Tools —> Serial Port menu, but I don't see anything similar with the Mini Pro.

The problem is probably in the connection between the USB/TTL converter and the Mini Pro, so my question is: which pins should connect to which?

FWIW the USB/TTL converter was supplied with a 5-core (not 6-core) cable to connect its 6 pins.

So do I connect Tx—>Tx and Rx->Rx, or should they be crossed over? It's fairly clear that "5V" connects to "Vcc" and "GND" goes to "GND", but what about CTS and DTR?

Also FWIW, I have googled this, and I have read a number of other posts and answers on StackExchange, but the fact that I'm here writing my question means that I'm still stuck. Any and all constructive suggestions will be appreciated. Thanks!

You need to hook it up with the Arduino TX --> FTDI RX, and vise versa, so crossed over.  If you take the FTDI and hook it up to the Ardiono pin to pin as you have it pictured it should work, provided the FTDI works.

No to your note about not having a serial port, you should have that as soon as you plug the FTDI into your computer, the Arduino is not necessary for this.  First things first, check you drivers, and check your USB connection.  You won't get anywhere until that Serial port is recognized on your computer.


Is there a way to get my MacBook's date and time into Arduino IDE? I am using a DS3231 RTC module. It requires to set the time every time it is reset. I was wondering if I could read my MacBook's time and date and feed into the module at the setup stage. Is this possible?

P.S. I do not have to use a battery.

You can use __DATE__ and __TIME__ compiler time constants in IDE and do check inside of your setup() function if the RTC clock is zeroed then parse and set compile time values.

char cr[] = __DATE__;
char ct[] = __TIME__;

At the compile time these macros will be replaced with text constants "Apr  4 2019" and "10:35:22" respectively.


Can we call GPRS HTTP request asynchronously in Arduino? Usually GPRS modules (SIM800,900, A6, etc) that used with arduino are called in synchronous way in HTTP (GET/POST) request. It takes more than 10 seconds in most times and this makes the system very slow. Is there a way to use them (libraries or the module) asynchronously (or is there any alternatives) and perform these request in background while main business is being done?

Sure there is. All you're doing is reading and writing serial data. All you have to do is learn how to do that without blocking.

Most code I see bandied around is of the form:

Send AT command
Delay for numerous seconds
Read and discard anything that might be there
Send another AT command
Delay for more seconds
Read and discard anything that might be there
... etc ...

That is completely the wrong way to do things.

Instead you should be using non-blocking reading to look for an actual OK response from the AT commands that you have sent and use that to progress through the different stages of a Finite State Machine.

Some reading resources from my blog:

Reading Serial on the Arduino
The Finite State Machine
The Evils of Arduino Strings
Splitting Up Text in C


How would I go about scrolling a name across a LoL shield with a potentiometer? I am fairly new to Arduino programming and I have been set with the task of scrolling my name across a LoL shield with a potentiometer. I really don't have any idea how to do this and when I tried to look it up online there is nothing for such a task. I did look at the library references on the LoL shield website but I couldn't make sense of it.

What I did find was a LoL shield sequencer to allow animation on the LoL shield and I figured that might help but I don't know how to use that code to create a scrolling effect with a potentiometer.

You know how wide the display is. You know how wide the text is. You know the position of the potentiometer. With those you can determine where in the text (if the text is wider) or display (if the display is wider) you need to start drawing from and where you need to stop drawing. Subtracting the text width from the display width will give you the range for performing linear interpolation with the pot position.


Arduino - Raspberry Pi serial communication I need to connect a Raspberry Pi and an Arduino Uno through serial communication and decided to follow this guide, which mentions the use of a voltage divider.

I understand the connection to the Raspberry Pi GPIO requires 3.3V but I also plan to power the Raspberry Pi from the Ardunio's 5v output pin.

What's the safest approach to achieve this and the recommended current? Thanks.

You CAN NOT reliably power any model Pi from the Arduino 5V output.
You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, AND you can power the Arduino from the Pi (I often do this).


Controlling a NC connection from two sources? I'm trying to control a garage door opener. The button that lets you open the door from the inside is a NC connection (press the button and it goes to "open" and makes the motor run).

I want to keep that AND add another source (an Arduino w/ an RF module) that taps in to this.

Is there some sort of splitter I'd add to the garage door button wires to do this?

Are you certain that your existing circuit is NC?

The typical garage door opener button is a momentary switch. Many third party remote devices, including two that I have installed, tap directly into this circuit. Because the contacts short across the existing switch, activating one, two or three is insignificant. These switches are connected in parallel.

It would be a good idea to use an external isolation circuit to the Arduino, either a relay or SSR in order to ensure that there is no "injected" power from your circuit to the garage door circuit.

If your circuit is indeed an NC type, you would connect your new relay or SSR in series, using the device's NC connections. The locations for tapping into the circuit would be where your existing button resides or where those two wires engage your garage door mechanism.

I suppose my older garage door opener is NO, while newer models would use a different architecture, aka NC.


Using rotary encoders with pin change interrupts I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.

I'm using the Rotary library (github link) for the rotary encoders and the EnableInterrupt library (github link) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):

#include <EnableInterrupt.h>
#include <Rotary.h>

Rotary r = Rotary(2, 3);

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

  /* Original interrupt setup:
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
  */

  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);
}

void loop() {

}

void interruptFunction() {

  Serial.println("Int. called");

  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.

My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.

Hope you can help!

check the library to see if it debounces the input.

if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.


Arduino uno + XBee Shield Not transmitting when under battery power? I have a few Arduino's along with XBee Shields communicating with one another.

The problem I'm having is that, when all the Arduinos+XBee Shields are powered via USB(PC) they seem to work fine and all transmissions get through to one another. But, when I use them with 9Volt batteries(fairly new batteries) the whole thing crashes and I never receive responses back from the battery powered ones.

I'm wondering if this is really a power issue? wouldn't a 9volt be enough to power a single arduino(uno)+xbee shield?

Using a multimeter you can confirm your theory by looking for a voltage drop on the power connections to the XBee and into the UNO.

9V batteries don't store much charge, nominally 563mAh according to wikipedia. It is possible that the fairly new batteries are not that new after all.

Depending on the XBee, power consumption varies. 40mA for a normal XBee (ZigBee), 200mA for pro, and 309mA when transmitting for the new XBee WiFi. If the battery is low, the high current draw plus internal battery resistance may drop the 9V output to below the 7V needed for the UNO's voltage regulator to function correctly.


ATTINYx5 usi for uart? Can the ATTINYx5 use its universal serial interface for a better UART than the Sofware Serial library alone? If so, is there a library or tutorial for this?

AVR307 describes implementation of a half duplex UART implementation using the USI. Note that full duplex is not possible due to the synchronous design of the USI.


Difference between void setup() and void setup(void) As it says in the title. I have been searching but I cant seem to find the answer.

What is the difference between void setup() and void setup(void) as well as void loop() and void loop(void)?

Absolutely nothing, in modern versions of C and C++. Specifying no arguments is the same as specifying void.

In old versions of C a function with no arguments took a single implicit int argument or allowed you to specify the arguments on a separate line, but no one uses anything like that nowadays.


Programming arduino with Objective-C Can you use clang, with --mpu=arm, etc. and avrdude to program an Arduino Due (Arm Cortex M3)?

Simple version: No, you cannot program Arduino using Objective-C.

Long version:
The Arduino IDE uses avr-gcc as it's compiler, and avr-gcc is a C/C++ compiler, not an Object-C compiler. The Arduino libraries are written in C/C++.

There are other compilers that exist for AVR processors, and so it is possible to use other languages for the AVR.

However, if you switch to a different compiler for your code, you will not be able to use the Arduino libraries with it, because they are written in C/C++ for the avr-gcc compiler. (It may be possible to compile the Arduino libraries with avr-gcc, and then link them to your code using external language linking methods, but that could be a significant challenge.)

Also, I do not know of any existing Objective-C compilers for AVR; it's possible one may exist, but after a quick web search, I didn't find any.