text:
How to read the raw data from GY-85 module?
This module has 3 sensors. Gyroscope, Accelerometer and Magnetometer.
I think I'm reading the raw data in the wrong way.
For example, for the magnetometer HMC5883L, I'm using this code which I copied from a library and it gives the correct values, but when I use the same code for reading the raw data from the accelerometer ADXL345 then it's not what it should be according to different sources I've read.

The magnetometer HMC5883L:
void HMC5883L_print_Serial(void)
{
  int16_t x,z,y;
  uint8_t data[6];
  float heading,heading_in_degrees,declination_angle_YANBU;

  data_read(data);

  // This one doesn't
  x = data[1] << 8 | data[0];
  z = data[3] << 8 | data[2];
  y = data[5] << 8 | data[4];

  // This one works OK
  /*x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];*/

  heading = atan2(y,x);
  declination_angle_YANBU = ((3.0 + (52.0 / 60.0)) / (180 / M_PI));  // in yanbu city it's
  heading += declination_angle_YANBU;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0){
    heading += 2 * PI;
  }

  if (heading > 2 * PI){
    heading -= 2 * PI;
  }

  heading_in_degrees = heading * 180 / M_PI;
  Serial.println(heading_in_degrees);
  _delay_ms(20);

}

The accelerometer ADXL345
void ADXL345_print_Serial(void){
  int16_t x,z,y;
  uint8_t data[6];

  ADXL345_read_raw(data);

  // This one gives values from -255 to +255
  x = data[1] << 8 | data[0];
  z = data[3] << 8 | data[2];
  y = data[5] << 8 | data[4];

  // This one give values from -32768 to +32768
  /*x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];*/
    Serial.print(x);Serial.print("\t");
    Serial.print(y);Serial.print("\t");
    Serial.println(z);
    _delay_ms(100);
}

So basically I want to learn how to work with these sensors and also I want to know the principles about each one, because I'm confused between then I feel they are the same and each one provides similar functions; like, tilt sensing.

One gives you an absolute orientation using the earth's magnetic field. The other gives you changes in velocity (and gravitational pull, which is a form of acceleration). In what way are they the same?

Have you looked at the ADXL345 datasheet to see what the communication protocol is? Is it the same as for the HMC5883L? Or should you be implementing a different system?

Hi, they both use I2C protocol. All the sensors on that board use the same protocol. You're right they are different but I thought it's like similar, because they change the values when tilting! That confuses me because; for example, the accelerometer should change the values only when I move it forward, backward and up-down, so it also changes the values when I flip or tilt it .. that was confusing.

OK, I started to understand the the accelerometer is actually measuring the static gravity values, that's why it gives values on each side of the module. The internal mass is tilting positions. So, I just now have to understand how to know how to prepare these values for my project.

One of the places where the datasheets for the sensors of the GY-85 module can be found is here: https://www.hotmcu.com/gy85-9dof-imu-sensor-module-p-298.html
The following information comes from these datasheets:
Both the HMC5883L and the ADXL345 have internal registers which are numbered consecutively. When reading more than one register they are most efficiently read in the order they are numbered. For each of the three axes both sensors use two 8-bit registers to hold the measured value.
In the HMC5883L the register with the lower number holds the most significant byte (MSB) and the register with the higher number holds the least significant byte (LSB). This means that in a consecutive read the MSB is read first followed bij the LSB. When you combine these two bytes into one 16 bit number (datatype int) you have to shift the MSB-holding byte (the first byte received) 8 places to the left and "OR-in" the LSB-holding byte (the second byte received).
In the ADXL345 the internal numbering is the other way around: the register with the lower number holds the LSB and the register with the higher nummer holds the MSB. When reading, the LSB is red first followed by the MSB. So this time you have to shift the second byte received and "OR-in" the first byte received.
Both sensors give the measured value as a 16-bit 2-complement number, corresponding to datatype int (Arduino Uno). An 16-bit int can hold values from -32,768 to +32,767 but the sensors don't (can't) use this full range:
The ADXL345 has an adjustable range with a maximum of 13 bits (-4096 to +4095).
The HMC5883L has a range of 12 bits (-2048 to +2047).

OK, then my current HMC5883L is wrong. I put the first byte on the right of the 16-bit register. As in this code: x = data[1] << 8 | data[0];   z = data[3] << 8 | data[2];   y = data[5] << 8 | data[4]; But I have to change it.

Success! Please let us know if if you new code works.

Yeah it's working now. My current concern is that I know that taking the atan2(y,x); would give me the heading. But what is the benefit of z-axis? And how can I use the HMC5883L in a quadcopter?


text:
I2C_graphical_LCD_display, fatal error: avr/pgmspace.h: No such file or directory
I have a problem with an ESP32 devkit V1 card. I'm trying to connect a WG12864A Winstar mod graphics display via the I2C MCP23017 adapter (RobotDyn), using Nick Gammon's I2C_graphical_LCD_display.h library.
Everything works well by connecting it to the Arduino Uno - Duemilanove board. Loading the sketch LCD_Demo_Using_I2C present in the library is compiled correctly without errors.
If I connect the display to ESP32 devkit V1, I try to compile it I get the following error:
C: \ Users \ Topolino \ Documents \ Arduino \ libraries \ I2C_graphical_LCD_display-master / I2C_graphical_LCD_display.h: 62: 26: fatal error: avr / pgmspace.h : No such file or directory.
Compilation terminated.
exit status 1
Error during compilation for DOIT ESP32 DEVKIT V1 card.

I tried to compile it with PlatformIO presents the usual compilation error.
You can help me, someone has some ideas to solve the problem.

The authors of the ESP32 core didn't bother to create a proper set of compatability shims for the PROGMEM system - chiefly because it's not needed for ESP32 operation.
We did for chipKIT, though, and you can grab a copy of ours here and place it in with the core files for the ESP32 in your Arduino installation (you only need the pgmspace.h file, and place it in an avr folder inside the core source folder).
It's completely architecture agnostic and basically defines some pretty much empty macros, and maps _P variants of various functions to the non _P alternatives.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How can I concatenate these two values as a string?
I've tried all the supposed solutions for the exact error, pasted into google, that I could find on every forum including this one and no matter the alleged solution I will either get the error about unsigned int to char*, the error below, or invalid pointers.
Why is this platform so completely unfriendly in data type conversion? It's almost as if the creator/s never wanted any data types to be able convert.
Here's my code that is apparently useless:
  char* DeviceName = "Device-" +  ESP.getChipId();
  wifiManager.autoConnect(DeviceName);

Error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
   char* DeviceName = "Device-" +  ESP.getChipId();
Then I tried to use the pointers, but I have no idea what I'm doing and I keep getting invalid pointer errors, and/or invalid conversion errors.

Hint: Try using sprintf(). http://www.cplusplus.com/reference/cstdio/sprintf/

char buffer [50];
char DeviceName = sprintf(buffer, "Device-%d", ESP.getChipId());
wifiManager.autoConnect(DeviceName);

error: invalid conversion from 'char' to 'const char*' [-fpermissive]
wifiManager.autoConnect(DeviceName);

You can use the c function sprintf(, , ...)
The char array has to be big enough to hold your text plus a null to terminate the string.
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  delay(1000);
  char out[20];
  sprintf(out, "Device-%08X",ESP.getChipId()); // %08X\n formats the hex and pads with 0s.

  Serial.println(out);
}

void loop() {}

Output:
Device-005D4D9D

Thank you! I tried this and it does output a numeric ID, but I wanted the string ID.
ESP8266 Chip ID = 005D4D9D <- this should be the ID...
Device-6114717 <- not the numeric conversion here

you are welcome - helpful user changed the format string to output 8 hex digits instead since that is what you seem to be looking for.

Learning is good. To eliminate extra characters you can also use sprintf(out, "Device-%X",ESP.getChipId());

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

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

#include <Arduino.h>

void blink();

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

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

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

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

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

I've got same issue after a deep sleep. Here is the error code @74880bps : epc1=0x40100000, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 Fatal exception (0): But when I see this issue, if I manually push the reset button or manually plug RESET to GND, the board is rebooting and restart my code as expected. Only the wakeup from deepsleep generates this issue. Have you fixed your issue ? Thanks,

The garbage is because the ESP8266 outputs boot information at 76800. This should include the boot reason and may help you understand why the code's not working as expected.
Try changing your Serial speed to 76800 in your code (just so that your messages don't end up being gibberish), use 76800 on platformio's monitor and you should be able to at least see what the D1 says it's doing.
You should see a line that ends in something like:

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

x should be 1 ("Power reboot"), 2 ("External reset or wake-up from Deep-sleep" - obviously what you want), 3 ("Software WDT" - the software watchdog went off) or 4 ("Hardware WDT reset" - the hardware watchdog timer went off)
boot mode indicates where the runtime image came from - y should be 3 ("Flash"); anything else is really unlikely for your setup.
There's more info on this at ESP8266 Reset Causes
and Common Fatal
Exception Causes
If you try this please post how it goes! I'd like to hear more about what's going on here.

Thanks a lot! The baud rate is right to capture that "garbage" - this is the output after setting the serial rate to 76800 everywhere:
--- Miniterm on /dev/ttyUSB0  76800,8,N,1 ---
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Hello I'm in the setup now
Going for some deep sleep

 ets Jan  8 2013,rst cause:5, boot mode:(1,6)

ets_main.c```

Don't know how to format code in the comments...

So the reset cause was the deep sleep wake up. The deviation in boot mode is something I'll have to dig in for tomorrow.

Yeah, unfortunately there's not a good way to format comments :( bites me all the time. Boot mode 1 should mean it's trying to boot via the UART (download new code) rather than the flash. Do you have anything wired up to D3 or D4? If you do try disconnecting them or try wiring D3 to 3.3V via a high value resistor (say, 47K or more, shouldn't really matter exactly the value). More info on boot mode at https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes

So the 1 in `boot mode(1,6) seems to mean my d1 mini is expecting to download code from the UART like you say: https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes
That message doesn't make a lot of sense to me. Sending code over serial doesn't seem like something the board can request.
Anyway - a little frustrated with this - I do appreciate all the input from folks, but for now deep sleep is eluding me.

@SEngstrom - yeah, the board can be forced into a mode where it boots code provided through the serial port, definitely not useful here. That's why I was asking about the D3 and D4 lines on the board - are they wired to anything? They're what controls the boot mode. If they're not wired to anything, try forcing D3 high and D4 low - that should force the ESP8266 into the mode where it boots from the SPI flash.

When I D3 high and D4 low the on-board LED goes on and stays on and I am not able to talk to the board any more. However, now I get a boot mode: (3,6) instead after pulling off the D3, D4 pulls, but it still stops after reporting that after the deep sleep wake-up.

It seems like there's something different between your D1mini and mine. I'm pretty much out of ideas here, sorry! Like @Rudy said, it should work (and I see it work with the same setup). I'll post a new comment if I can think of anything else to try.

Try and clear out the whole memory. Maybe there is something that is messing it up.
I tried your code and it works for me. I do not have a D1 mini but I can't see any reason for it not to work. (due to hardware reasons)
I would include a delay and then output a newline in the setup. As it is your loop print is written after the boot info and gets lost at the end of the line.
Like I said, your code worked for me. But I find this more user friendly. https://raw.githubusercontent.com/wemos/D1_mini_Examples/master/examples/02.Special/DeepSleep/Blink/Blink.ino
Check again your connections. (I'm sure you have done that a dozen times)

Thanks. Did what I think is a firmware reset by connecting D3 to GND for 5 seconds. Added a delay and a Serial.println() in setup(). Same results. I came across the link you suggested before but there is no difference if I put it all in setup().
It seems it is not only that the Serial communications are borked, the blink() should still happen if the code gets there (and it should reset again a little later).

Yeah. Like I said, your code works. (even though I don't like it) Do you have another board you can try?

I think @Rudy is right. I just tried the code on a D1 mini and it works fine for me. You can completely reset the firmware with PlatformIO with a command like this (you may need to change the serial device name): ~/.platformio/packages/tool-esptool/esptool  -vv -cd nodemcu -cb 115200 -cp /dev/cu.usbserial-1430 -ce

Thanks John - executing that results in:
stefan@Cameron ~ $ ~/.platformio/packages/tool-esptool/esptool -vv -cd nodemcu -cb 115200 -cp /dev/cu.usbserial-1430 -ce –
esptool v0.4.13 - (c) 2014 Ch. Klippel ck@atelier-klippel.de
setting board to nodemcu
setting baudrate from 115200 to 115200
setting port from /dev/ttyUSB0 to /dev/cu.usbserial-1430
espcomm_erase_flash
opening port /dev/cu.usbserial-1430 at 115200
error: cannot access /dev/cu.usbserial-1430

seems there were some success, but no change in the behavior when running the code.

@rudy - I did try another previously unused board and same result. Too bad you don't like my code :)

@SEngstrom the error on clearing the flash means the serial port name (/dev/ttycu.usbserial-1430) is wrong - if you want to try that again you'll need to find use the correct one for your system. Platformio probably prints it somewhere. It's probably just the "1430" part that'll be different.

@JohnRomkey thanks again - I did run that  esptool command but no dice.


text:
Trying to run Timer1 in ATmega2560 with assembly
I have a slight problem with Timer1 in arduino (ATmega2560) while coding it in assembly. I try to run the Timer1 in CTC mode - I configure everything well in my opinion, but the TCNT1 just doesn't increment each clock cycle, as it should. I checked the registers in Atmel Studio and everything seems okay, but maybe I forgot about something?
Here is the code
.ORG 0
jmp start

.ORG 0x22
call isr_toggle_PA0

.ORG 0x400
start:
LDI R16, HIGH(RAMEND)
OUT SPH, R16
LDI R16, LOW(RAMEND)
OUT SPL, R16 ; initialize stack pointer
clr r16

ldi r16, 0xff
out DDRA, r16 ; port A output
ldi r16, 0x00
out DDRD, r16 ; port D input
clr r16

ldi r20, 1<<OCIE1A
sts TIMSK1, r20 ; enable Timer1 A comapre match interrupt
sei

ldi r20, HIGH(25000)
sts OCR1AH, r20
ldi r20, LOW(25000)
sts OCR1AL, r20

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20
ldi r20, 0
sts TCCR1C, r20

; --- start main
main:

inc r16
rjmp main
; --- end main

isr_toggle_PA0: // toggle bit on PA0
    ldi r16,0x00000001
    in r17, PORTA
    eor r17,r16
    out PORTA, r17
    reti

Thank you and have a good day :)

Here:
ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20

you are setting the bit WGM11 on TCCR1A. The timer then runs in mode 2 (PWM, Phase Correct, 9-bit) rather than mode 4 (CTC).

Amazing!! Ineed that was the bug. For the ones wondering, the correct version is
ldi r20, 0b00000000 ; CTC mode, int clk;  sts TCCR1A, r20    ldi r20, 0b000001101 ; prescaler /1024  sts TCCR1B, r20


text:
Code working well on Arduino Uno is not working with Mega 2560
Following is the code block from my script. It uses timer1. Why it is not compatible with Arduino Mega?
TCCR1A = theTCCR1A; // 0b10000010;
  /*10 clear on match, set at BOTTOM for compA.
   00 compB disconected initially, toggled later to clear on match, set at BOTTOM.
   00
   10 WGM1 1:0 for waveform 15.
   */
  TCCR1B = 0b00011001;
  /*000
   11 WGM1 3:2 for waveform 15.
   001 no prescale on the counter.
   */
  TIMSK1 = 0b00000001;
  /*0000000
   1 TOV1 Flag interrupt enable.
   */
  sei();             // Enable global interrupts.
  // Set outputs pins.
  DDRB   = 0b00000110; // Set PB1 and PB2 as outputs.
  pinMode(13, OUTPUT); // Set trigger pin to output

Here I set pb1 and pb2 as output. But they don't get high or low as per my code. It works well with Arduino uno

Remember that comments are not part of the Q&A. The problem you are having should be in the question as an [edit]. But, really, you ought to just research this on the specific SE I mentioned.

It's not working because code you write is code that will work only on ATmega328. Every ATmega328 chip will run this code without any problem.
If you want that Mega does same task as Uno, then you have to rewrite whole code and use Arduino functions(such as pinMode, digitalRead etc..) or read ATmega2560 datasheet and use ATmega2560 registers. Also Search for ATmega2560 pin layout, you'll need it if you want use registers.


text:
Arduino Swissflow Meter
We've hooked up a Swissflow sf800 flow meter to our Arudino Uno. The system works, our interrupt callback is triggered and as water flows through the metre, it counts up. The issue is, that the pulse rate is supposed to be 5600/L and we get exactly double that, so we get 5600 per 500ml.
The code is:
if(millis() - lastTime >= 1000)
{
  noInterrupts();
  totalCount = pulseCount;
  lastTime = millis();
  interrupts();

  if (totalCount >= 5600)
  {
    // Here we have 500ml of water, not the expected litre....?
  }
}

void InterruptCallback()
{
  ++pulseCount;
}

For sake of brevity, I've left out variable declarations and globals etc but the code is working as "expected". Is the pulse count not correctly counted in the interrupt callback? We're both fairly new to this, but it seems to be the way people have implemented it in other examples. If it helps, the interrupt is set to trigger on RISING.
Link to the flow meter and spec:
http://www.swissflow.com/sf800.html
http://www.hemomatik.se/PDF/Datasheet_SF-800-3-8_2012_h.pdf
Interrupt code:
attachInterrupt(digitalPinToInterrupt(2), InterruptCallback, RISING);

The interrupt is being triggered and the count increases.

Without seeing the specs of your flow meter it's hard to answer.

And the initialization of the interrupt.


text:
TinyGPS++ isn't being updated or SoftwareSerial isn't reading
I'm trying to read the GPS data on an Arduino Uno from a Neo-6M module and print it on a LCD display. However, no variable is being changed by the read function. This could either be because of an incorrect reading of the gps variable or a wrong use of the SoftwareSerial library.
Here's the code:
#include <TinyGPS++.h>

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <splash.h>

#include <SoftwareSerial.h>

Adafruit_SSD1306 display;  // Create display
SoftwareSerial gpsSerial(4,3);//rx,tx
float lati=0,longi=0;
float sat=0;
TinyGPSPlus gps; // create gps object

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  gpsSerial.begin(9600); // connect gps sensor
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Initialize display with the I2C address of 0x3C
  display.clearDisplay();
  display.setTextColor(WHITE);
}

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

    gps.encode(gpsSerial.read());
    display.setCursor(80,3);
    display.print("R");

  //if(gps.location.isUpdated())
  {
    lati = gps.location.lat();
    longi = gps.location.lng();
    sat = gps.satellites.value();
    display.setCursor(100,3);
    display.print("U");
  }

  display.setCursor(20,20);
  display.print(lati);
  display.setCursor(20,40);
  display.print(longi);
  display.setCursor(100,40);
  display.print(sat);
  display.drawRect(0,0,127,63,WHITE);
  display.display();
}

EDIT: The data coming from gpsSerial is a series of -1
EDIT 2: Swapping SoftwareSerial gpsSerial(4,3); to SoftwareSerial gpsSerial(4,3); makes it output a series of ints. However, encoding it with gps.encode(gpsSerial.read()) still doesn't update the data.

no prints to Serial? why not use it for debug prints or connect the gps to it?

I'm powering the arduino with a battery to be able to go outside to test the reception, so I'm printing the information on the screen to read it as it's collected

then connect the module to Serial and don't use SoftwareSerial

I don't have a serial to miniUSB cable

pins RX and TX. 0 and 1.

did you connect RX to TX?

I tried rewriting the sketch to read data through the serial monitor and I tried swapping pins in every possible configuration, but i'm still getting the same problem. EDIT: I'm currently reading the direct gpsSerial.read() and it's a neverending series of -1s

read returns -1 if no data is available


text:
FastLED: Can't address led individually
I'm unable to access the first led in my strip with this code:
void loop()
{
  leds[0] = CRGB::White; FastLED.show(); delay(100);
  leds[0] = CRGB::Black; FastLED.show(); delay(100);
}

Instead, it blinks 3 leds, though I expect it to blink only the first one.

Here's how my setup code looks like:
#define DATA_PIN    1
#define CLK_PIN   5
#define LED_TYPE    WS2812B
#define COLOR_ORDER RGB
#define NUM_LEDS    60
CRGB leds[NUM_LEDS];

#define BRIGHTNESS          10

void setup() {
  delay(1000); // Power-up delay

  // tell FastLED about the LED strip configuration
  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

  // set master brightness control
  FastLED.setBrightness(BRIGHTNESS);
}

The led was bought from here: https://www.aliexpress.com/item/0-5-5M-30-60-LEDs-M-2811-Pixels-Programmable-Individual-Addressable-LED-Strip-light-WS2811/32849630888.html?spm=a2g0s.9042311.0.0.8e664c4dU4dru2

Dude, you own a WS2811 led strip, NOT a WS2812B. You need to know how to program this kind of led strip, but the line you want to change is this one: #define LED_TYPE    WS2812B

If you look at the video in your link carefully, you'll see that as per answer below, as much as the description says the LED are individually controlled, they are in fact controlled in groups of 3

@k.Cyborg tried that as well, didn't help

The description in the link of where you bought the strip says:

Description:

LED Type: 5050SMD with External IC WS2811 （1 IC control 3leds）

So, this is probably as intended.
Note the application circuits in the datasheet for the controller IC (WS2811) [Page 5] where, for 5V, you can address a single LED, but for a 12V configuration, you must group the LEDs in sets of 3.

Thanks for your answer. I got another WS2811 (https://www.aliexpress.com/item/12mm-black-Wire-WS2811-pixel-module-led-string-Chrismas-tree-50pcs-a-string-with-3pin-JST/32444382333.html?spm=a2g0s.9042311.0.0.27424c4d7GMaSp), it's 12V but individually addressable though


text:
Receiving junk values in Arduino serial monitor console
I want to send a character from a Zigbee transmitter to an Arduino Mega 2560. After the character is received, Arduino should send some data back to Zigbee. But Arduino is always receiving junk values at the console. If I send a character, suppose 'a', instead of 'a', Arduino console is always showing 'y'. It is the same for every character I send.
#include <EEPROM.h>
#include <SoftwareSerial.h>
SoftwareSerial XBee(19, 18); // RX, TX
int addr = 0;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000;  //the value is a number of milliseconds
void setup()
{

  XBee.begin(9600);
  Serial1.begin(9600);
  Serial.begin(9600);
  startMillis = millis();  //initial start time
 }
void loop()
{
  int id = 1;
  EEPROM.write(addr, id);
  if (Serial1.available()>0)
    {
      currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  if (currentMillis - startMillis >= period)  //test whether the period has elapsed
  {
    char recbyte=Serial.read();
    Serial.print(recbyte);
    // delay(1500);
    Serial1.write(id);
    Serial1.write(" 30 ");
    Serial1.write(" 99 ");
    Serial1.write(" 72 ");
    Serial1.write(" 1098 ");
    Serial1.write(" 728 ");
    Serial1.write(" 578 ");
    // Serial1.write("$");
    Serial1.write('PS=1\r\n');
    Serial1.end();
    startMillis = currentMillis;
  }
    }
}

There is a code formatting button on the editor toolbar but your code indentation is a big mess. If you are that careless then you can expect trouble. Use the edit link under your question to fix it and check the preview before you press "Save Edits".

@Transistor I got it.... For Akhila, have you tried other baud rates?

@King: I approved your edit but it's still not right. Look at the close braces at the bottom. There are other problems too. The author should fix the question.

@Transistor Oh you're right. Let me fix that. I think that automatically did that when I clicked on the code indention tool.

Whatever your actual issue is, having an EEPROM write in the the outermost uncondition part of your loop() is a mistake.

Your problem however is likely that you seem to be trying to take serial input from the PC.  Perhaps you mean to take it from Serial1 to which it seems you have the XBEE connected?

You have created a SoftwareSerial instance called XBee which is taking pins 17 and 18. You then use Serial1 which is pins 17 and 18.
You do not want, nor need, the XBee SoftwareSerial instance, since you are using hardware serial pins.  Delete it and all references to it.
Also, you are turning off Serial1 after using it, which means it will never work again:
Serial1.end();

You would only use that instruction in very very specific circumstances.  Delete it.
After checking to see if there is data available to read on Serial1 you then proceed to try and read it from Serial:
char recbyte=Serial.read();

That should be:
char recbyte=Serial1.read();

You are writing to EEPROM on every single iteration of loop:
EEPROM.write(addr, id);

It is likely that you have already killed your EEPROM.  C'est la vie...


text:
Running ADC triggered by TIMER1_COMPB
I'm trying to run ADC on channel 0 triggered by TIMER1_COMPB.
Everything seem to work ok but basic arithmetics is not working and variables inside ISR and even main loop don't get updated (x == 2 all the time)
Can somebody explain me why is it so? Even volatile variable was not changing...
Arduino UNO,
IDE v 1.8.6
#define SAMPLES_SIZE  205

const int adc_channel = 0;
const uint16_t t1_load = 0;

// 250 corresponds to 8kHz
const uint16_t t1_comp = 25000;

uint16_t samples[SAMPLES_SIZE];
volatile uint8_t samplePos = 0;

static int x = 0;

void initADC() {
  // Init ADC free-run mode; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void initTimer() {
  // Reset Timer1 Control Reg A
  TCCR1A = 0;

// Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

// Set prescaler to 8
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B &= ~(1 << CS10);

// Reset Timer 1 and set compare value
  TCNT1 = t1_load;
  OCR1B = t1_comp;

// Enable Timer 1 compare interrupt
  TIMSK1 = (1 << OCIE1B);
}

void setup() {
  cli();
  initADC();
  initTimer();
  sei();

  Serial.begin(115200);
}

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish
  cli();
  x = x + 2;
  Serial.print(samples[0]);
  Serial.print("\t");
  Serial.println(x);
//  for (int i = 0; i < SAMPLES_SIZE; i++) {
//    Serial.println(samples);
//  }
//  samplePos = 0;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
  sei();
}

ISR(ADC_vect) {
  int16_t sample = ADC;

  samples[0] = sample;
//  samplePos++;
  ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off

  if(samplePos >= SAMPLES_SIZE) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

//ISR(TIMER1_COMPB_vect) {
//}

Thanks in advance

I don't think the manual ADC conversion during initialization is _BV(ADSC)  | // ADC start should be there. Also samples should be volatile. I won't comment on the rest of the code, as it seems to be a work in progress.

Timer1 CTC mode requires you to put the CTC TOP value in OCR1A (see Table 15.5 in 328P datasheet). You didn't, so the timer is running all the way from 0 to 0xFFFF.
Timer1 ADC trigger mode requires you to put the ADC trigger value in OCR1B, which you did, so every time that the timer passes by your trigger value (t1_comp), it triggers an ADC conversion.
In short, you need to set both OCR1A and OCR1B to t1_comp.

I've found the solution, it's strange since I enabled CTC mode, but it started to work normally as soon as I reset Timer 1:
ISR(TIMER1_COMPB_vect) {
  TCNT1 = 0;
}


text:
Can't drive servo
I purchased a 20KG Digital Servo, DS3218MG with a Control Angle of 270° .
I am trying to get it to rotate with the following code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

int restingVal = 0;
int keyDown = 80;

void loop() {
  int minutesDelay = 1;
  Serial.print("Value");
  Serial.println(restingVal);

  delay(10000/2);

  myservo.write(keyDown);
  delay(500);
  myservo.write(restingVal);

}

It makes a small "clicking" noise, but it never moves.  I have tried:

powering it from the arduino using a USB cable
powering it using a power cord plugged into an electrical outlet
powering it with 4 AA batteries in a battery pack (power from the battery pack to the servo with it's ground to the Arduino's ground and the arduino plugged into an outlet)
using a 470uF capacitor and then tried a 680uF capacitor.

What am I doing wrong?  Is there something else I could look at?
update:
changed code to:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(60);
  delay(2000);
  myservo.write(120);
}

int restingVal = 0;
int keyDown = 80;

void loop() {

}

I get the same problem.
The power cord I'm using to connect the arduino is 12V DC 1A.
Here is a photo of the wiring in one configuration (with the battery pack and the wall outlet):

Orange wire goes to GND on arduino, the long green goes to ~9, yellow goes to VCC on battery pack.

It can require a peak of 1.8 A. Can the batteries do that? Try a small common servo motor.

When I replace it with a tiny servo, it works fine.

You should proivde schematic. It's unclear from given image

The batteries are perhaps too weak, the wires too thin and the breadboard can not handle those currents. Perhaps with a 5v 2a power supply, with good wires, and good connections it will work. Keep the grounds connected. @SilvioCro, I was able to follow the wires from the photo, the wiring is okay.

@Jot Look at orange wire. Looks like it's plug into GTND rail.

@SilvioCro both orange wires are gnd-wires. They connect the arduino gnd to the battery gnd to the servo gnd.

The DS3218MG servo motor is a strong servo motor and it requires more current than normal servo motors.
With a normal servo motor the peak current can be 500 mA or even 1 A. This DS3218MG is specified somewhere at 1.8 A stall current (only 80 to 100 mA during normal operation). However this YouTube video measures a stall current of 2.3 A.
During normal operation, the average current will not even be near the stall current. The peak current on the other hand can be close to the stall current. The peak current occurs at the moment that the servo motors starts to move.
You need a 5 V 2.5 A power supply for that servo motor, together with wires and connectors that are suitable for that current.
You could cheat a little by adding a capacitor. I suggest 2200 µF or 4700 µF.
It is a common mistake to underestimate the current of a servo motor. A power supply is often more expensive than the servo motor.
If a lot of torque is required, perhaps a geared motor is easier to use.

My guess is that the servo is drawing too much current from the Arduino 5v pin which can provide up to ~450mA when powered from USB and ~650mA from power jack.
Try providing 5v from an other source to the servo while keeping the GND of that power source and the Arduino common.

I guess he uses power from two differend sources

This may be a really simple question, but what kinds of other sources are available? I added the 4xAA battery pack to provide dedicated power to the servo, hoping it would help.  I thought about using a 9v battery, but the servo says "DC 4.8-6.8v"


text:
Resetting I2c Address - MLX90614
I was using my MLX90614 IRTherm sensor flawless and bought two more. I have connected two sensors serial with pull-ups to SDA --> A4 and SCL --> A5. After digging the internet I found out that I should change their default slave addresses to different addresses so that Arduino can recognize their 7-bit slave addresses.
After changing their address, now I can't read either two new serial MLX'es or my old MLX.

I might have messed up with their addresses and don't know how to
reset their addresses.
How can i connect multiple sensors/ how can i change their adress properly?

reading sensor data

#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte LED_PIN = 8; // Optional LED attached to pin 8 (active low)

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  therm.begin(0x5A); // Initialize thermal IR sensor
  therm.setUnit(TEMP_F); // Set the library's units to Farenheit
  // Alternatively, TEMP_F can be replaced with TEMP_C for Celsius or
  // TEMP_K for Kelvin.

  pinMode(LED_PIN, OUTPUT); // LED pin as output
  setLED(LOW); // LED OFF
}

void loop()
{
  setLED(HIGH); //LED on

  // Call therm.read() to read object and ambient temperatures from the sensor.
  if (therm.read()) // On success, read() will return 1, on fail 0.
  {
    // Use the object() and ambient() functions to grab the object and ambient
    // temperatures.
    // They'll be floats, calculated out to the unit you set with setUnit().
    Serial.print("Object: " + String(therm.object(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.print("Ambient: " + String(therm.ambient(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.println();
  }
  setLED(LOW);
  delay(500);
}

void setLED(bool on)
{
  if (on)
    digitalWrite(LED_PIN, LOW);
  else
    digitalWrite(LED_PIN, HIGH);
}

Setting address
#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte oldAddress = 0x5A;
const byte newAddress = 0x5B;

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  Serial.println("Press a key to begin");
  while (!Serial.available()) ;

  therm.begin(oldAddress); // Try using the old address first

  byte address;
  if (!therm.readID()) // Try reading the ID registers
  {
    // If the read fails, try re-initializing with the
    // new address. Maybe we've already set it.
    therm.begin(newAddress);

    if (therm.readID()) // Read from the ID registers
    { // If the read succeeded, print the ID:
      Serial.println("Communicated with new address.");
      Serial.println("ID: 0x" +
                     String(therm.getIDH(), HEX) +
                     String(therm.getIDL(), HEX));
    }
    else
    {
      Serial.println("Failed to communicate with either address.");
    }
  }
  else
  {
    // If the read suceeds, change the address to something
    // new.
    if (!therm.setAddress(newAddress))
    {
      Serial.println("Failed to set new address.");
    }
    else
    {
      Serial.println("Set the address to 0x" + String(newAddress, HEX));
      Serial.println("Cycle power to try it out.");
    }
  }
}

void loop()
{

}

Edit 1:
Datasheet

what does the datasheet say about resetting the address?

I couldnt find anything about it

edited the question

Page 13 of 35 in the datasheet states:

In order to provide access to any device or to assign an address to a
  SD before it is connected to the bus system, the communication must
  start with zero SA followed by low RWB bit. When this command is sent
  from the MD, the MLX90614 will always respond and will ignore the
  internal chip code information.

Supposedly, all you have to do is to connect only one device and use the address zero to read/write the registers.

I didn't understand  "low RWB bit" part

that is the read/write bit ... see figure 4 ..... the library should take care of it

I am doint what it says but not sure if zero SA = default adress

Maybe the problem is I2C speed. MLX90614 supports only 100KHz i2c. If your i2c is at 400KHz, there would be no response from MLX90614.


text:
Can SPI and serial.begin be used at the same time?
I have two modules where I want to control them through a single Arduino UNO.
I guess Serial.begin(9600) uses serial port and UART. But Im not sure about SPI.
Can I use SPI library hence the SPI communication together with serial communication(serial.begin) at the same time to communicate with two different modules?

Yes. UART and SPI are completely different things.  One uses pins 0/1, the other uses pins 11/12/13, and they use separate hardware and control registers inside the chip.

Thanks is it possible to use some other pin than pin 11 for SPI? Im currently using 8 9 10 and 11 for another module.

No. 11/12/13 are SPI. That can not be changed. Ever. It's written in stone (well, silicon, which is what most stone is made of).  You could bit-bang SPI using shiftIn() and shiftOut() on other pins if you don't need any great speed or full duplex operation if you really want.

I see then I will try to change the other module's pins.

@atomant if you're using a "Software SPI" you can use as default wired of SPI on your module. else if you're using a "Hardware SPI" you can define another pinout as SPI wire!!


text:
Vary voltage using relay. Is this possible?
I am planning to control a RGB lamp using Arduino. The lamp is 24V and I want to be able to control the brightness of the lamp. I found a relay that will let me control the 3 channels (red green and blue), but will only let me turn it on and off (Not control brightness)
I am looking for a way to control the lamp both on/off and brightness. What component will do the same as my relay, but also let me use the varying voltage from the arduino to control my 24V lamp? (Just like a transistor)
I have an external 24V powersupply along with 5V for the arduino
Thanks!

No, you can't vary the voltage with a relay. The only way you could do it with a relay would be to have a selection of different voltages available, and then use multiple relays to select which voltage is used. Less than ideal.
You need to use PWM to create a square wave with varying duty cycle. The duty cycle (the percentage of time the power is on within a given period) defines the average voltage of the output.  That PWM needs to be fed into a MOSFET which will in turn control the 24V power to the lamp.
It's exactly the same as driving RGB LED strips, except it's in the shape of a lamp not a long strip.

Should be noted that this also can control the LED to be on/off so it it removes the need for a noisy relay completely.  With the PWM output off, the LED is off, and then it can be ramped up to full brightness using higher duty cycle, all the way to fully on.

This is what I have been looking for. Do you reckon I can find a premade PCB that can do this for me on eBay (preferably from China)?

More than likely, yes.

Would you be a champ and confirm that I can vary the voltage using this: https://www.ebay.co.uk/itm/5PCS-MOSFET-Button-IRF520-MOSFET-Driver-Module-for-Arduino-ARM-Raspberry-pi/272160515977?_trkparms=aid%3D555018%26algo%3DPL.SIM%26ao%3D1%26asc%3D20140122125356%26meid%3D6d7f25afcc134e48b34f9f3d9a275cec%26pid%3D100005%26rk%3D1%26rkt%3D8%26mehot%3Dag%26sd%3D232518999508%26itm%3D272160515977&_trksid=p2047675.c100005.m1851

Probably. As long as you have the ability to switch the ground (cathode on an LED) connection. If it's a "common anode" arrangement (like most LED strips are) then that's fine.

Yes it is possible to vary voltage with a relay.  A relay is simply a 2 way 3 pole switch.

simulate this circuit – Schematic created using CircuitLab
By switching in a resistor to the supply voltage you have lowered the voltage and will dim the 24V light source.  The actual resistor value will depend on how dim you want to go.  Make sure the resistor is rated for the load you plan to place on it.

This is assuming there is already some resistance in your LED device, you would not normally want to hook a bare LED up to the supply with no resister in series.  But this is a viable option when/if you only want OFF/DIM/FULL.  The PWM signal and transistor gives more control.

That would only give on or dim, but no off...

Yes, the purpose of the schematic was to illustrate how to use a relay to adjust voltage.  It wasn't intended to be a complete schematic.

The LEDS I'm using are actually a board with 12 powerful LEDS. The lamp looks a bit like this: https://www.thomann.de/dk/stairville_quad_par_profile_5x8w_rgb_ww.htm My lamp broke (control board broke), so now I am planning on using it for a party-project and plan to take the lamp apart and keep the PCB-board where the LEDS, a heatsink, plastic housing and LED-lenses are on. I am almost sure that there are resistors on the board already. I can check to be sure, but if I burn it, it doesn't really matter. The LEDS has no value.

Do you reckon I can find a board on eBay (preferably from china) that will do this for me?

If there are no board on eBay. Perhaps I could build this and then use a transistor for the actualy powering of the LED lamps. Then I could just find a resistor that would dim so much, that the transistor barely sends power, making the LEDs look like they're off

If you want to have a variable dimmer then you'll have to go the power transistor route.  If you just want a simple On, Dim, Off circuit then a relay will work. (you'll actually need 2, one for dim/bright and one for on/off)


text:
How to Connect Dc motor with encoder (pololou) with motor shield and Arduino Mega 2560?
I tried to search a bout how to connect plolou motor with encoder to arduino mega and the motor control shield as in those pics  if any one knows how to connect those to each other please tell me

Did you try anything already, or look up a tutorial online perhaps?

A quick look on Pololu's website reveals that:
    Color   Function
  --------  --------------------------------------------
    Red     motor power (connects to one motor terminal)
    Black   motor power (connects to the other motor terminal)
    Green   encoder GND
    Blue    encoder Vcc (3.5 – 20 V)
    Yellow  encoder A output
    White   encoder B output

Thus: Red goes to M1A and Black goes to M1B on the motor shield.
The remaining wires are for the encoder and go to Arduino pins.
Green goes to Arduino GND, Blue goes to 5V, Yellow and White go to the
digital i/O pins of your choice.
Note: Your motor shield has extra 5V and GND pins so you can connect the Blue and Green wires there.


text:
How to remove the sketch for the LCD and retaining the sketch for the MPU6050?
I just got this from the internet and I only want to use the sketch for the MPU6050. Can someone help me to remove the code for the LCD? I'm sorry, I'm just noob when it comes to programming.
Here is my source: Earthquake Detector using Arduino and MPU-6050
Here is the sketch:
#include <LiquidCrystal.h>

#include <Wire.h>

#include <MPU6050.h>

#define minval -5

#define maxval 3

MPU6050 mpu;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()

{   lcd.begin(16, 2);

Serial.begin(115200);

pinMode(7,OUTPUT);

pinMode(8,OUTPUT);

lcd.print("   EarthQuake ");

lcd.setCursor(0, 1);

lcd.print("   Detector");

delay (2000);

lcd.clear();

// Initialize MPU6050

Serial.println("Initialize MPU6050");

while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))

{ Serial.println("Could not find a valid MPU6050 sensor, check wiring!");

delay(500);}

mpu.setThreshold(3);

// Check settings

checkSettings();

}

void checkSettings()

{

Serial.println();

Serial.print(" * Sleep Mode:        ");

Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

Serial.print(" * Clock Source:      ");

switch(mpu.getClockSource())

{case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and
keeps the timing generator in reset"); break;

case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external
19.2MHz reference"); break;

case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external
32.768kHz reference"); break;

case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis
gyroscope reference"); break;

case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis
gyroscope reference"); break;

case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis
gyroscope reference"); break;

case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz
oscillator"); break;

}

Serial.print(" * Gyroscope:         ");

switch(mpu.getScale())

{case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;

case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;

case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;

case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break:}

Serial.print(" * Gyroscope offsets: ");

Serial.print(mpu.getGyroOffsetX());

Serial.print(" / ");

Serial.print(mpu.getGyroOffsetY());

Serial.print(" / ");

Serial.println(mpu.getGyroOffsetZ());

Serial.println();}

void loop()

{   Vector rawGyro = mpu.readRawGyro();

Vector normGyro = mpu.readNormalizeGyro();

Serial.print(" Xraw = ");

Serial.print(rawGyro.XAxis);

Serial.print(" Yraw = ");

Serial.print(rawGyro.YAxis);

Serial.print(" Zraw = ");

Serial.println(rawGyro.ZAxis);

if(normGyro.XAxis > maxval || normGyro.XAxis < minval && normGyro.YAxis >
maxval || normGyro.YAxis  < minval && normGyro.ZAxis > maxval ||
normGyro.ZAxis  < minval)

{ digitalWrite(7,HIGH);

digitalWrite(8,HIGH);

delay(300);

digitalWrite(7,HIGH);

digitalWrite(8,HIGH);

delay(300);

lcd.clear();

lcd.print("***EarthQuake***");

delay (1000);

lcd.clear();}

else{digitalWrite(7,LOW);

digitalWrite(8,LOW);}

Serial.print(" Xnorm = ");

Serial.print(normGyro.XAxis);

Serial.print(" Ynorm = ");

Serial.print(normGyro.YAxis);

Serial.print(" Znorm = ");

Serial.println(normGyro.ZAxis);

delay(10);}

Delete all the lines that have "lcd" in them?

As Majenko states, carefully remove all lines with the lcd object in them. Due to the extremely poor formatting and indentation of the code, if you aren't careful you could lose some important syntax, such as the { and }.
Also, there is no need for the LiquidCrystal header file.
In addition, there is a typo in the posted code (it is beyond me why the author would post uncompilable (and hence untested) code), in this line:
case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break:}

Here is the code with the lcd related lines stripped out, correctly formatted and indented, with the typo fixed:
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

The page that you got your code from does not specify which MPU6050 library to use. It is not the library by Jeff Rowberg, as linked to from the Arduino Playground, MPU-6050 Accelerometer + Gyro. It is in fact this library, MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.

Thank you dude! Let me try your recommendation. I'll give some feedback later :D

You're welcome. Please don't forget to upvote and mark the answer as accepted (using the little green tick), if it helps you. Cheers.

@HamdanieImpa - don't forget to upvote


text:
Arduino LCD Brightness
I've made this small device that uses a ultrasonic sensor to tell how far away an object is and display it on a 16x2 display.
Here's the code:
#include <LiquidCrystal.h>

int Contrast=100;
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 7;
const int echoPin = 8;
// defining variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
  analogWrite(6, Contrast);

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

// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration / 29 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
  lcd.setCursor(0, 0);
  lcd.print("Distance: ");

 lcd.setCursor(0, 1);
  lcd.print(distance);
  delay(100);
  lcd.clear();
}

Every thing works fine apart from the fact that the lcd backlight is too dim(barely visible). I tried looking online but is there any way i can get max brightness without a potentiometer? I do have resistors , can i use them somehow?

Please share your wiring diagram so we can help you. Contract control is usually done using a potentiometer, but can vary depending on the LCD model.

The back light of the LCD is just an LED connected through a resistors on the A (15) and K (16) pins on the display. The LED doesn't require an external resistor since according to the datasheet there is a build in resistor on the board itself. If you aren't using any external resistors and applying a constant voltage of 5V and the screen is still dim than this means that the led is most likely dead and you would need to replace the back light panel.
If you are talking about the contrasts of the display. Than I would recommend you to hook up the contrast pin to a PWM pin on the Arduino and by using analogWite to tune the display in order to get the desired value of contrast.

Most character LCDs have a series resistor but not all. It is a manufacturing option, Typically LCDs available for the hobby market do, but this should be confirmed prior to use.


text:
Send file post request from the ESP32
Is it impossible to send a file post request from the ESP32 using the SPIFFS file system? ESP32 freezes while sending.
Code example:
File file = SPIFFS.open("/Images/test.bmp", FILE_READ);

String start_request = ""; String end_request = "";
start_request = start_request +
                "\n--AaB03x\n" +
                "Content-Disposition: form-data; name=\"userfile\"; filename=\"CAM.bmp\"\n" +
                "Content-Transfer-Encoding: binary\n\n";
end_request = end_request + "\n--AaB03x--\n";
uint16_t full_length;
full_length = start_request.length() + file.size() + end_request.length();

WiFiClient client;
if (!client.connect("server_name", 80)) {
  Serial.println("Connected FILED!");
  return;
}

Serial.println("Connected ok!");
client.println("POST /Home/Index HTTP/1.1");
client.println("Host: example.com");
client.println("User-Agent: ESP32");
client.println("Content-Type: multipart/form-data; boundary=AaB03x");
client.print("Content-Length: "); client.println(full_length);
client.print(start_request);

while (file.available()){
  client.write(file.read());
}

Serial.println(">>><<<");
client.println(end_request);

HTTP requires an empty line after the headers. add an empty line with client.println() before client.print(start_request);

One can send a POST request with data fields appended with binary data as shown in the code below. The presented code was made to make a POST request to a Dataverse repository, however, can be easily adapted to any other POST request. Finally, the code below is optimized for Tensilica's Xtensa LX6/7 microprocessors, vis-a-vis ESP32.
The full code can be found here:
https://github.com/aeonSolutions/openScienceResearch-Smart-DAQ-Device-able-to-Upload-Live-Experimental-Sensor-Data-to-a-Data-Repo
// *********************************************************
//            Upload Dataset to Harvard's Dataverse
// *********************************************************
void UploadToDataverse() {
  //Check WiFi connection status
  if(WiFi.status() != WL_CONNECTED){
    mserial.printStrln("WiFi Disconnected");
    if (connect2WIFInetowrk()){
      UploadToDataverse();
    }
  }
  // Start sending dataset file
  File datasetFile = FFat.open("/"+EXPERIMENTAL_DATA_FILENAME, FILE_READ);
  if (!datasetFile){
    mserial.printStrln("Dataset file not found");
    return;
  }

  String boundary = "7MA4YWxkTrZu0gW";
  String contentType = "text/csv";
  // DATASET_REPOSITORY_URL = "/api/files/:persistentId/replace?persistentId=" +PERSISTENT_ID;
  DATASET_REPOSITORY_URL =  "/api/datasets/:persistentId/add?persistentId="+PERSISTENT_ID;

  String datasetFileName = datasetFile.name();
  String datasetFileSize = String(datasetFile.size());
  mserial.printStrln("Dataset File Details:");
  mserial.printStrln("Filename:" + datasetFileName);
  mserial.printStrln("size (bytes): "+ datasetFileSize);
  mserial.printStrln("");

  WiFiClientSecure client;

  int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator)
  char SERVER_URL_char [str_len];    // Prepare the character array (the buffer)
  SERVER_URL.toCharArray(SERVER_URL_char, str_len);    // Copy it over

  client.stop();
  client.setCACert(HARVARD_ROOT_CA_RSA_SHA1);
  if (!client.connect(SERVER_URL_char, SERVER_PORT)) {
      mserial.printStrln("Cloud server URL connection FAILED!");
      mserial.printStrln(SERVER_URL_char);
      int server_status = client.connected();
      mserial.printStrln("Server status code: " + String(server_status));
      return;
  }
  mserial.printStrln("Connected to the dataverse of Harvard University");
  mserial.printStrln("");
  // We now create a URI for the request
  mserial.printStr("Requesting URL: ");
    mserial.printStrln(DATASET_REPOSITORY_URL);

  // Make a HTTP request and add HTTP headers
  // post header
  String postHeader = "POST " + DATASET_REPOSITORY_URL + " HTTP/1.1\r\n";
  postHeader += "Host: " + SERVER_URL + ":" + String(SERVER_PORT) + "\r\n";
  postHeader += "X-Dataverse-key: " + API_TOKEN + "\r\n";
  postHeader += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n";
  postHeader += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
  postHeader += "Accept-Encoding: gzip,deflate\r\n";
  postHeader += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
  postHeader += "User-Agent: AeonLabs LDAD Smart DAQ device\r\n";
  postHeader += "Keep-Alive: 300\r\n";
  postHeader += "Connection: keep-alive\r\n";
  postHeader += "Accept-Language: en-us\r\n";

  // jsonData header
  String jsonData = "{\"description\":\"LIVE Experimental data upload from LDAD Smart 12bit DAQ \",\"categories\":[\"Data\"], \"restrict\":\"false\", \"tabIngest\":\"false\"}";
  String jsonDataHeader = "--" + boundary + "\r\n";
  jsonDataHeader += "Content-Disposition: form-data; name=\"jsonData\"\r\n\r\n";
  jsonDataHeader += jsonData+"\r\n";

  // dataset header
  String datasetHead = "--" + boundary + "\r\n";
  datasetHead += "Content-Disposition: form-data; name=\"file\"; filename=\"" + datasetFileName + "\"\r\n";
  datasetHead += "Content-Type: " + contentType + "\r\n\r\n";

  // request tail
  String tail = "\r\n--" + boundary + "--\r\n\r\n";

  // content length
  int contentLength = jsonDataHeader.length() + datasetHead.length() + datasetFile.size() + tail.length();
  postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";

  // send post header
  int postHeader_len=postHeader.length() + 1;
  char charBuf0[postHeader_len];
  postHeader.toCharArray(charBuf0, postHeader_len);
  client.print(charBuf0);
  mserial.printStr(charBuf0);

  // send key header
  char charBufKey[jsonDataHeader.length() + 1];
  jsonDataHeader.toCharArray(charBufKey, jsonDataHeader.length() + 1);
  client.print(charBufKey);
  mserial.printStr(charBufKey);

  // send request buffer
  char charBuf1[datasetHead.length() + 1];
  datasetHead.toCharArray(charBuf1, datasetHead.length() + 1);
  client.print(charBuf1);
  mserial.printStr(charBuf1);

  // create buffer
  const int bufSize = 2048;
  byte clientBuf[bufSize];
  int clientCount = 0;

  while (datasetFile.available()) {
    clientBuf[clientCount] = datasetFile.read();
    clientCount++;
    if (clientCount > (bufSize - 1)) {
        client.write((const uint8_t *)clientBuf, bufSize);
        clientCount = 0;
    }
  }

  datasetFile.close();

  if (clientCount > 0) {
      client.write((const uint8_t *)clientBuf, clientCount);
      mserial.printStrln("[binary data]");
  }

  // send tail
  char charBuf3[tail.length() + 1];
    tail.toCharArray(charBuf3, tail.length() + 1);
    client.print(charBuf3);
  mserial.printStr(charBuf3);

  // Read all the lines of the reply from server and print them to mserial
    mserial.printStrln("");
    mserial.printStrln("Response Headers:");
  String responseHeaders = "";

  while (client.connected()) {
    // mserial.printStrln("while client connected");
    responseHeaders = client.readStringUntil('\n');
    mserial.printStrln(responseHeaders);
    if (responseHeaders == "\r") {
      mserial.printStrln("======   end of headers ======");
      break;
    }
  }

  String responseContent = client.readStringUntil('\n');
  mserial.printStrln("Harvard University's Dataverse reply was:");
  mserial.printStrln("==========");
  mserial.printStrln(responseContent);
  mserial.printStrln("==========");
  mserial.printStrln("closing connection");
  client.stop();
  }


text:
Faster way to parse a HTTP response in Arduino
I send a GET http request to a server and get following data back.
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 16 Nov 2018 16:30:05 GMT
Connection: close

35
{
  "uuid" : "13b29524-7e12-48fb-bbf9-4396aefff45d"
}
0

with the following code I get the header info and the body.
void parseResponse() {
  boolean headerEnd = false;
  byte lineCount = 0;
  String line;
  char endOfLine[] = "\r\n";
  while (1) {
    if (client.available()) {
      char inChar = client.read();
      if (!headerEnd && line.endsWith(endOfLine)) {
        // Just save the first then headers
        if (lineCount == 10) {
          headerEnd = true;
        } else {
          headers[lineCount] = line;
          line = "";
          lineCount++;
        }
      }

      if (line.endsWith("close")) {
        line = "";
        headerEnd = true;
      }

      if (headerEnd && line.endsWith("}")) {
        line.toCharArray(response, sizeof(response));
        client.stop();
        break;
      }

      line += inChar;
    }
  }
}

this thakes 60 - 70ms to parse. Is there a faster way to parse? I think that's slow, for so little text, in the world of AVRs.

That doesn't look like C...

The Arduino language is not C, but C++ with some non-standard extensions, such as boolean and byte for bool and unsigned char respectively. Please retag your question.

char lastChar = ""; should be char lastChar = '';. "" is a string, not a char.

But the lastChar variable is never used for anything, why do you keep assigning it?

@Barmer . Right, I have removed it.

there are nice functions inherited from Stream class
int parseResponse(char uuid[], int size) {
  if (!client.find("HTTP/1.1")) // skip HTTP/1.1
    return -1;
  int st = client.parseInt(); // parse status code
  int l = -1;
  if (st == 200 && client.find("\"uuid\" : \"")) {
    int l = client.readBytesUntil('"', uuid, size);
    uuid[l] = 0; // terminate the C string
  }
  return l;
}

Thanks for the note "client.readBytesUntil". I did not find that under Arduino Client.
https://www.arduino.cc/en/Reference/ClientConstructor but there, https://www.arduino.cc/en/Reference/StreamReadBytesUntil. :S. It's now 20ms faster!


text:
Arduino Leonardo keyboard.print keeps printing equal sign
I am currently working on a DIY controller for Train Sim World. I am relatively new to the Arduino and the C programming language. My code is structured to look for button presses or PS2 joystick inputs and print a specific character for each button. I have also included a kill switch on pin 3. However when I run the code and open Notepad to see the results, the Arduino keeps printing the = character even if pin 3 is not pulled low. After I pull pin 3 low and press a button, there is a delay of about two seconds during which the = character keeps being printed over and over again, and after these 2 seconds elapse the Arduino prints the character attributed to the button several times before returning to printing = over and over again.
What can I do to fix this?
#include <Keyboard.h>

void setup() {
    pinMode(0, INPUT_PULLUP);
    pinMode(1, INPUT_PULLUP);
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    pinMode(4, INPUT_PULLUP);
    pinMode(5, INPUT_PULLUP);
    pinMode(6, INPUT_PULLUP);
    pinMode(7, INPUT_PULLUP);
    pinMode(8, INPUT_PULLUP);
    pinMode(9, INPUT_PULLUP);
    pinMode(10, INPUT_PULLUP);
    pinMode(11, INPUT_PULLUP);
    pinMode(12, INPUT_PULLUP);
    pinMode(13, INPUT_PULLUP);
}
bool pantograph = 0;
void loop() {
    while (digitalRead(3) == LOW) {
        Keyboard.write("M");
        if (digitalRead(1) == LOW) {
            Keyboard.write("W");
        } else if (digitalRead(2) == LOW) {
            Keyboard.write("S");
        } else if (digitalRead(0) == LOW) {
            Keyboard.write("Q");
        } else if (digitalRead(5) == LOW) {
            Keyboard.write("Y");
        } else if (digitalRead(6) == LOW) {
            Keyboard.write("T");
        } else if (digitalRead(7) == LOW) {
            Keyboard.write("G");
        } else if (digitalRead(8) == LOW) {
            Keyboard.write("K");
        } else if (digitalRead(9) == LOW) {
            Keyboard.write("Z");
        } else if (digitalRead(10) == LOW) {
            if (pantograph == 0) {
                Keyboard.write("P");
            } else {
                Keyboard.write("O");
            }
        } else if (digitalRead(11) == LOW) {
            Keyboard.write(9);
        } else if (digitalRead(12) == LOW) {
            Keyboard.write("N");
        } else if (digitalRead(13) == LOW) {
            Keyboard.write(32);
        } else if (analogRead(A0) > 700) {
            Keyboard.write(93);
        } else if (analogRead(A0) < 200) {
            Keyboard.write(91);
        } else if (analogRead(A1) > 700) {
            Keyboard.print(39);
        } else if (analogRead(A1) < 200) {
            Keyboard.print(59);
        } else if (analogRead(A2) > 700) {
            Keyboard.print("A");
        } else if (analogRead(A2) < 200) {
            Keyboard.print("D");
        }
    }
    delay(1000);
}

I'm not sure if it'd cause it but I think you should have a Keyboard.begin() at the end of the setup function.

@PeterJ unfortunately it didn't work. Same thing happens as I've described before. However by moving the delay inside while the program slows down to printing once every second, as expected, and the buttons' associated characters only print once, but the program still prints the "=" over and over again

did you read my answer?

The method write with one parameter takes char not string. Use write('W'), not write("W");


text:
Flashing an ATtiny85 with a NodeMCU?
I recently purchased a Digispark for some of my smaller electronics projects. After it initially being a great little board, I soon found myself unable to flash the board in the same way I had done before i.e. according to the method described here. I am still unsure as to why the previous flashing method stopped working but have been unable to overcome the issue, nor have I found many other accounts of similar problems online.
After a period of frustration, unable to even find a way to reset the board, it dawned upon me that I may be able to use an Arduino to flash the board as seen here. However, the issue is that all the tutorials I could find online assumed that an Arduino Uno could be easily accessed, which is not the case for me. Despite this, I do have a few NodeMCUs hanging around and would love it if I could use them to flash the Digispark.
My question is: how exactly would I flash the Digispark using a NodeMCU (if it is even possible)?
P.S. Whilst I am aware that the Digispark board has a number of other components aside from the ATtiny85 chip, the pinouts (not the USB) of the board allow for direct interfacing with the chip.
Thank you in advance for any help,
Kind regards,
Rocco

Possible duplicate of using esp8266 feather to burn bootloader on redboard

@Juraj I agree that my question is similar to the one linked. However, I would still like someone to confirm that this is the case for my specific situation. I.e. for an ATtiny85 chip as opposed to an 'Arduino redbird'. If so, is this due to the nature of the NodeMCUs or is it a specific issue with the two components in question?

IIRC the NodeMCU is a 3.3V device and the ATtiny is 5V so that could cause problems.

It can be done. Your Digispark has SPI pins, which are ISP pins. For the esp8266 there is an ESP8266AVRISP library for OTA upload to AVR. You can use the example of the library.
You must wire the SPI pins and ground together. Wire reset pin of Digispark to io 5 (D1) of NodeMcu. You should use level conversion, but esp8266 tolerates 5 V TTL (not recommended for long term). Do not wire the SS pin.

Thank you for your reply. I still have a few questions; what is the 'Bluno' you are referring to? Would you be able to give a more step-by-step set of instructions of how to do this as I am unclear as to what exactly you mean. If possible, please could you include a wiring diagram for the digispark and NodeMCU? Thanks once again

@Rocco, sorry Bluno is a very similar small board. I fix it in the answer

Thanks for your answer, I'll give that a go when I next get the opportunity. Just two quastions: would I only need to use level conversion between the Digispark Reset and D5 or would I need it between all connections or what? Also, I can't find clear instructions for how to download avrdude tool online, is there a simple git clone or something?

Also, you mean wire the SPI pins of the NodeMCU and digispark together and then the ground of each board together as opposed to wiring the SPI pins to ground? I would also assume the digispark shouldn't need to be plugged in? Finally, would you be able to include a diagram showing exactly which wires are meant to go where for clarity if possible as I am not familiar with SPI? Thank you once again

reset and MISO are candidates for level conversion. the instructions are on the link to library in the answer

Still a few things I'm not quite sure about: As for the level shifting, is that FROM 3v to 5V or the other way round? I.E. does the digispark need external powering? It would be really great if you could include a full wiring diagram in your answer as it would answer all my remaining questions. Best

level conversion should protect the esp8266 from 5 V. I connected many times 5 V logic to esp8266. It is not like there is some real current. It is only pullup for logic level. You can power the Digispark from 5 V pin of NodeMcu. https://raw.githubusercontent.com/wiki/jandrassy/arduino-firmware-wifilink/images/wemos-nano-spi.jpg

the truth is, you should use level conversion for the 3.3 lines too, because AVR datasheet has that 5 V AVR needs at least 3.7 V as HIGH. but somehow 3.3 V is in tolerance. and the breadboard wiring of SPI with level conversion is spaghetti https://raw.githubusercontent.com/wiki/jandrassy/arduino-firmware-wifilink/images/wemos-nano-ls-spi.jpg

Ah I see, thank you for your reply and your detailed photos. To clarify, in your photo, thr D1 Mini represents the digispark or the other way round? Thanks once again for all your help!

D1 is esp8266 and Nano is AVR. on photos is SPI wiring not only for ISP, but for a networking firmware where AVR is master and esp8266 is slave. but the Nano can be flashed over esp8266. additionally to ISP  wiring there is CS pin, both resets and one more signal connection for the firmware


text:
Make an Xbox 360 controller with an Arduino Uno
I was thinking of making a custom Xbox 360 controller (racing wheel) with the Arduino Uno plugged into the Xbox. How would I emulate the buttons/triggers on the original controller with the Arduino? Is there a library that can help me do this?

you may or may not be able to do it with your Uno .... it depends on the kind of the USB to serial converter the board uses ..... what kind of a chip do you see near the USB connector?

I googled a bit at this topic. It seems, that at least most (if not all) Xbox360 controller emulations/DIY builds cannot be used with the Xbox360 itself, but only with a PC. The reason is, that a Xbox controller incorporates an extra security chip, which performs some form of handshake, before the console really accepts the controller. Some sites stated, that some chinese producers cracked that chip, to produce knockoffs, but I couldn't find a hint to a published crack. It might exist,  you may have to google much. If you find something, this will most likely be no beginner project.

If you decide, that using it only with a PC is ok, you should look at Arduino boards, that have a configurable USB connection, so that the Arduino can behave as a HID device. This is also possible with the Uno, but not as good and only with reflashing the USB to serial controller.

Thanks for pointing me in the right direction. Would I be able to emulate it with something more powerful like a raspberry pi? I also searched some more and found some stuff about PID and VID, is this what you meant by the security key or is there more to it? P.S here is a tutorial I was referring: link. There was also this repo on the "falcon panel"

PID and VID are definitions for the USB connection. They are used to identifiy the type of a device, that is connected via USB. Seems, that it can be changed. But despite that it will still just advertise itself as HID device. If you google for Xbox360 controller emulation, you find many people, who talk about a real extra chip on the controllers pcb, which does some kind of secret handshake. Without a real crack for this, you won't be able to get any DIY controller working with the Xbox360. Microsoft uses the security chip to actively prevent others from doing this.

VID and PID are just numbers that are associated with a Vendor and Product. They don't define what it is, only who it is and what it's called.  What it does is defined by the device descriptor - a large block of data that defines protocols, endpoint types, block sizes, etc.

The GIMX open source project may help. The GIMX adapter plugs into the console and a computer running Windows or Linux (raspberry pi has experiemental support). A real xbox controller must be plugged into the computer so it can do the xbox authentication. Off the shelf or custom controllers plugged into the same computer can talk to the Xbox console.

Ohh... That looks interesting. This might work! Thanks for the suggestion. Will let you know if this works out.

Arduino Uno's do not have a native USB Connection. However, if you use an Arduino Leonardo or Pro Micro, you can use MHeironimus's Joystick library, However I am not sure if they are specifically compatible with the XBox.
https://github.com/MHeironimus/ArduinoJoystickLibrary


text:
Connect a button to bluetooth board and comunicate with Android
I want to create a small device, just a button that sends its status to an Android application through Bluetooth.
I bought a Bluno Beetle, but the information it exposes to Bluetooth cannot be modified from Arduino code, so I have no way to send the button status to the Android App, rookie mistake I guess.
Could you please tell me which model of arduino+bluetooth should I purchase to do this ?

buy a bluetooth button like this https://www.amazon.com/iBOLT-Bluetooth-distance-Customize-commands/dp/B00R3H4II8

"access features of compatible apps" seems suspicious, also I can´t find anywhere if it can be used on custom Apps.

it is unclear why the Bluno Beetle is unsuitable for your project .... please post the code that you tried .......... the Bluno Beetle is an arduino with a bluetooth module and you are asking about replacing it with another arduino and another bluetooth module

I connected a button to the Bluno Beetle and I want the Android App to know when the button is pushed and when is not. I can´t change the characteristic the Bluno Beetle exposes on the Bluetooth Service from the code, so I cannot send the button status to the Android App.

have you seen  this page? ... https://www.dfrobot.com/blog-283.html

Yes, what I am supposed to be missing ?

many different Bluetooth buttons are in shops.

The beetle supports both acting as HID device or as a serial interface. You can use both ways to interact with a button (though using as HID is better, because you can even control other apps with it).

For your project you can buy cheap Arduino Nano, or even Mini(programmer needed). For BT module buy HM10. It's cheap and it supports Bluetooth Low Energy.

but that is exactly what Bluno Beetle is. a 328p plus CC2540

Why he asked then what he should buy

because he doesn't understand how it works

Hi Juraj,
If you understand how it works, could you explain to me how can I get the status of a button connected to the bluno to an android app connected to the bluno by Bluetooth ?

@Grefu, you must use @ to get a user notified. the manufacturer has examples. jsotola posted a link in comments to  the question


text:
ESP8266 ASCII to HEX convertion and checking
I am trying to convert ASCII to hex and check if the hex is equal to that hex that I want.
For example:
1B 42 05 it means B in ASCII, I need to check if that hex is equal to 1B 42 05.
Here I need to send converted hex code from ASCII code by using SoftwareSerial.
Example:
02 20 2D 33 30 32 35 30 20 6B 67 0D 0A 03

I have to convert to
-30250 kg

you can't convert 1B to HEX because it IS HEXadecimal representation of a number. it is like if you would say that you need to convert 42 to a decimal number. you can convert string "1B" to a byte value.

1B 42 05 is more than just a B ...... please consult ASCII tables

Your example looks like a serial protocol string... 02 20 2D 33 30 32 35 30 20 6B 67 0D 0A 03 corresponds to <stx> -30250 kg<cr><lf><etx>. So you have to do a bit more than just hex to ascii

A little explanation about HEX and ASCII:
About HEX
Raw computer data consists of zeros and ones. For humans it is difficult to read a (long) row of zeros and ones. You can represent such a row (of a certain length) by a decimal number, but then the relation with the underlying bits is not directly clear. For this reason the hexadecimal (HEX) representation is used (hexadeca comes from Greek and means 16.
Four bits can represent 16 different situations (= 16 different combinations of zeros and ones). The HEX digit belonging to each combination is:
0000 = 0; 0001 = 1; 0010 = 2; 0011 = 3; 0100 = 4; 0101 = 5; 0110 = 6; 0111 = 7
1000 = 8; 1001 = 9; 1010 = A; 1011 = B; 1100 = C; 1101 = D; 1110 = E; 1111 = F
When you memorize these 16 cases (from which the first 10 are easy because it is juist binary counting), you know immediately which bit-pattern belongs to a hexadecimal number and vice versa. For example: the HEX value 5A = 01011010.
About ASCII
Computer data contain not only numbers, but also text. As the computer can only handle bits (zeros and/or ones) we have to decide how letters (characters) are presented by bit patterns. And preferably in a standardized way, in order that different computers can handle each others text. Unfortunately there is more than one standard, but one that is very much used is the ASCII standard (see: https://en.wikipedia.org/wiki/ASCII).
The ASCII standard uses 7 bits codes and defines not only characters but also 'control codes' e.g. for 'line feed' and 'carriage return'. Often these 7 bits are stored in one byte (with the leftmost 8th bit set to 0) and can than be represented by two HEX digits.
Without further information nobody can tell what a row of bits represents. That's one of the reasons datatypes are used. They tell us what the row of bits represents and how many bits (or bytes) are used for the representation.
So the HEX representation of your row of 3 bytes is "1B 42 05" and, when these are characters, could stand for (look at the ASCII table): "ESCAPE B ENQ". In which 'ESCAPE' and 'ENQ' are control codes which meaning depends on the communication protocol.
The second row (of 14 bytes) could stand for: "STX SPACE - 3 0 2 5 0 SPACE k g CR LF ETX". STX and ETX stand for 'START OF TEXT' and 'END OF TEXT'. 'LF' stands for 'LINE FEED' and 'CR'stands for 'CARRIAGE RETURN'.
I hope that with this explanation you have a better idea about HEX and ASCII and that you now will be able to figure out how to handle your data.

Converting an ASCII HEX digit is simple enough.  Here's a little function I use all the time:
uint8_t h2d(char hex) {
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

Pass it a single HEX digit as a char variable and it returns a number between 0 and 15.
To convert a pair of characters into an 8-bit value just call it twice with each character, shift one of them 4 bits to the left, and OR them together.  For instance:
uint8_t h2d2(char h1, char h2) {
    return (h2d(h1)<<4) | h2d(h2);
}

That would give you a number between 0 and 255 (or 016 and FF16, or 08 and 3778...)
How you receive and split up the incoming data properly is a whole other topic, but this and this could probably help you.


text:
How can I get my (Arduino) Pro Micro schematic to allow me to program it through GPIO instead of USB
I'm trying this project so far I've got the schematic of a Pro Micro, which is powered through GPIO from a Raspberry Pi Zero, and want to remove the micro usb connection and able to flash it using an avr programer and a few pins.
How do I get to Achieve that? also the Pro Micro is getting D+/D- from the the raspberry's D+/D- pads as well. Schematic below for reference.

Yes, you can program Pro Micro with programmer.

you cannot power the board through GPIO pins ... those are for input/output only

if Micro is connected to PI with USB, you can use it for serial upload to Micro from PI with avrdude.

I would like to understand what you want to build. PI has GPIO so why to attach a Micro?

Please provide an explanation of what you mean by this: "flash it using an avr programer and a few pins", and why you want to do that.

It's unfortunate m1gu3 wouldn't bother to answer my question. I believe I might provide a useful answer. In the latest avrdude 6.3.0-arduino14 from Arduino, a linuxspi programmer option was added. This allows you to use an RPi as an ISP programmer. You can find a general overview in the 2nd half of https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer and some more technical discussion at: https://github.com/per1234/Arduino_Boards/pull/1. Currently it only works if run as superuser. That bug should be fixed in the next avrdude release, after which I will release a package.

@per1234, thanks for getting back at me with this. Actually the whole goal of the project is to have this arduino compatible board that can house a button matrix, screen, battery and raspberry pi, such like the PocketChip. I want to avoid having this particular USB for the arduino part since the power supply will have a usb for charging. Hope that answers your question.

Welcome to arduino.stackexchange.
You can program your ATmega32U4 on at least two ways:
1. Use Arduino's bootloader and D+/D- pins. This way you won't need an external programmer. Try search for phase "programming ATmega32U4 with bootloader".
2. Use ISP (In-System-Programming) method. In this case you can use your avr programmer. To do so you also need access to PINs named Reset, MISO, MOSI, SCLK. See this link or this one
As always, the important read is ATMega32U4 datasheet.

Awesome, links and everything. Thanks a lot!

Why don't you buy a pi zero to USB  add-on board?
You can stack the pi on top and plug it into a normal female USB port on your computer.
The USB board has some pins that connect to the solder points of the mini USB, so you can delete all the connectors you won't need.
Other option is to solder a wire to the pi and extend the connector with a cable.
I'm not shire, if you can program the pi true its serial pins.
USB is a serial connection after all. So I think this should be possible

Hey @DAM, your idea sounds very doable but the main concept of this project is to have a mobile rPi, I want to flatten it most I can. But thanks for your input I might use some of those ideas too!

An avr programmer uses the ISP interface to program a chip. For this you need the pins for MOSI, MISO, SCK and Reset. Of course you have also to provide power to the board through Vcc and ground.
I'm not sure, if it's OK to keep the USB connection while programming via ISP, but since you want to remove that connection either way, this isn't a problem for you. You can remove the USB connection completely (no D+ or D- connection).
Note: when you are programming the Arduino Micro via ISP without also burning the bootloader, you won't be able to use USB for programming anymore, until you burn the bootloader again.

Sounds good, so basically a 4 pin header with MOSI, MISO, SCK and RST will do the trick. And yeah its exchanging data with the rPI without the USB plug I guess. Sorry not an expert on this kind of things, thanks!

Depending in the voltage, that the Micro runs on, you may need a level shifter, so that nothing gets damaged due to too high voltage


text:
What is 1.8 to 5.5 VDC?
I'd like to buy a standalone capacitive touch sensor to create interactive art.  It says it is powered by 1.8 to 5.5 VDC.  I am new to arduinos - what type of battery can I buy to power this sensor?  I'm hoping it's simple, not complicated. Thanks!

Welcome, Sarah. That means that you can power your sensor with anything that delivers at least 1.8 volts of direct current upto at most 5.5 volts. Depending on the model of your Arduino, it has either 3.3V and/or 5V outputs for powering other components and its pin are expecting signals of the same voltage level.

VDC is an abbreviation for volts DC. DC means Direct Current you can read more a detailed explanation about it here. Basically what powered by 1.8 to 5.5 VDC means is that the DC voltage on the input of your sensor can vary from 1.8 volts up to 5.5 volts. So you can use either 3 AAA batteries in series since the sum of their voltage will be: 1.5V * 3 = 4.5V what is in the range of recommended voltages for your sensor. Also, you can use a Li-ion battery in order to power your sensor since the voltage of this type of battery is 3.7V it is also in the range of recommended voltages for your sensor. However you would need an additional charge/discharge module in order to recharge and keep the battery in a good condition. You can read more about it on the web.

do you have a 5V power supply?
If you do I'd suggest connecting your arduino to the power supply and then you can power your sensor with a pin of the arduino.


text:
Reading analog value while generating PWM signal
I'm trying to generate dim two LED strips simultaneously by generating two PWM signals based on potentionmeter value. The pot sets how bright each of the LED strips will be. To drive this I'm using Arduino Pro Micro equipped with Atmel 32u4 chip.

I'm using following code:
int sensorValue = 0;
int outputValue = 0;

void setup() {
}

void loop() {
  sensorValue = analogRead(A0);

  outputValue = map(sensorValue, 0, 1023, 0, 255);
  analogWrite(5, outputValue);
  analogWrite(6, 255 - outputValue);

  delay(2);
}

The problem is, the analogRead never returns 1023 when the pot is fully open. The value is always around 980. This itself would not be a big deal.
The main issue is that the analogRead is incredibly noisy. The value returned for the maximum position is in range of [940-1020].
When I don't use the analogWrite to generate PWM, the problem goes away an the input is crystal clear in range [0-1023] as expected.
I have tried to turn off the PWM before reading the value in, but this generates flicker, as the LEDs are temporarily off.
Is there any HW or SW solution to this? I don't mind writing some assembly if required.

It sounds like fluctuations in the power caused by the switching of the LEDs.  Add some large capacitors across the power near the LEDs.

Have you checked your power source? If it is a switching source you might want to add some capacitors to cancel out the ripple. I suggest you use a scope. If you don't have a scope just connect your voltage source to A1 and analogread(A1).

Try adding some delay, say sample the pot just 10 or 20 times a second, vs the ~500 times a second that your code would do now. That gives the PWM outputs a chance to perform vs being constantly given new values to use.

@Majenko it was an issue with the power source. It's an USB led strip, so I was powering it through Arduino, which was a bad idea as it turns out.

It was an issue with the power source. It's an USB led strip, so I was powering it through Arduino, which was a bad idea as it turns out.
When I have added external power source to the circuit everything started working correctly.


text:
How to convert string to byte array on arduino
Well my title pretty much sums it up , how to convert string to byte array? i cant find any usefull code

You asked this already and I answered it here https://arduino.stackexchange.com/questions/58105/http-request-as-bytes/58106#58106

Well, the C string is already byte array.
If you mean Arduino's String class, then it has c_str() method.
Both needs reinterpret cast to const byte pointer:
byte const* byteArray = reinterpret_cast<byte const*>(yourString.c_str());

Yeah the Arduinos String , i did not understand the last line , i am sorry if i post stupid questions and i am new to all of this so i dont have experience

What did you ment by reinterpret cast to const byte pointer?

@Ivanh23 There is a difference between char and byte signedness so it must be cast by reinterpret_cast. I've added it into the answer.  But be warned, it's valid only as long as the yourString exists and wasn't changed. If you change the yourString, you have to get correct pointer again.